添加到Tkinter程序的图片未显示

2024-05-20 23:53:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我代码的一部分:

rip = tk.Tk()

f2 = tk.Frame(rip)
f2.grid(column=0, row=0, sticky=("nwes"))
f2.columnconfigure(0, weight=1)
f2.rowconfigure(0, weight=1)
c1=tk.Label(f2, text="feet to meter or meter to feet?")
c1.grid(row=0, column=0)
c2=tk.Label(f2, text='type "ft" for feet to meter, type "m" for meter to feet')
c2.grid(row=1, column=0)
lol = tk.StringVar()
choice = tk.Entry(f2, width=7, textvariable=lol)
choice.grid(row=2, column=0)
b1=tk.Button(f2, text="Confirm", command=choose)
b1.grid(row=3, column=0)
picfile="bgmain.gif"
image = tk.PhotoImage(file=picfile)
w=image.width()
h=image.height()
x=10
y=10
rip.geometry("%dx%d+%d+%d"%(w,h,x,y))
panel=tk.Label(rip,image=image)
button=tk.Button(panel, text="button widget")
button.pack(side="top", pady=5)
panel.image=image

rip.mainloop()

我正在给它加背景图片。没有错误消息,并且似乎图片被调出,因为窗口大小已更改为图片的大小。但是什么都不会出现,背景还是白色的。你知道吗


Tags: totextimagecolumnbuttonlabeltkgrid
1条回答
网友
1楼 · 发布于 2024-05-20 23:53:18

您已将图像添加到标签,但尚未将标签添加到窗口。因为panel没有放在屏幕上,所以它是不可见的。既然它是看不见的,里面的图像也就看不见了。你知道吗

如果您希望这是一个背景图像,place是几何管理器的一个好选择。可以使用place设置图像以填充其父图像,如下所示:

panel.place(x=0,y=0, relwidth=1.0, relheight=1.0)

您也可以使用grid,尽管显然有不同的参数。在这种情况下,您不能使用pack,因为您已经在主窗口中使用了grid。你知道吗

根据需要的效果,可能需要更改堆叠顺序。由于您当前正在创建panel作为最后创建的内容之一,它可能会掩盖其他小部件,因为它将“堆叠”在它们之上。最简单的解决方案是先创建背景图像,然后创建位于顶部的小部件。另一种选择是使用panel.lower(0)来降低panel的堆叠顺序。你知道吗

相关问题 更多 >