【问题标题】:How can I make udate_idletasks work on Mac如何使 update_idletasks 在 Mac 上工作
【发布时间】:2022-01-07 00:46:27
【问题描述】:

我编写了一个带有动画的 tkinter 脚本,在 Xubuntu 上运行良好,但是当我在 Mac 上运行它时,动画不起作用。这是一个演示问题的小脚本:

import tkinter as tk
from time import sleep

root = tk.Tk()
canvas = tk.Canvas(root, height=200, width = 200)
canvas.pack()

this = canvas.create_rectangle(25,25, 75, 75, fill='blue')
that = canvas.create_rectangle(125, 125, 175, 175, fill = 'red')

def blink(event):
    global this, that
    for _ in range(9):
        canvas.itemconfigure(this, fill='red')
        canvas.itemconfigure(that, fill = 'blue')
        canvas.update_idletasks()
        sleep(.4)
        this, that = that, this
        
canvas.bind('<ButtonRelease-1>', blink)

root.mainloop()

这会在画布上绘制一个红色方块和一个蓝色方块。当用户单击画布时,方块会反复切换颜色。在 Xubuntu 上,它按预期工作。

在 Mac 上,当我单击画布时,我得到了旋转的沙滩球,几秒钟后,我们看到方块已经切换了颜色,因为它们在代码中切换了奇数次。

在我看来 update_idletasks 不起作用。有没有办法解决这个问题?我在 Big Sur 上运行带有 Tk 8.6 的 python 3.9.5。

【问题讨论】:

  • 无论如何都要避免使用sleep(),而是与after()集成
  • @CoolCloud 好点。自从我上次做这样的事情以来已经有很长时间了。

标签: macos tkinter


【解决方案1】:

我认为你可以做的是避免会阻止mainloop 的任务,在这种情况下是time.sleep()。因此,您的代码可以通过使用after 模拟for 循环来重新制作,我没有看到任何阻止此通用代码运行独立于操作系统的东西:

count = 0 # Think of this as the `_` in for _ in range(9)
def blink(event=None):
    global this, that, count
    
    if count < 9: # Basically repeats everytime `count` is less than 9, like a for loop
        canvas.itemconfigure(this, fill='red')
        canvas.itemconfigure(that, fill='blue')

        this, that = that, this
        count += 1 # Increase count
        root.after(400,blink) # Repeat this code block every 400 ms or 0.4 seconds
    else: 
        count = 0 # After it is 9, set it to 0 for the next click to be processed

【讨论】:

    【解决方案2】:

    我发现使用update 而不是update_idletasks 在两个平台上都可以使用。不过,我的理解是后者更受欢迎。例如,请参阅this question 的已接受答案。这解决了我的直接问题,但有人知道update_idletasks 是否可以在 Mac 上运行?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-16
      • 2016-04-26
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      • 2012-08-26
      • 2022-07-22
      相关资源
      最近更新 更多