Home > Blockchain >  Python: GUI based "reverse entry" using recursion failing
Python: GUI based "reverse entry" using recursion failing

Time:03-04

I am trying to make a Python program that asks the user for a number then reverses it using recursion. My attempt is below, but my code gives me TypeError: unsupported operand type(s) for //: 'Entry' and 'int' - any ideas?

from tkinter import * 

def reverseInteger(n, r):
    if n==0:
        return r
    else:
        return reverseInteger(n//10, r*10   n)

window = Tk() 
window.title("Reverse Integer")

frame1 = Frame(window) 
frame1.pack()

number = StringVar()
numEntry = Entry(frame1, textvariable=number) 
btGetName = Button(frame1, text = "Calculate", command = reverseInteger(numEntry, 0)) 
label3 = Label(frame1)

numEntry.grid(row = 1, column = 1)
btGetName.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1, sticky="w")

window.mainloop() 

CodePudding user response:

Your recursive function is perfectly fine but there are several other problems in your code.

The main one is that the command parameter of Button must be the function that will be called when the user presses on the buttton. In your code, command is set to the return value of reverseInteger which is an int. So there is a problem here.

Also it seems to me that you want to put the result of your calculation in label3 so your StringVar should be attached to it and not to numEntry.

So here is a version that seems ok to me:

from tkinter import *

def reverseInteger(n, r):
    if n==0:
        return r
    else:
        return reverseInteger(n//10, r*10   n)

def reverse():  # called when the user click on the button
    value = reverseInteger(int(numEntry.get()), 0)
    number.set(value)  # change the text of the label

window = Tk() 
window.title("Reverse Integer")

frame1 = Frame(window) 
frame1.pack()

number = StringVar()
numEntry = Entry(frame1) 
btGetName = Button(frame1, text = "Calculate", command = reverse) 
label3 = Label(frame1, textvariable=number)

numEntry.grid(row = 1, column = 1)
btGetName.grid(row = 1, column = 2)
label3.grid(row = 2, column = 1, sticky="w")

window.mainloop()
  • Related