简体   繁体   English

Python Tkinter GUI:“清除结果”按钮不起作用

[英]Python Tkinter GUI: 'Clear result' button does not work

This is my first python program. 这是我的第一个python程序。 I'm trying to create torricelli's draintime calculator, but the 'clear result' button doesn't work. 我正在尝试创建torricelli的排水时间计算器,但是“清除结果”按钮不起作用。 I want it to clear calculated results. 我希望它清除计算结果。

I get this error: 我收到此错误:

Traceback (most recent call last):
    File "C:\Users\David \Desktop  File\GUI_DrainTime_Calculator.py", line 83, in clear
    drain_label.destroy()
NameError: name 'drain_label' is not defined

Please help me figure why this NameError persists. 请帮我弄清楚为什么这个NameError持续存在。 this is the culprit: 这是罪魁祸首:

drain_label = Label(
    WIN, 
    font=('Helvetica', 8, 'bold'),
    text="The time it takes for the liquid to drain is: %.0f hour, %.0f minutes, and %.0f seconds." % (hr, Min, sec)).pack(side=BOTTOM)

def clear():
    drain_label.destroy()
    Clearbtn = Button(WIN, text="Clear Results", font('Helvetica',7,'bold'), fg='black',command=clear)
    Clearbtn.configure(background='grey')
    Clearbtn.pack(side=TOP,pady=5)

Thank you all ! 谢谢你们 !

Try using a textvariable for your label. 尝试为标签使用textvariable I also recommend using a Class for your program. 我还建议为您的程序使用类。

import tkinter as tk
from tkinter import ttk

class Calculator:
    def __init__(self, master):

        frame = tk.Frame(master)

        self.text_var = tk.StringVar()
        hr, min, sec = 1, 4, 20
        text = 'drain time = %.0f Hr, %0f Min, %.0f Sec' % (hr, min, sec)

        drain_label = ttk.Label(frame, textvariable=self.text_var).pack()

        clear_button = ttk.Button(frame, text='clear', command=self.destroy).pack()

        frame.pack()

    def destroy(self):
        self.text_var.set('')

root = tk.Tk()
app = Calculator(root)
root.mainloop()

you can use tk.StringVar() along with the .get() and .set() methods to get and set the string variable. 您可以将tk.StringVar().get().set()方法一起使用来获取和设置字符串变量。 you could also use string variables for hr, min, sec and pass those using a button. 您还可以将字符串变量用于hr, min, sec然后使用按钮传递这些变量。

您的变量drain_label不是global的,因此该功能无法看到它的定义/声明的任何地方,尝试通过drain_label作为参数在函数或使其global ,虽然使用全局变量,尽可能我建议回避。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM