I am having trouble setting the x position of an arc called "pac_man", and then changing it using = with a function called "xChange()".
I have tried multiple things, but I think using a dictionary would suffice. This is because the variable "coord" needs 4 values to assign shape and position for "pac_man."
#Imports
from tkinter import *
#Functions
def xChange():
print("Change the value of pac_man's x position here")
#Object Attributes
wn = Tk()
wn.geometry('512x320')
wn.title('Moving with Keys')
cvs = Canvas(wn, bg='limegreen', height=320, width=512)
coord = {'x_pos': 10, 'y_pos': 10, 'x_size': 50, 'y_size': 50}
pac_man = cvs.create_arc(
coord['x_pos'],
coord['y_pos'],
coord['x_size'],
coord['y_size'],
start=45,
extent=270,
fill='yellow',
outline='black',
width=4,
)
cvs.bind('<Right>', xChange)
cvs.pack()
CodePudding user response:
See comments in the code:
#Imports
from tkinter import *
#Functions
def move(event):#add event parameter
pixels = 1 #local variable, amount of pixels to "move"
direction = event.keysym #get keysym from event object
if direction == 'Right':#if keysym is Left
cvs.move('packman', pixels, 0)
#canvas has already a method for move, use it!
#move "packman" 1 pixel on the x-axis and 0 on the y-axis
#Window
wn = Tk()
wn.geometry('512x320')
wn.title('Moving with Keys')
#Canvas
cvs = Canvas(wn, bg='limegreen', height=320, width=512, takefocus=True)
#coord = {'x_pos': 10, 'y_pos': 10, 'x_size': 50, 'y_size': 50}
#tkinter stores these values in form of a list
#You can retrieve it with like this print(cvs['coords'])
pac_man = cvs.create_arc(
10,10,50,50,
start=45,
extent=270,
fill='yellow',
outline='black',
width=4,
tags=('packman',)#add a tag to access this item
#tags are tuple^!!
)
#cvs.bind('<Right>', xChange)
#You could bind to canvas but would've made sure
#that canvas has the keyboard focus
#it is easier to bind to the window
wn.bind('<Left>', move)
wn.bind('<Right>', move)
wn.bind('<Up>', move)
wn.bind('<Down>', move)
cvs.pack()
wn.mainloop()
Additional resource, in case you wonder. event parameter