【发布时间】:2021-03-20 08:40:11
【问题描述】:
我正在使用 tkinter 构建一个 GUI 应用程序,然后我遇到了这种挫败感。
当我尝试创建一个简单的程序来改变我点击按钮时的图片时,我首先在名为 buildGUI() 的函数中声明了每个 tkinter 小部件,然后我运行了代码,那个简单的程序无法改变图片。
但是当我把 buildGUI() 中的所有代码放在外面时,程序就可以正常运行了。
为什么会这样?
import tkinter
from tkinter import ttk
from PIL import ImageTk,Image
## GUI
frame = tkinter.Tk()
tab_control = ttk.Notebook(frame)
detect_frame= ttk.Frame(tab_control)
label1 = ttk.Label()
box1 = ttk.Label()
btn1 = ttk.Button()
##
example = ImageTk.PhotoImage(Image.open("gui_data/goose.png"))
def changeIMG():
print("Changing image ")
global example
example = ImageTk.PhotoImage(Image.open("gui_data/overwork.jpg").resize((320,320)))
box1.configure(image=example)
def buildGUI():
global example
icon = ImageTk.PhotoImage(Image.open("gui_data/icon.jpg"))
frame.title('IOT-Project_TEST')
frame.geometry("800x600")
frame.resizable(width=False, height=False)
frame.iconphoto(False,icon)
tab_control.add(detect_frame,text='Detect Zone')
tab_control.pack(expand=1,fill="both")
button_style = ttk.Style().configure("def.TButton",font=("Courier",16))
label1 = ttk.Label(detect_frame,text="Detect Zone")
box1 = ttk.Label(detect_frame,image=example,borderwidth=5,relief='solid')
btn1 = ttk.Button(detect_frame,text="Open Camera",command=changeIMG,style="def.TButton")
label1.pack()
box1.pack(pady="10")
btn1.pack(pady=10,ipadx="10",ipady="10")
frame.mainloop()
【问题讨论】:
-
这是因为变量的默认作用域是函数内的局部变量。
-
@quamrana 所以如果我想让我的 buildGUI() 工作,我必须告诉变量它来自全局变量,比如全局示例?
-
你可以从 buildGUI() 返回 box1
标签: python tkinter python-imaging-library