当我按下按钮购买东西时,我希望在第二次消失后不能出现标签。似乎time.sleep(1)使它无法正常工作。这是在python tkinter上完成的。
def buttonpressed():
Label.place(x = 500, y = 500 #where i want the label to appear
time.sleep(1)
Label.place(x = 10000, y = 10000) #moving it away where i wont be able to see it
答案 0 :(得分:2)
您可以使用after()
在指定的时间间隔后设置回调。在回调函数中,使用pack_forget()
清除标签(如果您使用网格,则清除grid_forget()
)。这比将标签的text属性设置为空字符串更好,因为这会导致小部件调整大小,这可能不是您想要的。这是一个例子:
import Tkinter as tk
class App():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text='I am a label')
self.label.place(x=0, y=0)
self.label.after(1000, self.clear_label) # 1000ms
self.root.mainloop()
def clear_label(self):
print "clear_label"
self.label.place_forget()
app=App()
另一种选择是使用self.label.destroy()
来销毁小部件,但是,pack_forget()
允许您再次通过调用小部件上的pack()
来再次显示标签。
答案 1 :(得分:1)
您无法使用sleep
,因为它会停止mainloop
您可以使用root.after(time_in_milliseconds, function_name)
来运行功能
实施例
import tkinter as tk
def button_pressed():
# put text
label['text'] = "Hello World!"
# run clear_label after 2000ms (2s)
root.after(2000, clear_label)
def clear_label():
# remove text
label['text'] = ""
root = tk.Tk()
label = tk.Label(root) # empty label for text
label.pack()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
如果您必须创建和删除标签,请使用label.destroy()
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, destroy_widget, label) # label as argument for destroy_widget
def destroy_widget(widget):
widget.destroy()
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
没有destroy_widget
import tkinter as tk
def button_pressed():
label = tk.Label(root, text="Hello World!")
label.pack()
root.after(2000, label.destroy)
root = tk.Tk()
button = tk.Button(root, text="Press Button", command=button_pressed)
button.pack()
root.mainloop()
多次按下按钮可看到许多标签在2秒后消失。
答案 2 :(得分:0)
# I made it through calling 2 functions:
from tkinter import *
root = Tk()
root.geometry('400x200') # width by height
def one_text():
label['text'] = "Look around"
root.after(1000, another_text)
def another_text():
label['text'] = "and smile"
root.after(1000, one_text)
label= Label(root ,font=('Helvetica', 14), fg='black', bg='white')
label.pack()
one_text()
root.mainloop()