【问题标题】:Creating a calculate + clear button Tkinter创建一个计算 + 清除按钮 Tkinter
【发布时间】:2021-04-05 11:04:35
【问题描述】:

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

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

【问题讨论】:

  • 至少部分问题是您的Window.lable() 函数没有返回值,因此将其返回值分配给result_label 会使其值为None。一旦我通过在末尾添加return label1 语句解决了这个问题,清除按钮就起作用了。
  • 非常感谢,成功了!你能解释一下为什么我需要返回 label1 吗?我试图更好地理解这一点
  • 所有函数都返回某种值,通常通过它们内部某处的return 语句。但是,如果函数结束时没有遇到(和/或执行)这样的语句,Python 会隐式执行 return None
  • 欣赏回复,有道理。谢谢

标签: python user-interface tkinter


【解决方案1】:

如果你像这样构造你的代码可能会更容易。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2022-09-28
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 2014-06-02
    相关资源
    最近更新 更多