Python,使用箭头键移动对象

时间:2019-02-26 16:08:16

标签: python

我需要使用Python创建一个对象(特别是椭圆形),该对象可以自行移动或使用户能够使用箭头键移动该对象。我需要使用这两个def

import tkinter 
def motion():
    if m==1:
        can.move (id, 0,-5)
    elif m==3:
        can.move (id,0, 5)
    elif m==0:
        can.move (id,5, 0)
    else:
        can.move (id, - 5,0)
    can.after (50, motion)
def arrows (event):
    global m
    if event.keysym=='Up':
        m==1
    elif event.keysym=='Down':
        m==3
    elif event.keysym=='Right':
        m==0
    else:
        m==2
can=tkinter.Canvas (width=800,height=800)
can.pack ()
id=can.create_oval (100,100,150,150) 
can.bind ('<Button-1>',motion)
can.bind_all ('<Key>', arrows) 

1 个答案:

答案 0 :(得分:0)

好的,这就是我需要的。

import tkinter 
def motion():
      if m==1:
           can.move (id, 0,-5)
      elif m==3:
           can.move (id,0, 5)
      elif m==0:
           can.move (id,5, 0)
      else:
           can.move (id, - 5,0)
      can.after (50, motion)
def arrows (event):
    global m
    if event.keysym=='Up':
          m=1
    elif event.keysym=='Down':
          m=3
    elif event.keysym=='Right':
          m=0
    else:
          m=2
can=tkinter.Canvas (width=800,height=800)
can.pack ()
id=can.create_oval (100,100,150,150) 
m=3
motion () 
can bind ('<Button-1>',motion)
can.bind_all ('<Key>', arrows)