首页 > 解决方案 > 创建一个计算 + 清除按钮 Tkinter

问题描述

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

最初我的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()

标签: pythonuser-interfacetkinter

解决方案


如果您像这样构建代码,可能会更容易。

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

推荐阅读