我正在尝试使用Tkinterface创建一个简单的计算器,它可以添加,减去,乘法和除法,但是我有一个问题,当我尝试执行我的程序时,我收到了这个错误:
TypeError:+:'instance'和'instance'
的不支持的操作数类型我个人不知道为什么会这样,我一直在环顾四周,发现了类似错误的问题,但没有找到“实例”和“实例”。 这是我的代码:
#!/usr/bin/python2.7
#Imports necessary modules
from Tkinter import *
#import Tkinter.messagebox
import time as t
import os
#End of importing
#Defines interface
calc = Tk()
calc.title("GUI Calculator")
calc.geometry("500x350+200+200")
#End of interface definition
#Defines methods
def add(val1, val2):
global ans
ans = int(val1 + val2)
return ans
def sub(val1, val2):
global ans
ans = int(val1 - val2)
return ans
def mul(val1, val2):
global ans
ans = int(val1 * val2)
return ans
def div(val1, val2):
global ans
ans = float(val1 % val2)
return ans
#End of method defining
#Heading
but1Text = StringVar()
but1Text.set("Welcome to the GUI Calculator")
label1 = Label(calc, textvariable=but1Text, height=2)
label1.pack()
#Instruction 1
but2Text = StringVar()
but2Text.set("Enter value number one!")
label2 = Label(calc, textvariable=but2Text, height=2)
label2.pack()
#Val 1 input
num1 = IntVar()
val1 = Entry(calc, textvariable=num1)
val1.pack()
#Instruction 2
but3Text = StringVar()
but3Text.set("Enter value number one!")
label3 = Label(calc, textvariable=but2Text, height=2)
label3.pack()
#Val 2 input
num2 = IntVar()
val2 = Entry(calc, textvariable=num2)
val2.pack()
#Operation selector
but4Text = StringVar()
but4Text.set(None)
operator = Radiobutton(calc, text = "Addition", value = "Add", variable = but4Text,command = add(val1,val2)).pack()
operator = Radiobutton(calc, text = "Subtract", value = "Sub", variable = but4Text,command = sub(val1,val2)).pack()
operator = Radiobutton(calc, text = "Multiply", value = "Mul", variable = but4Text,command = mul(val1,val2)).pack()
operator = Radiobutton(calc, text = "Divide", value = "Div", variable = but4Text,command = div(val1,val2)).pack()
#Answer
but5Text = StringVar()
but5Text.set("Answer=")
label4 = Label(calc, textvariable=but5Text, height=2)
label4.pack()
#Answer
but6Text = StringVar()
but6Text.set(ans)
label5 = Label(calc, textvariable=but6Text, height=2)
label5.pack()
#Mainloop
calc.mainloop()
以下是完整错误:
Traceback (most recent call last):
File "./tkCalc.py", line 76, in <module>
operator = Radiobutton(calc, text = "Addition", value = "Add", variable = but4Text,command = add(val1,val2)).pack()
File "./tkCalc.py", line 24, in add
ans = int(val1 + val2)
TypeError: unsupported operand type(s) for +: 'instance' and 'instance'
答案 0 :(得分:2)
您需要对控件实例中文本的数值(int或float)执行操作,而不是对控件本身执行操作。
尝试:
def add(num1, num2):
global ans
ans = int(num1.get() + num2.get())
return ans
和
operator = Radiobutton(calc, text = "Addition", value = "Add", variable = but4Text,command = add(num1, num2)).pack()
所以你的添加按钮传递变量,函数从中获取值。