【发布时间】: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