将 tkinter 的 intvar 添加到整数 [英] Add tkinter's intvar to an integer

查看:39
本文介绍了将 tkinter 的 intvar 添加到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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: 不支持 += 的操作数类型:'int' 和 'IntVar'.

TypeError: unsupported operand type(s) for +=: 'int' and '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

推荐答案

需要先调用IntVar.get方法:

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()

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

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.

这篇关于将 tkinter 的 intvar 添加到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆