python - 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()
解决方案
单选按钮小部件被调用tk.Radiobutton
,而tk.RADIOBUTTON
只是字符串'radiobutton'
,因此是错误消息。
请注意,根据 python 样式指南(请参阅PEP8),大写名称对应于 tkinter 中的常量。并且类名遵循 CapWords 约定。
推荐阅读
- java - 是否可以指示 JVM 仅记录完整的 GC 事件?
- git - 当我可以在“git init”之后对“git pull”做同样的事情时,为什么要“git clone”?
- ios - App.Delegate 从 ViewController 到 TabController Swift 5
- google-cloud-firestore - Firebase 使用侦听器与完整查询
- ssas - 来自 ssas 多维立方体,如何通过 salesPoint 和 month 从 factsales 中获得最高销售额
- node.js - 我如何编写一个从 mongodb 查询的辅助函数,然后可以为任何 ejs 模板调用此函数
- responsive - 我怎样才能使网站移动友好?
- java - 在java中使用递归来反转字符串
- python - 使用 SymPy 解决具有符号数量变量的约束优化问题
- git - git push a detached head to a dev branch of remote