简体   繁体   中英

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. 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. 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. So that's why you can't do that. To make a variable global you have to use global function. Example:

def my_function():
    global my_variable
    my_variable = 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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