Python 将 tkinter 的 intvar 添加到整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19719577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:25:28  来源:igfitidea点击:

Add tkinter's intvar to an integer

pythonuser-interfacetkintertk

提问by JShell

I'm having some trouble adding a value taken from an Entry box and adding it to an existing number. In this case, I want the value of the "change speed" box to be added to the robots current speed. When run, my code produces an error:

我在添加从输入框中获取的值并将其添加到现有数字时遇到了一些麻烦。在这种情况下,我希望将“更改速度”框的值添加到机器人当前速度。运行时,我的代码产生错误:

TypeError: unsupported operand type(s) for +=: 'int' and 'IntVar'.

类型错误:不支持 += 的操作数类型:'int' 和 'IntVar'。

Below is the code that produces the entry box:

下面是生成输入框的代码:

change_speed_entry = ttk.Entry(main_frame, width=5)  # Entry box for linear speed
change_speed_entry.grid()
data = tkinter.IntVar()
change_speed_entry['textvariable'] = data

And next is where I try to manipulate the result. This is a method within a class. All other methods of the class work correctly:

接下来是我尝试操纵结果的地方。这是一个类中的方法。该类的所有其他方法都可以正常工作:

def changeSpeed(self, delta_speed):
    self.speed += delta_speed

采纳答案by Tim Peters

You need to first invoke the .getmethod of IntVar:

您需要先调用以下.get方法IntVar

def changeSpeed(self, delta_speed):
    self.speed += delta_speed.get()

which returns the variable's value as an integer.

它将变量的值作为整数返回。

Since I don't have your full code, I wrote a small script to demonstrate:

由于我没有你的完整代码,我写了一个小脚本来演示:

from Tkinter import Entry, IntVar, Tk

root = Tk()

data = IntVar()

entry = Entry(textvariable=data)
entry.grid()

def click(event):
    # Get the number, add 1 to it, and then print it
    print data.get() + 1

# Bind the entrybox to the Return key
entry.bind("<Return>", click)

root.mainloop()

When you run the script, a small window appears that has an entrybox. When you type a number in that entrybox and then click Return, the script gets the number stored in data(which will be the number you typed in), adds 1 to it, and then prints it on the screen.

运行脚本时,会出现一个带有输入框的小窗口。当您在该输入框中键入一个数字然后单击 时Return,脚本会获取存储在data其中的数字(这将是您输入的数字),将其加 1,然后将其打印在屏幕上。

回答by Tim Peters

You didn't show the code defining .speedor delta_speed, so I'm guessing here. Try:

您没有显示定义.speedor的代码delta_speed,所以我在这里猜测。尝试:

    self.speed += delta_speed.get()
                             ^^^^^^

Ifdelta_speedis an IntVar, .get()will retrieve its value as a Python int.

如果delta_speedIntVar.get()则将其值作为 Python int 检索。