【问题标题】:.place_forget() not executed until after everything else in the function.place_forget() 直到函数中的所有其他内容之后才执行
【发布时间】:2020-11-01 23:46:25
【问题描述】:

所以我有下面的函数应该忘记一个按钮,迭代一个分数,等待一秒钟,然后把按钮带回来。

def iteration():
    global score
    #should hide button
    b1.place_forget()
    #raise score
    score += 1
    label.config(text = score)
    #wait one second
    sleep(1)
    #bring button back
    b1.place(relx = 0.3, y = 30)

相反,place_forget() 直到其他所有操作之后才运行,导致按钮从不闪烁并在迭代分数之前等待一秒钟。为什么事情会按此顺序发生,我该如何解决?这是我的其余代码:

from tkinter import *
from time import sleep

global score
score = 0

def iteration():
    global score
    #should hide button
    b1.place_forget()
    #raise score
    score += 1
    label.config(text = score)
    #wait one second
    sleep(1)
    #bring button back
    b1.place(relx = 0.3, y = 30)
    
 
root = Tk()  
root.geometry("150x100") 


#make label
label = Label(root, text = score) 
  
# place in the window 
label.place(relx=0.4, y=5) 
  
#make and place button 1
b1 = Button(root, text = "hide text", 
            command = lambda: iteration())
  
b1.place(relx = 0.3, y = 30) 
  
# make and place button 2
b2 = Button(root, text = "retrieve text", 
            command = lambda: iteration())
  
b2.place(relx = 0.3, y = 50) 
  
# Start the GUI 
root.mainloop()

【问题讨论】:

  • 对于您的情况,您需要在sleep(1) 之前调用root.update() 以强制tkinter 更新窗口。
  • 不胜感激将答案标记为正确的答案

标签: python tkinter time widget


【解决方案1】:

我认为该过程正在发生,但您的 sleep(1) 冻结了 GUI,因此您看不到它。

  1. 或者,替换sleep(1),然后将小部件替换为after(),可能会得到您想要的效果,例如:
def iteration():
    global score
    #should hide button
    b1.place_forget()
    #raise score
    score += 1
    label.config(text = score)
    #wait one second and bring button back
    root.after(1000,lambda: b1.place(relx = 0.3, y = 30))

after() 防止 GUI 在应该隐藏和显示的位置滞后一秒钟。

  1. 否则,使用threading 喜欢:
import threading
.... #same old codes

b1 = Button(root, text = "hide text",command =lambda: threading.Thread(target=iteration).start())

现在sleep(1) 不会导致 GUI 滞后,因为它不在 tkinter 线程中。

  1. 否则,您可以让它与 update() 一起使用,但 GUI 仍可能被冻结但它会更新,按钮“闪烁”,例如:
root.update()
sleep(1)
#bring button back
b1.place(relx = 0.3, y = 30)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多