tkinter-第二次单击按钮时如何清除标签?

时间:2020-06-19 14:40:31

标签: python tkinter

当有人再次单击按钮时,我试图清除屏幕上的输出。

def eval_click():
    if entry_buysell.get().lower() == 'b':
        stoploss = (float(entry_price.get()) - float(entry_stop_loss.get()))
        take_profit = (float(entry_profit.get()) - float(entry_price.get()))
        ratio = take_profit/stoploss
        if ratio > 2.5:
            output = Label(reasons_window,text="TRADE, risk seems ok.")
            output.grid(row=1, column=2)
        else:
            output = Label(reasons_window,text="DON'T TRADE")
            output.grid(row=1, column=2)

我尝试使用output.destroy(),它基本上会在文本生成后立即销毁。

我不确定该使用什么正确的程序。用户可能对输入字段和输出开关进行了更改,但是在最后一条消息上它被覆盖。

2 个答案:

答案 0 :(得分:2)

您可以先将按钮单击保存到变量中,以检查用户在您的情况下两次按下按钮的次数,然后在函数中检查该变量。现在您有两个选择

  1. 如果不想再次使用该标签,则只需用l1.destroy()删除它,然后在l1.winfo_exists()条件下添加if来检查该小部件是否存在或不是。

    if track_clicks > 0 and l1.winfo_exists():
        l1.destroy()
    
  2. 如果您想稍后在程序中使用标签,则只需使用pack_forget()grid_forget() / place_forget() grid 和< em> place 几何管理器。

    if track_clicks > 0:
        l1.pack_forget()
    
  3. 您也可以执行l1.config(text='')来删除标签文本。


以下是示例:

import tkinter as tk

track_clicks = 0
def click():
    global track_clicks
    if track_clicks > 0 and l1.winfo_exists():
        l1.destroy() # destroys the label
    track_clicks += 1

root = tk.Tk()

l1 = tk.Label(root, text="DON'T TRADE")
l1.pack()
b1 = tk.Button(root, text='Click :)', command=click)
b1.pack()

root.mainloop()

答案 1 :(得分:-1)

尝试一下:

output.delete('1.0', END)

假设您正在使用Python3?