在mainloop()中更新Tkinter画布

时间:2018-12-06 15:54:21

标签: python-3.x tkinter tkinter-canvas

我试图在Tkinter中创建一个简单的冒泡排序可视化,但是我不知道如何更新画布/刷新。

from tkinter import *
import random
height, width = 350,600
randomLines = []
master = Tk()
w = Canvas(master,width=width,height=height)
w.pack()

def drawRandomLines():
    w.delete("all")
    for i in range(width):
        w.create_line(i,0,i,randomLines[i])

def bubbleSort():
    for passnum in range(len(randomLines)-1,0,-1):
        for i in range(passnum):
            if randomLines[i]>randomLines[i+1]:
                temp = randomLines[i]
                randomLines[i] = randomLines[i+1]
                randomLines[i+1] = temp

for i in range(width):
    rnd = random.randint(0,width)
    randomLines.append(rnd)
drawRandomLines()
bubbleSort()
mainloop()

如果我在bubbleSort()循环中使用drawRandomLines(),它将保留窗口并在显示画布之前不显示画布

3 个答案:

答案 0 :(得分:0)

您将要使用after()来管理不会影响主循环的更新循环。通过使用after(),我们可以随时间创建视觉更新。我们将需要一个跟踪变量来管理循环上​​的索引,并需要一个用于跟踪程序的全局语句。

示例:

from tkinter import *
import random
height, width = 350, 600
randomLines = []
master = Tk()
tracker = 0
w = Canvas(master, width=width, height=height)
w.pack()

def drawRandomLines():
    global tracker
    if tracker <= width:
        w.create_line(tracker, 0, tracker, randomLines[tracker])
        tracker += 1
        master.after(10, drawRandomLines)

def bubbleSort():
    for passnum in range(len(randomLines)-1, 0, -1):
        for i in range(passnum):
            if randomLines[i] > randomLines[i+1]:
                temp = randomLines[i]
                randomLines[i] = randomLines[i+1]
                randomLines[i+1] = temp

for i in range(width):
    rnd = random.randint(0, width)
    randomLines.append(rnd)
drawRandomLines()
bubbleSort()
mainloop()

答案 1 :(得分:0)

Tkinter不会更新窗口,直到完成重要任务的队列。因此,如果要每次迭代更新,则必须强制执行。试试这个:

def drawRandomLines():
    w.delete("all")
    for i in range(width):
        w.create_line(i,0,i,randomLines[i])
    w.update()   # Force canvas update

答案 2 :(得分:0)

您可以使用after()替换for中的外部bubbleSort()并在drawRandomLines()内调用bubbleSort()

from tkinter import *
import random

height, width = 350, 600
thickness = 5

# create the random lines
randomLines = [random.randint(1, height-1) for i in range(0, width, thickness)]

master = Tk()
w = Canvas(master, width=width, height=height)
w.pack()

def drawRandomLines():
    w.delete("all")
    for i in range(len(randomLines)):
        x = i * thickness
        # use bars for more clearly presentation
        w.create_rectangle(x, height, x+thickness, height-randomLines[i], fill='red')

def bubbleSort(passnum):
    for i in range(passnum):
        if randomLines[i] > randomLines[i+1]:
            randomLines[i], randomLines[i+1] = randomLines[i+1], randomLines[i]
    drawRandomLines()
    if passnum > 0:
        master.after(20, bubbleSort, passnum-1)
    else:
        w.create_text(50, 50, text='Done!', font=('Arial', 24))

drawRandomLines() # show initial order of lines
bubbleSort(len(randomLines)-1)

master.mainloop()