微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.place_forget直到函数中的所有其他内容之后才执行

如何解决.place_forget直到函数中的所有其他内容之后才执行

因此,我具有以下功能,该功能应该忘记一个按钮,迭代一个乐谱,等待一秒钟,然后将按钮放回原处。

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)正在冻结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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。