python中使用绑定来更改圆弧的位置

python无法设置名为“pac_man”的弧的 x 位置,然后使用带有名为“xChange()”的函数的 += 更改它。

我尝试了多种方法,但我认为使用字典就足够了。这是因为变量“coord”需要 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()

转载:http://www.szwzim.cn/bcjs/52.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值