Python程序开发之简单小程序实例
(11)小 游戏 -跳动的小球
一、项目功能
二、项目分析
根据项目功能自定义两个类,一个用于控制小球在窗体中的运动,一个用于接收用户按下左右键时,挡板在窗体中的运动。在控制小球的类中,我们还需要考虑当小球下降时,碰到挡板时的位置判断。
三、程序源代码
源码部分截图:
源码:
#!/usr/bin/python3.6
# -*- coding: GBK -*-
#导入相应模块
from tkinter import *
import random
import time
#自定义小球的类 Ball
class Ball:
# 初始化
def __init__(self,canvas,paddle,color):
#传递画布值
self.canvas=canvas
#传递挡板值
self.paddle=paddle
#画圆并且保存其ID
self.id=canvas.create_oval(10,10,25,25,fill=color)
self.canvas.move(self.id,245,100)
#小球的水平位置起始列表
start=[-3,-2,-1,1,2,3]
#随机化位置列表
random.shuffle(start)
self.x=start[0]
self.y=-2
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]=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]
可以参考这个:from tkinter import *
from time import time, localtime, strftime
class ToolTip( Toplevel ):
"""
Provides a ToolTip widget for Tkinter.
To apply a ToolTip to any Tkinter widget, simply pass the widget to the
ToolTip constructor
"""
def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ):
"""
Initialize the ToolTip
Arguments:
wdgt: The widget this ToolTip is assigned to
msg: A static string message assigned to the ToolTip
msgFunc: A function that retrieves a string to use as the ToolTip text
delay: The delay in seconds before the ToolTip appears(may be float)
follow: If True, the ToolTip follows motion, otherwise hides
"""
self.wdgt = wdgt
self.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widget
Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevel
self.withdraw() # Hide initially
self.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title bar
self.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip
if msg == None:
self.msgVar.set( 'No message provided' )
else:
self.msgVar.set( msg )
self.msgFunc = msgFunc
self.delay = delay
self.follow = follow
self.visible = 0
self.lastMotion = 0
Message( self, textvariable=self.msgVar, bg='#FFFFDD',
aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widget
self.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already has
self.wdgt.bind( '<Leave>', self.hide, '+' )
self.wdgt.bind( '<Motion>', self.move, '+' )
def spawn( self, event=None ):
"""
Spawn the ToolTip. This simply makes the ToolTip eligible for display.
Usually this is caused by entering the widget
Arguments:
event: The event that called this funciton
"""
self.visible = 1
self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in miliseconds
def show( self ):
"""
Displays the ToolTip if the time delay has been long enough
"""
if self.visible == 1 and time() - self.lastMotion > self.delay:
self.visible = 2
if self.visible == 2:
self.deiconify()
def move( self, event ):
"""
Processes motion within the widget.
Arguments:
event: The event that called this function
"""
self.lastMotion = time()
if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapear
self.withdraw()
self.visible = 1
self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointer
try:
self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function fails
except:
pass
self.after( int( self.delay * 1000 ), self.show )
def hide( self, event=None ):
"""
Hides the ToolTip. Usually this is caused by leaving the widget
Arguments:
event: The event that called this function
"""
self.visible = 0
self.withdraw()
def xrange2d( n,m ):
"""
Returns a generator of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A generator of values in a 2d range
"""
return ( (i,j) for i in xrange(n) for j in xrange(m) )
def range2d( n,m ):
"""
Returns a list of values in a 2d range
Arguments:
n: The number of rows in the 2d range
m: The number of columns in the 2d range
Returns:
A list of values in a 2d range
"""
return [(i,j) for i in range(n) for j in range(m) ]
def print_time():
"""
Prints the current time in the following format:
HH:MM:SS.00
"""
t = time()
timeString = 'time='
timeString += strftime( '%H:%M:', localtime(t) )
timeString += '%.2f' % ( t%60, )
return timeString
def main():
root = Tk()
btnList = []
for (i,j) in range2d( 6, 4 ):
text = 'delay=%i\n' % i
delay = i
if j >= 2:
follow=True
text += '+follow\n'
else:
follow = False
text += '-follow\n'
if j % 2 == 0:
msg = None
msgFunc = print_time
text += 'Message Function'
else:
msg = 'Button at %s' % str( (i,j) )
msgFunc = None
text += 'Static Message'
btnList.append( Button( root, text=text ) )
ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay)
btnList[-1].grid( row=i, column=j, sticky=N+S+E+W )
root.mainloop()
if __name__ == '__main__':
main()
跳动爱心代码Python软件。
带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,比如调试、语法高亮、项目管理、代码跳转、智能提示、自动完成、单元测试、版本控制。
可以让苹果手机用户直接去进行爱心代码编写的手机软件,各种编写方式都可以随时去开启,不仅可以让用户体验到更多全面的使用服务,还有最新的爱心玩法都可以尽享。
优点:
简单:Python是一种代表简单主义思想的语言。阅读一个良好的Python程序就感觉像是在读英语一样。它使你能够专注于解决问题而不是去搞明白语言本身。
易学:Python极其容易上手,因为Python有极其简单的说明文档。
易读、易维护:风格清晰划一、强制缩进。
速度较快:Python的底层是用C语言写的,很多标准库和第三方库也都是用C写的,运行速度非常快。