Sander
Sander

Reputation: 5

How can I make a button input as Integer

I just started to work with python with a little to no actual programming background. As most of the newcomers I am writing a calculator. I've got some buttons for writing my numbers into a label. This works well if I set the textvariable in StringVar as the snippet below:

numbers = StringVar()
display = Label(root, font = "Arial 20", textvariable = numbers, relief = RIDGE, anchor = E)

But when I set this into IntVar it doesnt work anymore. I don't seem to be able to solve my problem. Here is some more of my code to clearify what Im doing (wrong?).

numbers = IntVar()
display = Label(root, font = "Arial 20", textvariable = numbers, relief = RIDGE, anchor = E)
display.place(x=1, y=1, width=212,height=47


def display_input (inputValue):
    CurrentInput = numbers.get()
    numbers.set(CurrentInput + inputValue)


btn1 = Button(root, text = '1', bd = '1', bg = 'lightsteelblue', relief = RAISED, command = lambda: display_input('1'))
btn1.place(x=1, y=96, width=71,height=47) 

Upvotes: 0

Views: 404

Answers (1)

michaeldel
michaeldel

Reputation: 2385

here you are calling the display_input function with a string (str) instead of an integer (int):

# '1' with quotes is a string, not an integer
Button(root, ..., command = lambda: display_input('1'))

This will make you attempt to update an IntVar with the result of the sum of an int with a str, which is not supported:

>>> 0 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Replacing that command with display_input(1) instead (here 1 is an int) should fix your issue.

Upvotes: 1

Related Questions