创建计算+清除按钮Tkinter

2024-09-29 11:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释为什么“添加”和“清除”按钮不起作用吗?另外,是否有人能就我应该如何构造此代码以添加和清除标签提供建议

最初我的add命令将输入相加并创建了一个标签,但我意识到我的clear()函数将无法访问本地标签变量来清除它

我的下一个想法是创建一个全局label_result变量,然后在add函数中用结果更改它,并在clear()函数中清除它

然而,我得到了一个错误 AttributeError: 'NoneType' object has no attribute 'config' Exception in Tkinter callback

from tkinter import*

class Window:
    def __init__(self,root,title,geometry):
        self.root=root
        self.root.title(title)
        self.root.geometry(geometry)

    def dynamic_button(self,text,command):
        dynamic_button = Button(self.root,text=text,command=command)
        dynamic_button.grid()

    def label(self,text):
        label1 = Label(self.root,text=text)
        label1.grid()

    def input(self):
        input=Entry(self.root)
        input.grid()
        return input


def add():
    result = int(input1.get()) + int(input2.get())
    result_label.config(text=result)

def clear():
    result_label.config(text="")

root=Tk()
window1 = Window(root,"Practice GUI","550x400")
result_label = window1.label(text="")

input1 = window1.input()
input2 = window1.input()

calculate_button = window1.dynamic_button("Calculate",add)
clear_button = window1.dynamic_button("Clear",clear)

root.mainloop()


Tags: 函数textselfaddconfiginputdefbutton
1条回答
网友
1楼 · 发布于 2024-09-29 11:14:27

如果像这样构造代码,可能会更容易

from tkinter import *

class Window:
    def __init__(self,root,title,geometry):
        self.root=root
        self.root.title(title)
        self.root.geometry(geometry)

        #input 1
        self.input_1 = Entry(self.root)
        self.input_1.pack()

        #input 2
        self.input_2 = Entry(self.root)
        self.input_2.pack()

        #add button
        self.add_Btn = Button(self.root, text="Calculate", command=self.add)
        self.add_Btn.pack()

        #clear button
        self.clear_Btn = Button(self.root, text="Clear", command=self.clear)
        self.clear_Btn.pack()

        #result label
        self.label = Label(self.root)
        self.label.pack()

    def add(self):
        try:
            total = int(self.input_1.get())+int(self.input_2.get())
            self.label["text"] = f"Sum is {total}."
        except ValueError:
            pass

    def clear(self):
        self.input_1.delete(0, 'end')
        self.input_2.delete(0, 'end')
        self.label["text"] = ""

root=Tk()
window1 = Window(root,"Practice GUI","550x400")

root.mainloop()

相关问题 更多 >