使用Python和TKinter移动选项

时间:2018-02-16 01:32:27

标签: python-3.x tkinter

我对编码很陌生,因为我的公司正在为我支付一些技术学费。我试图用Python TKinter项目中的箭头键来控制对象的速度时遇到了问题。有人可以看看下面的代码吗?任何建议将不胜感激。

 width = 1000
 height = 200
 radius = 20

 from tkinter import *

 class main():
     def __init__(self):
         window = Tk()
         window.title("Car")

         self.canvas = Canvas(window, bg = "white", width = width, height = height)
         self.canvas.pack()

#build car and speed control

         self.canvas.create_rectangle(10,100,210, 125, fill = "red", tags = "rect")
         self.canvas.create_rectangle(150, 50, 200, 100, fill = "blue", tags = "rect")
         self.canvas.create_oval(40 - radius, 200 - radius, 60 + radius, 100 + radius, fill = "black", tags = "oval")
         self.canvas.create_oval(160 - radius, 200 - radius, 180 + radius, 100 + radius, fill = "black", tags = "oval")
         self.canvas.bind('<Up>', self.up)
         self.canvas.bind('<Down>', self.down)
         self.canvas.focus_set()

    # start movement

         dx = 5
         x = 0
         while True:
             self.canvas.move("rect", dx, 0)
             self.canvas.after(100)
             self.canvas.update()
             self.canvas.move("oval", dx, 0)
             self.canvas.after(100)
             self.canvas.update()
             if x < width - 210:   #Test for end of screen
                 x += dx
             else:                  # delete and start animation again
                 x = 0
                 self.canvas.delete("rect")
                 self.canvas.delete("oval")
                 self.canvas.create_rectangle(10,100,210, 125, fill = "red", tags = "rect")
                 self.canvas.create_rectangle(150, 50, 200, 100, fill = "blue", tags = "rect")
                 self.canvas.create_oval(40 - radius, 200 - radius, 60 + radius, 100 + radius, fill = "black", tags = "oval")
                 self.canvas.create_oval(160 - radius, 200 - radius, 180 + radius, 100 + radius, fill = "black", tags = "oval")


         window.mainloop()


# define speed control functions

     def up(self,event):
         dx += 5

     def down(self,event):
         dx -= 5

1 个答案:

答案 0 :(得分:0)

到目前为止,您只定义了自己的班级main()。您需要在类定义下创建该类的实例,以便显示窗口。例如,您可以使用

初始化名为game的实例
game = main()

当你运行该代码时,你会看到你的窗口弹出。

您还会看到卡车只是向右移动,无论您是按下绑定功能的<Up>还是<Down>键。如果您有调试器,您可能会看到它生成UnboundLocalError并显示消息:

local variable 'dx' referenced before assignment

出现此错误,因为dx仅在main()的范围内定义。如果您想在整个班级中访问dx,请将每个dx更改为self.dx

如果再次运行程序,您应该会看到可以使用<Up><Down>键控制汽车的速度。

如果您遇到问题或想添加任何功能,请与我们联系。

-Jason