Issue
I'm trying to create a simple calculator using Tkinter, but I'm facing a problem. First see the relevant code:
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)
Here I'm creating a function for the divide
button. The functionality of the button is whenever you click on the button, it takes the instantaneous value of the entry_text
variable, stores it in a temporary variable and resets the value of entry_text
variable. Then it runs a loop for collecting the next value of entry_text
until the equal button is clicked. But the problem lies just here. Whenever I click on divide
button, the GUI becomes unresponsive, and I don't get to enter the next value for the divide operation and get out of the loop.
Can anyone help?
Solution
Avoid using while loop in a tkinter application because it will block tkinter mainloop
from handling pending events.
Also, get_answer
inside equals()
is a local variable because you haven't declare it as a global using global get_answer
.
Actually you should perform the required operation inside equals()
, but you need to store the first number and selected operation as global variables:
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)
Answered By - acw1668
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.