0

Edit: I fixed the error, etc, with which this post was concerned, and now I am trying a different way to achieve advanced features I was originally going for. This time I have a display, and a display function. The buttons call the update function by inserting text into said display. I was wondering how I could use this function, and maybe textvariable =so that I can both change my buttons' text from 1, 2, 3, 4... 9, 0 to A, B, C, D...I, J. My code is below, any help would be appreciated. :)

from tkinter import *
import time

root = Tk()
root.title('Calculator')



displayb = Entry(root)
displayb.grid(row = 1, columnspan = 6)


mode = 0

i = 0


'''def update():
    global mode
    if mode == 0:
        mode = 1
    else:
        mode = 0
    return'''
def display(e):
    global i
    displayb.insert(i,e)
    i += 1

txt1 = StringVar()
a = '1' if mode == 0 else 'A'
one = Button(root, text = '1', command = lambda : display(1))
txt1.set(a)
one.grid(row = 2, column = 0)
two = Button(root, text = '2', command = lambda : display(2))
two.grid(row = 2, column = 1)
three = Button(root, text = '3', command = lambda : display(3))
three.grid(row = 2, column = 2)
four = Button(root, text = '4', command = lambda : display(4))
four.grid(row = 3, column = 0)
five = Button(root, text = '5', command = lambda : display(5))
five.grid(row = 3, column = 1)
six = Button(root, text = '6', command = lambda : display(6))
six.grid(row = 3, column = 2)
seven = Button(root, text = '7', command = lambda : display(7))
seven.grid(row = 4, column = 0)
eight = Button(root, text = '8', command = lambda : display(8))
eight.grid(row = 4, column = 1)
nine = Button(root, text = '9', command = lambda : display(9))
nine.grid(row = 4, column = 2)
zero = Button(root, text = '0', command = lambda : display(0))
zero.grid(row = 5, column = 1)
'''shift = Button(root, text = 'sft', command = lambda : mode = 1 if mode == 0 else 0)
shift.grid(row = 2, column = 1)'''


root.mainloop()
Ryan Flynn
  • 71
  • 1
  • 8

1 Answers1

2

When providing the command parameter a value, you need to give it a reference to your function by just giving it the function name.

shift = Button(root, text = 'sft', command = update())

Here you have () at the end of it which is calling your function. Either remove the () or use lambda like you did earlier.

Now, the reason you are getting the error you are is because mode is a global variable, defined outside your update function. So if you want to update the variable then you need to let it know that mode is global

def update():
    global mode
    if mode == 0:
        mode = 1
    else:
        mode = 0
    return mode

Also note that unless you will call this function somewhere else, you can't retrieve the return value on Button press.

More info on global and local scope.

Community
  • 1
  • 1
Steven Summers
  • 5,079
  • 2
  • 20
  • 31