[英]Program unresponsive on clicking a button in Tkinter?
我正在嘗試使用 Tkinter 創建一個簡單的計算器,但我遇到了一個問題。 先看相關代碼:
entry_text = StringVar()
inout = Entry(root, textvariable=entry_text)
inout.grid(row=0, column=0, columnspan=4, sticky="nsew")
def equals():
print("Equal button is clicked")
get_answer = True
def divide():
tempvar = entry_text.get()
num1 = int(tempvar)
entry_text.set("")
while get_answer == False:
tempvar2 = entry_text.get()
try:
num2 = int(tempvar2)
except ValueError:
num2 = 0
print("I'm out of the loop.")
answer = num1 / num2
entry_text.set(answer)
在這里,我正在為divide
按鈕創建一個函數。 按鈕的功能是每當您單擊按鈕時,它都會獲取entry_text
變量的瞬時值,將其存儲在臨時變量中並重置entry_text
變量的值。 然后它運行一個循環來收集entry_text
的下一個值,直到單擊等於按鈕。 但問題就在這里。 每當我單擊divide
按鈕時,GUI 都會變得無響應,並且我無法輸入除法操作的下一個值並退出循環。
任何人都可以幫忙嗎?
避免在mainloop
應用程序中使用 while 循環,因為它會阻止mainloop
處理掛起的事件。
此外, equals()
中的get_answer
是一個局部變量,因為您尚未使用global get_answer
其聲明為global get_answer
。
實際上,您應該在equals()
執行所需的操作,但您需要將第一個數字和選定的操作存儲為全局變量:
num1 = 0
operator = None
def equals():
global num1, operator
print("Equal button is clicked")
try:
tempvar = entry_text.get()
num2 = float(tempvar) # used float() instead of int()
if operator == '/' and num2 != 0:
answer = num1 / num2
entry_text.set(answer)
operator = None # reset operator
except ValueError:
print('Invalid value', tempvar)
def divide():
global num1, operator
try:
tempvar = entry_text.get()
num1 = float(tempvar) # used float() instead of int()
entry_text.set("")
operator = '/' # save the operator
except ValueError:
print('Invalid value', tempvar)
程序變得無響應,因為while
循環永遠持續下去並且永遠不會中斷,因為變量get_answer
永遠不會更改為True
。
你不能點擊任何按鈕,因為
while
循環一直在運行並且不能在沒有給定條件變為false
的情況下中斷,或者在一定數量的循環后被手動告知break
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.