首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Tkinter中单选按钮的TypeError

Tkinter中单选按钮的TypeError
EN

Stack Overflow用户
提问于 2020-12-23 03:29:09
回答 1查看 32关注 0票数 0

我正在尝试用Python用Tkinter编写一个简单的计算器。但是,我的单选按钮总是出现错误。这是我在第39行得到的错误: plus = tk.RADIOBUTTON(window,text='+',variable=switch,value=1) TypeError:'str‘对象不可调用

代码如下:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2020-12-23 03:40:35

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

请注意,根据python样式指南(请参阅PEP8),大写名称与常量相对应,在tkinter中就是这种情况。类名遵循CapWords约定。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65414758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档