【问题标题】:Canvas update in tkintertkinter 中的画布更新
【发布时间】:2016-04-30 10:48:24
【问题描述】:

我是 tkinter 的新手,正在编写一个在画布上绘制五行的简单骨架程序。我希望在每个新行之后更新画布。我快到了(!),但是在计算完所有行之前,画布不会更新。所有关于如何修复我的代码的建议将不胜感激。谢谢!

from tkinter import *
from time import sleep

class app():
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=300, height=300)
        self.canvas.pack()   

        self.go()
        self.root.mainloop()

    def go(self):
        for i in range(5):
            self.drawLine(i)
            sleep(1) # simulate computation of next value

    def drawLine(self, n):
        self.canvas.create_line(0, 0, 50, n * 50 + 10)
        # now I would like canvas to be updated with the new line added

app()

【问题讨论】:

  • self.root.update() 在 drawLine 方法的末尾应该可以解决问题。
  • 谢谢,现在代码可以正常工作了。

标签: python tkinter


【解决方案1】:

sleep 与 tkinter 不兼容,因为它阻塞了事件循环。一起使用它们通常会导致您的 tkinter 窗口冻结。睡眠五秒钟可能会或可能不会在您的计算机上导致此问题,但仍然非常不可靠。如果您以后想显示 15 行而不是 5 行,那么您的程序几乎肯定会停止工作。

这里正确的解决方案是使用根对象的after 方法。 after 在一定时间内执行指定的函数。这是您的代码的一个工作示例:

from tkinter import *

class app():
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=300, height=300)
        self.canvas.pack()

        self.line_counter = 0
        self.draw_next_line()
        self.root.mainloop()

    def draw_next_line(self):
        self.canvas.create_line(0, 0, 50, self.line_counter * 50 + 10)
        self.line_counter += 1
        if self.line_counter != 5:
            # call this function again after 1000 milliseconds
            self.root.after(1000, self.draw_next_line)

app()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2019-12-30
    • 2018-05-07
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多