繁体   English   中英

如何在没有全局变量的情况下访问其他 Function 中定义的 Tkinter 小部件?

[英]How to Access Tkinter Widgets Defined in Other Function Without Global Variables?

我有以下代码,并试图在按下时制作提交按钮,删除 label 和条目,并添加新的小部件。 我了解以下代码不起作用,因为它无法访问小部件的变量,因为它们位于另一个 function 中。 我知道使用全局变量是不好的做法,那么如果没有这样做我该怎么做呢? 对不起,如果这是一个初学者问题!

import tkinter as tk
window = tk.Tk()
name_var = tk.StringVar()


def run_prototype():
    window.geometry("500x100")
    window.title("Shepherdstown Bake Shop")
    greeting = tk.Label(window,text="Hello, Welcome to the Shepherdstown Bake Shop!", font = ('Helvetica 12 bold'))
    start_button = tk.Button(window, text="Please Click Here to Begin", font = ('Helvetica 8'), width = 30, height = 5, command = start,)
    greeting.pack()
    start_button.pack()

def start():
    window2 = tk.Toplevel(window)
    window2.grab_set()
    window.withdraw()
    window2.geometry("500x500")
    window2.title("Shepherdstown Bake Shop Interface")
    label = tk.Label(window2, text="What is your name?")
    submit_button = tk.Button(window2, text = "submit", command = submit)
    submit_button.place(x = 225, y = 45)
    name_entry = tk.Entry(window2, textvariable = name_var,)
    label.pack()
    name_entry.pack()

def submit():
    name = name_var.get()
    name_var.set("")
    name_entry.destroy()
    submit_button.destroy()
    print("Welcome to Shepherdstown Bake Shop, " + name)
    

if __name__ == "__main__":
    run_prototype()

我有坏消息要告诉你。 你不能那样做。 因为当你在 function 中创建一个变量时,它会自动成为一个局部变量,当你想要一个按钮做某事时,你必须创建一个 function。 所以这就是为什么你不能这样做。 要使变量全局化,您必须使用global function。 例子:

def my_function():
    global my_variable
    my_variable = 11

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM