Python:基于 GUI 的“反向输入”使用递归失败
我正在尝试编写一个Python程序,要求用户输入一个数字,然后使用递归反转它。我的尝试如下,但我的代码给了我 TypeError: unsupported operand type(s) for //: 'Entry' and 'int' - 有什么想法吗?
from tkinter import *
def reverseInteger(n, r):
if n==0:
return r
else:
return reverseInteger(n//10, r*10 + n%10)
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()
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%10)
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的递归函数非常好,但还有其他几个
您的代码中存在问题。
主要的是
Button
的command
参数必须是当用户按下按钮时将调用的函数。在
您的代码中,
command
设置为reverseInteger
的返回值这是一个整数。所以这里有一个问题。
另外,在我看来,你想把你的结果
label3
中的计算,因此您的StringVar
应附加到它而不是
numEntry
。所以这是一个对我来说似乎不错的版本:
Your recursive function is perfectly fine but there are several other
problems in your code.
The main one is that the
command
parameter ofButton
must be thefunction that will be called when the user presses on the buttton. In
your code,
command
is set to the return value ofreverseInteger
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 yourStringVar
should be attached to itand not to
numEntry
.So here is a version that seems ok to me: