【发布时间】:2021-08-09 08:46:52
【问题描述】:
当我注意到一些非常奇怪的行为时,我试图用 Tkinter 在其中放置带有图像的按钮。举个例子:
此代码有效:
import tkinter as tk
root = tk.Tk()
root.geometry('720x480')
toolbar = tk.Frame(root, height=32)
toolbar.pack()
button1 = tk.Button(toolbar, text="1")
img1 = tk.PhotoImage(file="img1.png")
button1.config(image=img1)
button1.pack(side=tk.LEFT)
这段代码没有:(区别在倒数第二行)
import tkinter as tk
root = tk.Tk()
root.geometry('720x480')
toolbar = tk.Frame(root, height=32)
toolbar.pack()
button1 = tk.Button(toolbar, text="1")
button1.config(image=tk.PhotoImage(file="img1.png"))
button1.pack(side=tk.LEFT)
什么?为什么tk.PhotoImage(file="img1.png") 的值是否存储在变量中很重要,button1.config(image= 在一天结束时会收到相同的东西,不管它是如何到达那里的。
此外,这些图像的竞争变量名称似乎也会导致错误,见下文:
这行得通:
import tkinter as tk
root = tk.Tk()
root.geometry('720x480')
toolbar = tk.Frame(root, height=32)
toolbar.pack()
button1 = tk.Button(toolbar, text="1")
img1 = tk.PhotoImage(file="img1.png")
button1.config(image=img1)
button1.pack(side=tk.LEFT)
button2 = tk.Button(toolbar, text="2")
img2 = tk.PhotoImage(file="img2.png")
button2.config(image=img2)
button2.pack(side=tk.LEFT)
root.mainloop()
这不会:(只有第二个按钮获取图像)
import tkinter as tk
root = tk.Tk()
root.geometry('720x480')
toolbar = tk.Frame(root, height=32)
toolbar.pack()
button1 = tk.Button(toolbar, text="1")
img = tk.PhotoImage(file="img1.png")
button1.config(image=img)
button1.pack(side=tk.LEFT)
button2 = tk.Button(toolbar, text="2")
img = tk.PhotoImage(file="img2.png")
button2.config(image=img)
button2.pack(side=tk.LEFT)
root.mainloop()
非常感谢解释为什么将这些值存储在变量中而不是直接传递给函数会产生任何影响。
编辑:
更多怪事...
这行得通:
import tkinter as tk
root = tk.Tk()
root.geometry('720x480')
toolbar = tk.Frame(root, height=32)
toolbar.pack()
button1 = tk.Button(toolbar, text="1")
img1 = tk.PhotoImage(file="img1.png")
button1.config(image=img1)
button1.pack(side=tk.LEFT)
root.mainloop()
这不是:
import tkinter as tk
root = tk.Tk()
root.geometry('720x480')
toolbar = tk.Frame(root, height=32)
toolbar.pack()
def add_button(frame, txt, im_file):
button = tk.Button(frame, text=txt)
img = tk.PhotoImage(file=im_file)
button.config(image=img)
button.pack(side=tk.LEFT)
add_button(toolbar, 1, 'img1.png')
root.mainloop()
【问题讨论】: