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.
1 Answer 1
You have a few errors in your code. As the error says, you don't have canvas variable in your moved method. Also, player is also not defined in your moved method.
Assign the canvas to a class variable either in __init__ or in player method:
def player(self,canvas,x,y,xx,yy,color):
self.canvas = canvas
self.player = canvas.create_rectangle(x,y,xx,yy,fill=color)
Then use that:
def moved(self,x,y):
self.canvas.move(self.player,x,y)
You don't need to pass player1:
player1.moved(100, 200)
on_clickinon_click? Hope that is a formatting errormovemethod as you don't havecanvasdefined anywhere that's considered local tomove. Did you want to include thecanvasparameter?pynputif you can assign mouse button to function usingtkinter- something likebind("<Button-1>", on_mouse_click)