[Python] Using move method from canvas on object created from another class

Discussão em 'Python' iniciado por Stack, Agosto 21, 2025.

  1. Stack

    Stack Membro Participativo

    I created a class called Player in a player.py file. The class creates a rectangle when called and I am trying to use canvas.move using the created object in my main.py file. So I created object as player1 = player.Player(). I pass in the coords and color and the object is created just fine, but when I try to use a move method from Player it says canvas is not in move. And will not accept anything.

    from player import *
    from tkinter import *
    colors = ["blue","red","yellow","purple","black","gray"]
    positions = [(10,20,30,40),(100,110,120,130),(200,210,220,230),(300,310,320,330),(400,410,420,430)]
    other_positions = [(600,610,620,630),(700,710,720,730),(800,810,820,830),(900,910,920,930),(1000,1010,1020,1030)]

    xx, yy = 0, 0

    window = Tk()
    canvas = Canvas(width=1200,height=1000,bg="green")

    canvas.pack()
    text = 10
    xx,yy = 0,0




    player1 = Player()
    player1.player(canvas,10,20,30,50,colors[4])
    plays = canvas.bbox(player1)
    #player1.moved(player1,100,200)
    canvas.move(player1,500,500)



    from tkinter import *
    from PIL import Image,ImageTk
    import random
    from tkinter import ttk
    from pynput.mouse import Button, Controller,Listener

    class Player:


    def __init__(self):
    # self.color = self.colors[c]
    # self.positon = self.positions[p]
    self.x = 0
    self.y = 0

    def on_click(selfx,y,button,pressed):


    def on_click(x, y, button, pressed):
    global xx, yy
    xx, yy = x, y
    print('{0} at {1}'.format(
    'Pressed' if pressed else 'Released',
    (x, y)))
    if not pressed:
    # Stop listener
    return False

    with Listener(on_click=on_click) as listener:
    listener.join()
    # here you can read xx and yy

    def player(self,canvas,x,y,xx,yy,color):
    canvas.create_rectangle(x,y,xx,yy,fill=color)
    def moved(self,x,y):
    canvas.move(player,x,y)
    def position(self, pynput=None):

    # with Listener(on_click=self.on_click) as listener:
    #listener.join()
    mouse = Controller()




    I've tried to use self.canvas and tried using variable as coords but no luck. If I create a function in main.py to create rectangle and move it it's just fine.

    Continue reading...

Compartilhe esta Página