python-tkinter模块图形绘制、移动小程序(二)
2018-01-25 01:17
435 查看
挡板游戏:
原文地址:点击打开链接。
#__*__coding:utf-8__*__ #python3 from tkinter import * import random import time class Ball:#小球的类 def __init__(self,canvas,paddle,color): self.canvas=canvas#传递画布值 self.paddle=paddle#把挡板传递进来 self.id=canvas.create_oval(10,10,25,25,fill=color)#画椭圆并且保存其ID self.canvas.move(self.id,245,100) start=[-3,-2,-1,1,2,3] random.shuffle(start)#随机化列表 self.x=start[0] self.y=-3 self.canvas_heigh=self.canvas.winfo_height()#获取窗口高度并保存 self.canvas_width=self.canvas.winfo_width() def draw(self): self.canvas.move(self.id,self.x,self.y) pos=self.canvas.coords(self.id)#返回相应ID代表的图形的当前坐标(左上角和右上角坐标) #使得小球不会超出窗口 pad=self.canvas.coords(self.paddle.id)#获取挡板的坐标 if pos[1]<=0 : self.y=3 if pos[3]>=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]<=pad[2]): self.y=-3 if pos[0]<=0: self.x=3 if pos[2]>=self.canvas_width: self.x=-3 class Paddle:#挡板的类 def __init__(self,canvas,color): self.canvas=canvas self.color=color self.id=canvas.create_rectangle(0,0,100,10,fill=color) self.canvas.move(self.id,200,300) self.canvas_width=self.canvas.winfo_width() self.l=0 self.r=0 def draw(self): pos=self.canvas.coords(self.id) if pos[0]<=0: self.l=0 if pos[2]>=self.canvas_width: self.r=0 def turn_left(self,event): self.canvas.move(self.id,self.l,0) self.l=-20 def turn_right(self,event): self.canvas.move(self.id,self.r,0) self.r=20 tk=Tk() tk.title('Game') tk.resizable(0,0)#使得窗口大小不可调整 tk.wm_attributes('-topmost',1)#包含画布的窗口放在其他窗口的前面 canvas=Canvas(tk,width=500,height=400,bd=0,highlightthickness=0)#后面两个参数去掉边框 canvas.pack() tk.update() paddle=Paddle(canvas,'blue') ball=Ball(canvas,paddle,'red') canvas.bind_all('<KeyPress-Left>',paddle.turn_left)#绑定方向键 canvas.bind_all('<KeyPress-Right>',paddle.turn_right) while 1: ball.draw() paddle.draw() tk.update_idletasks()#快速重画屏幕 tk.update() time.sleep(0.01)
原文地址:点击打开链接。
相关文章推荐
- python-tkinter模块图形绘制、移动小程序(一)
- Python中使用Tkinter模块创建GUI程序实例
- Python图形界面编程---Tkinter模块使用
- python开发之tkinter实现图形随鼠标移动的方法
- python matplotlib模块——绘制三维图形、三维数据散点图
- 用python的tkinter模块写了个查询IP地址的小程序
- Python中使用Tkinter模块创建GUI程序实例
- Python图形界面编程---Tkinter模块基础
- python开发之tkinter实现图形随鼠标移动的方法
- python开发_tkinter_图形随鼠标移动
- python matplotlib模块——绘制三维图形、三维数据散点图
- Python实现在tkinter中使用matplotlib绘制图形的方法示例
- Python基本图形绘制
- python可视化模块tkinter
- python中的turtle库绘制图形
- Python Imaging Library: ImageTk Module(图像Tkinter模块)
- python数字图像处理(12):基本图形的绘制
- python的tkinter模块创建菜单需要先实例化菜单
- python图形界面:首选Tkinter
- Python tkinter模块弹出窗口及传值回到主窗口操作详解