Reputation:
I'm making simple calculator and I've implemented all the functions except one function. As you know, dots must be used only once until the new number comes. So I want to make the (.) button disabled after used once and make it available again when I use symbol or C. I was thinking about changing the button text by using configure method.
Here's my code:
from tkinter import*
w1 = Tk()
w1.title("My Calculator")
show = Entry(w1, width=33, bg="yellow")
show.grid(row=0, column=0, columnspan=5)
btn_list = [
'7','8','9','/','C',
'4','5','6','*','',
'1','2','3','-','',
'0','.','=','+','']
index_row = 1
index_col = 0
def click(button):
if button == "=":
value = eval(show.get())
s = str(value)
show.delete(0,"end")
show.insert(END,s)
elif button=="C":
show.delete(0,"end")
else:
show.insert(END,button)
for btn_text in btn_list:
def go(k=btn_text):
click(k)
Button(
w1, text=btn_text, width=5, command=go
).grid(row=index_row, column=index_col)
index_col += 1
if index_col > 4:
index_row += 1
index_col = 0
w1.mainloop()
Upvotes: 2
Views: 352
Reputation: 15088
Easiest way is to use a tkinter variable and trace
it.
var = StringVar()
show = Entry(w1, width=33, bg="yellow", textvariable=var)
def validate(*args):
if var.get().count('.') > 1:
var.set(var.get()[:-1])
var.trace('w',validate)
There are more than just one way to do this, starting with storing input in the list, or storing the specific button as a variable and so on. There are also different ways to loop through the texts easily.
Updated because your professor has not taught you the previous method(yet):
def click(button):
..... # Same stuff
if show.get().count('.') >= 1:
dot_btn.config(state='disabled')
else:
dot_btn.config(state='normal')
for btn_text in btn_list:
def go(k=btn_text):
click(k)
if btn_text == '.':
dot_btn = Button(w1, text=btn_text, width=5, command=go)
dot_btn.grid(row=index_row, column=index_col)
else:
Button(
w1, text=btn_text, width=5, command=go
).grid(row=index_row, column=index_col)
index_col += 1
if index_col > 4:
index_row += 1
index_col = 0
This looping method is really beating around the bush, directly you could just use nested loops and get your desired output, you would not even need to made index_row
and index_col
. Never limit your understanding to what your professor or mentor has taught you, be ready to explore and learn more(maybe you will end up teaching him :P).
Note that using eval()
to do mathematical expressions alone is poor, it opens a whole new galaxy of security issues.
Upvotes: 0