Home > OS >  Tkinter - unable to move polygon on the screen
Tkinter - unable to move polygon on the screen

Time:08-02

I'm learning Python and I decided to make a GUI. It's a simple GUI that'll just move a polygon on the screen. But it seems the thread keep getting stuck in the update method.

class main():

    render = Render(500, 500)

    while True:
        render.update()
        time.sleep(1)


class Render:

    def __init__(self, width, height):
        self.window = Tk()
        self.window.config(height=500, width=500)
        self.canvas = Canvas(self.window, width = width, height = height, 
                             background = "white")
        self.deltaX = 0


    def update(self):
        print(self.deltaX)
        self.canvas.create_polygon(150   self.deltaX, 75, 225   self.deltaX, 0, 
                                   300   self.deltaX, 75, 225   self.deltaX, 150, 
                                   outline = "black", fill = "")
        self.canvas.pack()
        self.window = mainloop()
        self.deltaX  = 10
        return None

Sorry if this is dumb, but I'm very new to Python.

CodePudding user response:

You shouldn't call mainloop like that, probably you should only call it once. See Tkinter understanding mainloop

CodePudding user response:

There's a couple ways to write this out. No matter how you do it you only need to call/draw the object once and then update it through your loop

It can be as simple as creating a property in the constructor and then updating via a method

from tkinter import *
import time

class Render:

    def __init__(self, width, height):
        self.window = Tk()
        self.window.config(height=500, width=500)
        self.canvas = Canvas(self.window, width = width, height = height, 
                             background = "white")
        self.deltaX = 2
        self.poly = self.canvas.create_polygon(150   self.deltaX, 75, 225   self.deltaX, 0, 
                                   300   self.deltaX, 75, 225   self.deltaX, 150, 
                                   outline = "black", fill = "")
        self.canvas.pack()
    def update(self):
        self.canvas.move(self.poly, self.deltaX, 0)
        self.window.update()    


class main():

    render = Render(500, 500)

    while True:
        render.update()
        time.sleep(1)
  • Related