簡體   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