我正在嘗試制作一個 Tkinter 視窗,該視窗根據您單擊的按鈕將變數設定為某些內容。據我所知,唯一的方法是將“命令”分配給一個函式。但是使用該變數的代碼不在該函式中,所以我試圖使用“全域”來設定我想要選擇的實際變數。但出于某種原因,它仍然回傳 0,這是我最初設定的。這是我的代碼
choi = 0
def return1():
global choi
choi = '1'
print(choi)
def choicedone():
choiwind.destroy()
choiwind = tkinter.Tk()
preset1_button = tkinter.Button(choiwind, text = 'button', command = return1)
quit_button = tkinter.Button(choiwind, text = 'Done', command = choicedone)
preset1_button.pack()
quit_button.pack()
choiwind.mainloop()
print(choi)
if choi == '1':
#do stuff
else:
print('Error')
它回傳“1”然后“0”然后“錯誤”
uj5u.com熱心網友回復:
看起來發布的代碼在一個函式內,所以global choi不參考該choi函式內的變數。
您需要更改global choi為nonlocal choi.
請參閱在Python的檔案global和nonlocal詳細資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/370470.html
上一篇:如何使用tkinter切換螢屏?
下一篇:什么都不會附加到框架
