如何使用绑定来改变圆弧的位置?



我在设置一个名为"pac_man"的弧的x位置时遇到了问题,然后使用+=和一个名为"xChange()"的函数来更改它。

我尝试了很多方法,但我认为使用字典就足够了。这是因为变量"需要4个值来指定"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()

见代码注释:

#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()

额外的资源,如果你想知道的话。事件参数

最新更新