Tkinter画布不显示图像
问题描述:
我可以得到tkinter来显示窗口或背景图像,没有任何人有一个建议如何同时显示(我希望对象进入背景图像),我的代码是如下:Tkinter画布不显示图像
from tkinter import *
from tkinter import ttk
root= Tk()
# Code to add widgets will go here...
root.title("MTGO Daily Decklists")
def test():
print("things")
# pick a .gif image file you have in the working directory
# or give full path
image1 = PhotoImage(file="backgroundimage.gif")
w = Canvas(root, width=800, height=700,)
background = PhotoImage(file = "backgroundimage.gif")
w.create_image(500, 500, image=image1)
w.pack()
format_mtg= StringVar()
format_entry= ttk.Entry(w, width=25, textvariable=format_mtg)
format_entry_window = w.create_window(10, 10, anchor='n', window=format_entry)
format_entry.pack()
date= StringVar()
date_entry=ttk.Entry(root, width=25, textvariable=date)
date_entry_window = w.create_window(10, 10, anchor='n', window=date_entry)
date_entry.pack()
ttk.Label(w, text="input format here").pack()
ttk.Button(w, text="fetch", command=test).pack()
ttk.Label(w, text="input date here").pack()
sortby= StringVar()
sortby_entry= ttk.Entry()
sortby_entry.pack()
ttk.Label(w, text="input how you want the decklists to be sorted").pack()
root.mainloop()
答
您将图像的中心放置在500x500。但是,程序启动后,您的窗口只有大约300x200。您的图片可能在那里,但不在屏幕的可见部分。
即使您将画布的大小设置为800x700,也会在画布内部打包窗口小部件。这会导致画布缩小以适应其内容。当然,在打包画布时,不要使用expand
或fill
选项,因此最终结果是GUI的内部缩小到最小尺寸。
注:如果您使用create_window
将窗口添加到画布,你应该不还呼吁该窗口上grid
或pack
。您需要拨打create_window
或pack
,但不能同时拨打。无论你最后打电话给谁,都会有影响。
有很多解决方案,其选择取决于您的最终目标是什么。如果您希望无论窗口大小或内容大小如何都将画布强制为800x700的高度,则可以在画布内关闭几何图形传播。例如:
w.pack_propagate(False)
您也可以打包画布以填充指定给它的空间,然后将背景图像锚定到左上角。例如:
w.pack(fill="both", expand=True)
w.create_image(0, 0, image=image1, anchor="nw")
您也可以停止使用画布,并将背景图像放在标签中。然后,您可以使用place
将标签居中在主窗口中。例如:
background_label = Label(root, image=image1)
background_label.place(relx=.5, rely=.5)
+0
工作,非常感谢你 – dovefromhell
我没有看到任何尝试在背景图像之外创建画布图像。 – TigerhawkT3
哎呀,我改变 w.create_image(500,500,图像=图像1) 到 w.create_image(500,500,图像=背景) 但它仍然有同样的问题 – dovefromhell
当你把它改成'形象=背景“,你是否添加了一行来为'image1'创建画布图像,还是只创建一个图像? – TigerhawkT3