python学习--canvas画布实现小球的自由移动

耐心研究了好久,终于实现小球的自由移动,以及边框检测结果 

from tkinter import *
from tkinter import messagebox      #必须另外导入该模块messagebox
class MovingBall:
    def __init__(self):
        window=Tk()
        window.title('移动小球')
        BallImage=PhotoImage(file='c:/pythondata/2.gif')        #小球的图片
        self.canvas=Canvas(window, bg='white', width=400, height=400)     #制作画布
        self.canvas.pack()
        self.canvas.create_image((200,200),image=BallImage,tags='image')    #初始位置居中
        self.x=200
        self.y=200

        frame=Frame(window)
        frame.pack(padx=0,pady=0)
        btLeft = Button(window, text='Left', command=self.Left)
        btLeft.pack(side=LEFT)
        btRight = Button(window, text='Rigth', command=self.Right)
        btRight.pack(side=LEFT)
        btUp = Button(window, text='Up', command=self.Up)
        btUp.pack(side=LEFT)
        btDown = Button(window, text='Down', command=self.Down)
        btDown.pack(side=LEFT)

        window.mainloop()
    def Left(self):
        if self.x > 20:              #需要根据位置及图像大小数据进行调整
            self.Moving(-10, 0)
            self.x -= 10
        else:
            self.Back()

    def Right(self):
        if self.x < 390:
            self.Moving(10, 0)
            self.x += 10
        else:
            self.Back()
    def Up(self):
        if self.y > 20:
            self.Moving(0, -10)
            self.y -= 10
        else:
            self.Back()
    def Down(self):
        if self.y < 390:
            self.Moving(0, 10)
            self.y += 10
        else:
            self.Back()
#移动方法
    def Moving(self, dx1, dx2):
        self.canvas.move('image', dx1, dx2)
#边缘检测方法
    def Back(self):
        messagebox.showinfo(title='提示',message="已到边框")
MovingBall()

结果: 

         

猜你喜欢

转载自blog.csdn.net/weixin_44372245/article/details/117902476