Python 构建Tkinter应用程序内部和外部功能之间的差异
我在用tkinter构建GUI应用程序时遇到了这种挫折 当我试图创建一个简单的程序来更改图片时,当我单击一个按钮时,我首先声明了名为buildGUI()的函数中的每个tkinter小部件,然后我运行代码,这个简单的程序无法更改图片 但当我将buildGUI()中的所有代码放在它的外部时,程序就可以正常运行了 为什么会这样Python 构建Tkinter应用程序内部和外部功能之间的差异,python,tkinter,python-imaging-library,Python,Tkinter,Python Imaging Library,我在用tkinter构建GUI应用程序时遇到了这种挫折 当我试图创建一个简单的程序来更改图片时,当我单击一个按钮时,我首先声明了名为buildGUI()的函数中的每个tkinter小部件,然后我运行代码,这个简单的程序无法更改图片 但当我将buildGUI()中的所有代码放在它的外部时,程序就可以正常运行了 为什么会这样 import tkinter from tkinter import ttk from PIL import ImageTk,Image ## GUI frame = t
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()
这是因为在
buildGUI()
方法中声明了box1
的local
范围。此变量在函数外部不可用。因此,当您尝试这样做时:
box1.configure(image=example)
,它不起作用
你可以做两件事:
global
btn1.bind(“,lambda e:changeIMG(box1))#内置UI
您可以阅读有关作用域的更多信息这是因为变量的默认作用域是函数中的局部变量。@quamrana因此,如果我想让buildGUI()工作,我必须告诉变量它来自全局变量,如全局示例?您可以从buildGUI()返回框1