![](/img/trans.png)
[英]Returning into variable from function called in tkinter.Button command
[英]Tkinter Toplevel() in function called from button's command makes not accessible variables
感謝您閱讀我的帖子。 我還是編碼新手,遇到了一堵磚牆,讓我們進入正題:所以我嘗試在根 window 上創建一個 GUI 我有一個按鈕:
add_association_button = Button(text="Add Association Text", image=add_association_icon, command=add_association)
當用戶點擊此按鈕時,另一個 window 會出現,並帶有輸入和保存按鈕。
def add_association():
input_window = Toplevel()
input_window.config(bg=BACKGROUND_COLOR, padx=10, pady=10)
input_window.title("Set association")
association_label = Label(input_window, text=f"Provide association for the word {word_on_the_screen.japanese_word}",
bg=BACKGROUND_COLOR, font=("Arial", 14, "bold"))
global association_entry
association_entry = Entry(input_window, width = 50)
save_button = Button(input_window, text="Save", command=save_association)
association_label.pack()
association_entry.pack()
save_button.pack()
這是保存按鈕的問題,我想將用戶的值保存到全局 object 並關閉 input_window。 我發現我可以將 global 用於 association_entry 並在 function 的第二個實例中獲取它
def save_association():
#TODO
global association_entry
user_association = association_entry.get()
global word_on_the_screen
word_on_the_screen.association = user_association
canvas.itemconfig(word_association_canvas, text=word_on_the_screen.association)
我的問題是如何關閉 save_association function 中的 input_window 並且有沒有其他方法可以在 save_association 中訪問 Association_entry?
input_window的實現或實現是否應該在main_body中? 如果是這樣,如何根據我的意願使 input_window 可見和不可見? 我認為這可以解決我的問題:)
對於任何答案非常感謝!
您的問題在第一次閱讀時並不清楚,因為如果 window 已關閉,那么按鈕是如何按下並執行save_association()
的。 但后來我假設你的意思是,你想在 window 關閉后在其他地方調用save_association()
。 好吧,我可以在這里想到一種方法,當 window 關閉時,調用 function 將獲取用戶條目並使其成為global
。 所以它會像:
from _tkinter import TclError
.....
def add_association():
input_window = Toplevel()
.....
def save():
global inp # Notice I used inp instead of input because it is built in function
inp = association_entry.get() # Get the value and make it global
input_window.destroy() # Close the window
input_window.protocol('WM_DELETE_WINDOW',save) # If window is closed execute save()
那么您的其他 function 將是:
def save_association():
global inp
#TODO
try:
inp = association_entry.get()
except TclError: # This error will get triggered if window is closed, by which last typed input from save() will be used
pass
word_on_the_screen.association = user_association
canvas.itemconfig(word_association_canvas, text=inp)
由於我沒有可用的示例,因此我無法嘗試此代碼,但這應該可以解決問題。 這就像一種 hacky 方式,如果發生錯誤則覆蓋變量,否則從輸入框本身獲取它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.