简体   繁体   中英

Pausing a GUI Python program

I am trying to create a simple sorting visualizer in python using Tkinter . With that being said, I would like the user to be able to see the changes that occur in each iteration of the sorting algorithm (whatever algorithm is used) and in order to do so, I have to "pause" the program for the user to see the changes each tick.

It's the "pausing" part that confuses me. I looked into time.sleep which is irrelevant for GUI programs (due to the mainloop) and after() in the Tkinter library, but I can't seem to get it right.

My code:

arr = [random.randint(0,600) for i in range(100)]


WIN_WIDTH = 1200
WIN_HEIGHT = 800


BAR_NUM = len(arr)
BAR_WIDTH = WIN_WIDTH // BAR_NUM

class sortVisualizer(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        canvas = tk.Canvas(root,width=WIN_WIDTH,height=WIN_HEIGHT)

        self.draw(canvas)
        canvas.pack()

        queue = [self.bubbleSort(canvas)] //theres going to be more than just one sorting algorithm
        queue[0]

    def re_draw(self,canvas,index1,index2):

        canvas.delete("all")

        temp = arr[index1]
        arr[index1] = arr[index2]
        arr[index2] = temp

        for i in range(BAR_NUM):
            canvas.create_rectangle(BAR_WIDTH * i,
                                    WIN_HEIGHT - arr[i],
                                    BAR_WIDTH * (i+1),
                                    WIN_HEIGHT,
                                    fill = "white")

        canvas.pack()

    def bubbleSort(self,canvas):
        for item in range(len(arr)-1,0,-1):
            for i in range(item):
                if (arr[i] > arr[i+1]):
                    self.re_draw(canvas,i,i+1)

There are a few other functions in the sortVisualizer class but they are irrelevant.

So my question is: how will I be able to "pause" or "stop" the program in order for the user to be see the changes in each tick?

Following @Mike - SMT 's comment, I used root.update() at the end of the bubbleSort function as so:

def bubbleSort(self,canvas):
    for item in range(len(arr)-1,0,-1):
        for i in range(item):
            if (arr[i] > arr[i+1]):
                self.re_draw(canvas,i,i+1)
                root.update()

This not only "paused" or "stopped" or showed the progression of the program but also brought up the program's window and allowed for the graphics to be updated from within the mainloop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM