首页 > 解决方案 > Tkinter 中单选按钮的 TypeError

问题描述

我正在尝试用 Python 中的 Tkinter 编写一个简单的计算器。但是,我的单选按钮不断收到错误消息。这是我在第 39 行得到的错误:plus = tk.RADIOBUTTON(window, text='+', variable=switch, value=1) TypeError: 'str' object is not callable

这是代码:

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

标签: pythontkinterradio-buttontypeerror

解决方案


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

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


推荐阅读