我是 Python 和 Tkinter 的初学者。我试图将图像放在左上角,但我做不到。我尝试使用属性“justify”和“Anchor”。这是我的代码:
logo_upb = PhotoImage(file="upb.gif")
label = Label(root, image=logo_upb, justify=LEFT)
label.image = logo_upb
label.place(bordermode=INSIDE, x=0, y=0)
label.pack()
如果有任何解决方案,我将不胜感激。
最佳答案
您尝试过网格几何管理器吗?
网格几何管理器将小部件放入二维表中。您会惊讶地发现使用网格管理器比使用打包器要容易得多。
让我们通过这个例子来展示网格的功能。使用包管理器创建此布局是可能的,但它需要许多额外的框架小部件。
但使用网格几何管理器,您还可以让小部件跨越多个单元格。 columnspan
选项用于让小部件跨越多于一列 rowspan
选项则让它跨越多于一行
以下代码创建所示的布局:
label1.grid(sticky=E)
label2.grid(sticky=E)
entry1.grid(row=0, column=1)
entry2.grid(row=1, column=1)
checkbutton.grid(columnspan=2, sticky=W)
image.grid(row=0, column=2, columnspan=2, rowspan=2,
sticky=W+E+N+S, padx=5, pady=5)
button1.grid(row=2, column=2)
button2.grid(row=2, column=3)
因此,您的答案将与
import Tkinter as tk
root = tk.Tk()
img = tk.PhotoImage(file ="somefile.gif")
panel = tk.Label(root, image = img)
panel.grid(row=0,column=1)
root.mainloop()
我个人的建议是使用Python Imaging Library (PIL)链接:http://www.pythonware.com/products/pil/为游戏添加更多支持的文件格式。支持的文件格式列表:http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html
在此示例中,我使用了 tkinter 本身不支持的 .jpg 文件格式,但由于我们使用的是 PIL,所以一切都可以正常工作。
import Tkinter as tk
from PIL import ImageTk,Image
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open("somefile.jpg"))
panel = tk.Label(root, image = img)
panel.grid(row=0,column=1)
root.mainloop()
警告:切勿在同一个主窗口中混合网格和包。 Tkinter 会很高兴地用你的余生尝试协商一个双方经理都满意的解决方案。不要等待,而是终止应用程序,然后再次查看您的代码。一个常见的错误是对某些小部件使用了错误的父级。
关于python - 在 Tkinter 中加载图像的角落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16312933/