python - 构建 Tkinter 应用程序内部和外部功能之间的区别
问题描述
我正在使用 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()
解决方案
发生这种情况是因为您在方法内部声明的local
范围。此变量在函数外不可用。因此,当您尝试这样做时:
,它不起作用。box1
buildGUI()
box1.configure(image=example)
你可以做两件事:
- 创建
global
要在函数外部更改其值的变量。 - 除了函数调用,您还可以发送要更改的对象。例子 -
btn1.bind("<Button-1>",lambda e:changeIMG(box1)) #Inside buidGUI
您可以在此处阅读有关范围的更多信息
推荐阅读
- excel - VBA 我的数组没有将值粘贴在工作表上
- php - 访问对象 PHP 中的对象
- javascript - 无法使用带有 angular/typescript/javascript 的 OpenXml 创建/保存 word 文档
- python - python winrm 协议抛出 WARNING 的如何防止呢?
- jq - 仅在匹配名字和姓氏时提取jq记录
- javascript - 基于值删除 Google Sheet 表格内容时出错
- swift - 如何更新 NSDiffableDataSourceSnapshot 项
- node.js - 从标准输出中清除多行
- angular - ng new 卡在 npm install - windows
- sockets - 如何在 C++ 中实现 IP 协议(IP 封装)中的 IP?