TypeError for Radiobutton in Tkinter



我正在尝试用Python中的Tkinter编程一个简单的计算器。然而,我的单选按钮一直出现错误。这是我在第39行得到的错误:plus=tk.RRADIOBUTTON(窗口,文本="+",变量=开关,值=1(TypeError:"str"对象不可调用

这是代码:

import tkinter as tk
from tkinter import messagebox
# evaluate function
def evaluate():
try:
global result
if switch == 1:
result = float(first) + float(second)
elif switch == 2:
result = float(first) - float(second)
elif switch == 3:
result = float(first) * float(second)
elif switch == 4:
result = float(first) / float(second)
messagebox.showinfo('Result', result)
except ValueError:
messagebox.showerror('!', 'Please enter either a float or an integer')
except ZeroDivisionError:
messagebox.showerror('!', 'Do not divide by zero!')

# create main window
window = tk.Tk()
window.title("Calculator")
# create and place entry fields
number_1 = tk.Entry(window, width=10)
number_1.grid(column=1, row=3)
number_2 = tk.Entry(window, width=10)
number_2.grid(column=3, row=3)
# get numbers from entry fields
first = number_1.get()
second = number_2.get()
# create and place Radiobuttons
switch = tk.IntVar()
plus = tk.RADIOBUTTON(window, text='+', variable=switch, value=1)
plus.grid(column=2, row=1)
minus = tk.RADIOBUTTON(window, text='-', variable=switch, value=2)
minus.grid(column=2, row=2)
multiply = tk.RADIOBUTTON(window, text='*', variable=switch, value=3)
multiply.grid(column=2, row=4)
divide = tk.RADIOBUTTON(window, text='/', variable=switch, value=4)
divide.grid(column=2, row=5)
# create and place button
button = tk.Button(window, text='Evaluate', command=evaluate())
button.grid(column=2, row=6)
# start controller
window.mainloop()

单选按钮小部件被称为tk.Radiobutton,而tk.RADIOBUTTON只是字符串'radiobutton',因此会出现错误消息。

请注意,根据python样式指南(请参阅PEP8(,大写名称对应于常量,tkinter就是这样。类名遵循CapWords约定。

最新更新