【问题标题】:Difference between building Tkinter app inside and outside function构建 Tkinter 应用程序内部和外部功能之间的区别
【发布时间】: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


【解决方案1】:

这是因为您在 buildGUI() 方法中声明的 box1local 范围。此变量在函数外不可用。因此,当您尝试这样做时: box1.configure(image=example),不行。

你可以做两件事:

  1. 创建要在函数外部更改其值的变量global
  2. 与函数调用一起,您可以发送要更改的对象。 示例 -
btn1.bind("<Button-1>",lambda e:changeIMG(box1))    #Inside buidGUI

你可以阅读更多关于作用域here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2017-05-05
    • 2011-07-29
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多