[英]How to Access Tkinter Widgets Defined in Other Function Without Global Variables?
I have the following code, and am trying to make the submit button upon press, delete the label and entry, and add new widgets.我有以下代码,并试图在按下时制作提交按钮,删除 label 和条目,并添加新的小部件。 I understand the following code I have doesn't work, because it cant access the variables for the widgets as they are in another function.我了解以下代码不起作用,因为它无法访问小部件的变量,因为它们位于另一个 function 中。 I know it is bad practice to use global variables, so how would I do this without so?我知道使用全局变量是不好的做法,那么如果没有这样做我该怎么做呢? Sorry If this is a beginner question!对不起,如果这是一个初学者问题!
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()
I have bad news for you.我有坏消息要告诉你。 You can't do that.你不能那样做。 Because when you create a variable in a function it's automatically a local variable and when you want a button to do something you have to make a function.因为当你在 function 中创建一个变量时,它会自动成为一个局部变量,当你想要一个按钮做某事时,你必须创建一个 function。 So that's why you can't do that.所以这就是为什么你不能这样做。 To make a variable global you have to use global
function.要使变量全局化,您必须使用global
function。 Example:例子:
def my_function():
global my_variable
my_variable = 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.