[英]Firstly I want to place label1 and after 3 seconds i want to configure background but it doesnt work
import tkinter as tk
import time
root=tk.Tk()
label1=tk.Label(text='hello',font='Calibri 25')
label1.pack()
time.sleep(3)
label1.configure(bg='green')
root.mainloop()
Again and again I say only I want to place label1 and after 3 seconds I want to change the background color but it doesnt work.我一次又一次地说我只想放置 label1,3 秒后我想更改背景颜色,但它不起作用。 Can you explain me the main problem and what can I do?
你能解释一下主要问题吗?我该怎么办?
sleep
should not be used in the main tkinter loop, as this causes the interface to freeze.不应在主 tkinter 循环中使用
sleep
,因为这会导致界面冻结。 It's better to use after
.最好在
after
使用。
import tkinter as tk
COLOR = 'green'
def lbl_clear():
label1.configure(text="", bg=root['bg'])
def lbl_bg(color):
label1.configure(bg=color)
root.after(3000, lbl_clear)
root = tk.Tk()
label1 = tk.Label(text='hello', font='Calibri 25')
label1.pack()
root.after(3000, lbl_bg, COLOR)
root.mainloop()
So, few things to clerify here.所以,这里没有什么要澄清的。
the elements are not placed on the screen before root.mainLoop()
is called, In fact - there is no screen at this point.在调用
root.mainLoop()
之前,元素并未放置在屏幕上,事实上 - 此时没有屏幕。 If you do sleep(1000)
for example, nothing will happened for 1000 seconds, then the screen will show with green label.例如,如果你执行
sleep(1000)
,1000 秒内什么都不会发生,然后屏幕将显示绿色标签。
Your first lines create programmatic objects (containing data on how to be drawn on the screen, but they do nothing).您的第一行创建程序化对象(包含有关如何在屏幕上绘制的数据,但它们什么也不做)。
Only after calling rootMainLoop
, tk
creates the screen.只有在调用
rootMainLoop
之后, tk
才会创建屏幕。
An event is a way of executing code when something happenes ( a button is clicked, a text is typed or for your example - a screen is created )事件是一种在发生某些事情时执行代码的方式(单击按钮、键入文本或您的示例 -创建屏幕)
Please read more about events here 请在此处阅读有关活动的更多信息
a way of implementing what you want:一种实现你想要的东西的方法:
create the screen创建屏幕
write a function that changes the label编写一个更改标签的函数
bind the function to an events that fires when label show on screen (ie set the function to run only when the label is displayed )将函数绑定到屏幕上显示标签时触发的事件(即将函数设置为仅在显示标签时运行)
def change_color(): global label sleep(3) label.config(bg="green") root = tk.Tk() label = tk.Label(...) label.bind('<Map>',change_color) root.mainloop()
note: this example is pseudo code.注意:这个例子是伪代码。 not running as is
没有按原样运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.