单击按钮,弹球开始弹来弹去,碰到画布的边缘会反弹。请同学们把程序修改成多个彩色弹球的版本。
import time from tkinter import * from tkinter import messagebox def ball_born(): t = messagebox.askyesno('这是标题','要弹球出世吗?') if not t: return b1.configure(state=DISABLED) dx = 10 dy = 10 # left,top,right,bottom ball = canvas.create_oval(50,50,100,100,fill='red',width=5) while True: canvas.move(ball,dx,dy) # 移动球水平,垂直 left,top,right,bottom = canvas.coords(ball) # 获取ball的最小矩形 if left<=0 or right>=480:dx= -dx if top<=0 or bottom>=360:dy= -dy canvas.update() time.sleep(0.01) root = Tk() # Tk是一个类,实例化一个窗口 root.title('tkinter弹球基础') root.geometry('480x400') root.config(bg='yellow') b1 = Button(root,text='开始弹球',command=ball_born) b1.pack(side=TOP) # RIGHT,TOP,BOTTOM ##speeds = [[1,2],[2,3],[-1,2]] ##speeds[0][0] ##speeds[0][1] canvas = Canvas(root,width=480,height=360,bg='cyan') canvas.pack() root.mainloop()
发表评论