首页 > 解决方案 > 构建 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()

标签: pythontkinterpython-imaging-library

解决方案


发生这种情况是因为您在方法内部声明的local范围。此变量在函数外不可用。因此,当您尝试这样做时: ,它不起作用。box1buildGUI()box1.configure(image=example)

你可以做两件事:

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

您可以在此处阅读有关范围的更多信息


推荐阅读