python - 创建一个计算 + 清除按钮 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()
解决方案
如果您像这样构建代码,可能会更容易。
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()
推荐阅读
- python - 如何设计神经网络使其表现得像 For-Loop?
- r - Tidyr::crossing 2 个以上的参数 (..1,..2,..3)
- python - python:比较复合主键值
- ansible - 检查是否在 Windows 上安装了 MSI 包
- mysql - 尝试内连接;出现错误或没有返回行?
- java - 如何在java项目中实现单点登录?
- javascript - “类型错误:元素为空”。在 javascript 中调用 getElementById 时
- javascript - 在 Javascript 代码中键入波斯语/阿拉伯语
- c# - 如何在 C# 中编译和执行文本?
- java - 如何知道在 Android Studio 中输入的字母是否为大写?