【完结篇】《Python GUI设计 tkinter菜鸟编程》配套代码 第19章 Canvas

这些Python脚本展示了如何利用Tkinter库创建各种图形,包括线条、矩形、椭圆、多边形、文字以及动态移动的图形。它们涉及到基本图形绘制、颜色填充、线型样式、文本标注以及图片显示等功能。通过这些例子,可以了解到Tkinter在图形用户界面设计中的基本用法。
摘要由CSDN通过智能技术生成

ch19_1.py

# ch19_1.py
from tkinter import *
import math

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
x_center, y_center, r = 320, 240, 100
x, y = [], []
for i in range(12):    # 建立圆外围12个点
    x.append(x_center + r * math.cos(30*i*math.pi/180))   # x = x0 + r * cos(A)
    y.append(y_center + r * math.sin(30*i*math.pi/180))   # y = y0 + r * sin(A)
for i in range(12):    # 将12个点彼此连线
    for j in range(12):
        canvas.create_line(x[i],y[i],x[j],y[j])

tk.mainloop()

ch19_2.py

# ch19_2.py
from tkinter import *
import math

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
canvas.create_line(100,100,500,100)
canvas.create_line(100,125,500,125,width=5)
canvas.create_line(100,150,500,150,width=10,fill='blue')
canvas.create_line(100,175,500,175,dash=(10,2,2,2))    

tk.mainloop()

ch19_3.py

# ch19_3.py
from tkinter import *
import math

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
canvas.create_line(30,30,500,30,265,100,30,30,
                    width=20,joinstyle=ROUND)
canvas.create_line(30,130,500,130,265,200,30,130,
                    width=20,joinstyle=BEVEL)
canvas.create_line(30,230,500,230,265,300,30,230,
                    width=20,joinstyle=MITER)
tk.mainloop()

ch19_4.py

# ch19_4.py
from tkinter import *
import math

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
canvas.create_line(30,30,500,30,width=10,capstyle=BUTT)

canvas.create_line(30,130,500,130,width=10,capstyle=ROUND)

canvas.create_line(30,230,500,230,width=10,capstyle=PROJECTING)
# 以下是垂直线
canvas.create_line(40,20,40,240)
canvas.create_line(500,20,500,250)

tk.mainloop()

ch19_5.py

# ch19_5.py
from tkinter import *
import math

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()

canvas.create_line(30,30,500,30,width=50,stipple="gray25")
canvas.create_line(30,130,500,130,width=50,stipple="questhead")
canvas.create_line(30,230,500,230,width=50,stipple="info")
tk.mainloop()

ch19_6.py

# ch19_6.py
from tkinter import * 
from random import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
for i in range(20):
    x1, y1 = randint(1,640), randint(1,480)
    x2, y2 = randint(1,640), randint(1,480)
    if x1 > x2:
        x1,x2 = x2,x1
    if y1 > y2: 
        y1,y2 = y2,y1
    canvas.create_rectangle(x1,y1,x2,y2)
    # canvas.create_line(x1,y1,x2,y2)

tk.mainloop()

ch19_7.py

# ch19_7.py
from tkinter import * 
from random import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
canvas.create_rectangle(10,10,120,60,fill="red")
canvas.create_rectangle(130,10,200,80,fill="yellow",outline='blue')
canvas.create_rectangle(210,10,300,60,fill="green",outline='grey')

tk.mainloop()

ch19_8.py

# ch19_8.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
# 以下以圆形为基础
canvas.create_arc(10, 10, 110, 110, extent=45, style=ARC)
canvas.create_arc(210, 10, 310, 110, extent=90, style=ARC)
canvas.create_arc(410, 10, 510, 110, extent=180, fill="yellow")
canvas.create_arc(10, 110, 110, 210, extent=270, style=ARC)
canvas.create_arc(210, 110, 310, 210, extent=359, style=ARC, width=5)
# 以下以椭圆形为基础
canvas.create_arc(10, 250, 310, 350, extent=90, style=ARC, start=90)
canvas.create_arc(320, 250, 620, 350, extent=180, style=ARC)
canvas.create_arc(10, 360, 310, 460, extent=270, style=ARC, outline="blue")
canvas.create_arc(320, 360, 620, 460, extent=359, style=ARC)

tk.mainloop()

ch19_9.py

# ch19_9.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
# 以下以圆形为基础
canvas.create_arc(10, 10, 110, 110, extent=180, style=ARC)
canvas.create_arc(210, 10, 310, 110, extent=180, style=CHORD)
canvas.create_arc(410, 10, 510, 110, start=30, extent=120, style=PIESLICE)

tk.mainloop()

ch19_10.py

# ch19_10.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()
# 以下是圆形
canvas.create_oval(10, 10, 110, 110)
canvas.create_oval(150, 10, 300, 160,fill="yellow")
# 以下是椭圆形
canvas.create_oval(10, 200, 310, 350)
canvas.create_oval(350, 200, 550, 300,fill="aqua",outline="blue",width=5)

tk.mainloop()

ch19_11.py

# ch19_11.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()

canvas.create_polygon(10,10, 100,10, 50,80, fill='',outline='black')
canvas.create_polygon(120,10, 180,30, 250,100, 200,90, 130,80)

canvas.create_polygon(200,10, 350,30, 420,70, 360,90,fill='aqua')
canvas.create_polygon(400,10, 600, 10,450,80,width=5,outline="blue",fill='yellow')

tk.mainloop()

ch19_12.py

# ch19_12.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=480)
canvas.pack()

myStr = "Ming-Chi Institute of Technology"

canvas.create_text(200, 50, text=myStr)
canvas.create_text(200, 80, text=myStr, fill='blue')
canvas.create_text(300, 120, text=myStr, fill='blue',
                    font=('Old English Text MT',20))

tk.mainloop()

ch19_13.py

# ch19_13.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk, width=640, height=240, bg='yellow')
canvas.pack()

tk.mainloop()

ch19_14.py

# ch19_14.py
from tkinter import * 
from PIL import Image, ImageTk

tk = Tk()
img = Image.open("kobe.jpg")
myPic = ImageTk.PhotoImage(img)

canvas = Canvas(tk, width=img.size[0]+40,
                height=img.size[1]+30, bg='yellow')
canvas.create_image(200,15,anchor=NW,image=myPic)
canvas.pack(fill=BOTH,expand=True)

tk.mainloop()

ch19_15.py

# ch19_15.py
from tkinter import * 
def paint(event):              # 拖曳可以绘图
    x1,y1 = (event.x,event.y)  # 设置左上角坐标
    x2,y2 = (event.x,event.y)  # 设置右下角坐标

    x1,y1 = (event.x-1,event.y-1)  # 设置左上角坐标
    x2,y2 = (event.x+1,event.y+1)  # 设置右下角坐标

    canvas.create_oval(x1,y1,x2,y2,fill="blue")
def cls():                     # 清除画面
    canvas.delete("all")

tk = Tk()
lab = Label(tk,text='拖曳鼠标可以绘图')      # 建立标题
lab.pack()
canvas = Canvas(tk,width=640, height=300)  # 建立画布
canvas.pack()

btn = Button(tk,text="清除",command=cls)    # 建立“清除”按钮
btn.pack(pady=5)

canvas.bind("<B1-Motion>",paint)            # 鼠标拖曳绑定paint

tk.mainloop()

ch19_16.py

# ch19_16.py
from tkinter import * 
import time

tk = Tk()
canvas = Canvas(tk,width=500, height=150)  # 建立画布
canvas.pack()
canvas.create_oval(10,50,60,100,fill="yellow",outline='lightgray')
for x in range(0,80):
    canvas.move(1,5,0)   # ID=1  x轴移动5像素,y轴不变
    tk.update()          # 强制tkinter重绘
    time.sleep(0.05)

# tk.mainloop()

ch19_17.py

# ch19_17.py
from tkinter import * 
import time

tk = Tk()
canvas = Canvas(tk,width=500, height=300)  # 建立画布
canvas.pack()
canvas.create_oval(10,50,60,100,fill="yellow",outline='lightgray')
for x in range(0,80):
    canvas.move(1,5,2)   # ID=1  x轴移动5像素,y轴移动2像素
    tk.update()          # 强制tkinter重绘
    time.sleep(0.05)

# tk.mainloop()

ch19_18.py

# ch19_18.py
from tkinter import * 
import time

tk = Tk()
canvas = Canvas(tk,width=500, height=250)  # 建立画布
canvas.pack()
id1 = canvas.create_oval(10,50,60,100,fill="yellow")
id2 = canvas.create_oval(10,150,60,200,fill="aqua")
for x in range(0,80):
    canvas.move(id1,5,0) 
    canvas.move(id2,5,0)   # ID=1  x轴移动5像素,y轴移动2像素
    tk.update()          # 强制tkinter重绘
    time.sleep(0.05)

# tk.mainloop()

ch19_19.py

# ch19_19.py
from tkinter import * 
import time
from random import * 

tk = Tk()
canvas = Canvas(tk,width=500, height=250)  # 建立画布
canvas.pack()
id1 = canvas.create_oval(10,50,60,100,fill="yellow")
id2 = canvas.create_oval(10,150,60,200,fill="aqua")

for x in range(0,100):
    if randint(1,100) > 70:
        canvas.move(id2,5,0) 
    else:
        canvas.move(id1,5,0)   # ID=1  x轴移动5像素,y轴移动2像素
    tk.update()          # 强制tkinter重绘
    time.sleep(0.05)

# tk.mainloop()

ch19_20.py

# ch19_20.py
from tkinter import * 
import time
def ballMove(event):
    if event.keysym == 'Left':   # 左移 ################################
        canvas.move(1, -5, 0)
    if event.keysym == 'Right':  # 右移
        canvas.move(1, 5, 0)
    if event.keysym == 'Up':     # 上移
        canvas.move(1, 0, -5)
    if event.keysym == 'Down':  # 左移
        canvas.move(1, 0, 5)
tk = Tk()
canvas = Canvas(tk,width=500, height=300)  # 建立画布
canvas.pack()
canvas.create_oval(225,125,275,175,fill="red")
canvas.bind_all('<KeyPress-Left>',ballMove)
canvas.bind_all('<KeyPress-Right>',ballMove)
canvas.bind_all('<KeyPress-Up>',ballMove)
canvas.bind_all('<KeyPress-Down>',ballMove)
mainloop()
# tk.mainloop()

ch19_21.py

# ch19_21.py
from tkinter import * 
from random import * 
import time 

class Ball:#class Ball():#这样写是一样的
    def __init__(self,canvas,color,winW,winH):
        self.canvas = canvas
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
    def ballMove(self):
        self.canvas.move(self.id, 0, step)        # step是正值表示往下移动

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.03    # 设置移动速度

tk = Tk()
tk.title("Bouncing Ball")                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH)  # 建立画布
canvas.pack()
tk.update()   

ball = Ball(canvas,'yellow',winW,winH)  # 定义球对象

while True:
    ball.ballMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

# tk.mainloop()

ch19_22.py

# ch19_22.py
from tkinter import * 

tk = Tk()
canvas = Canvas(tk,width=500, height=150)  
canvas.pack()
oval_id = canvas.create_oval(10,50,60,100,fill='yellow',outline='lightgray')
ballPos = canvas.coords(oval_id)
print(ballPos)  # [10.0, 50.0, 60.0, 100.0]

ch19_23.py

# ch19_23.py
from tkinter import * 
from random import * 
import time 

class Ball:#class Ball():#这样写是一样的
    def __init__(self,canvas,color,winW,winH):
        self.canvas = canvas
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
        self.x = 0     # 水平不移动
        self.y = step  # 垂直移动单位
    def ballMove(self):
        self.canvas.move(self.id, self.x, self.y)        # step是正值表示往下移动
        ballPos = self.canvas.coords(self.id)
        if ballPos[1] <= 0:
            self.y = step
        if ballPos[3] >= winH:
            self.y = -step

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.03    # 设置移动速度

tk = Tk()
tk.title("Bouncing Ball")                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH)  # 建立画布
canvas.pack()
tk.update()   

ball = Ball(canvas,'yellow',winW,winH)  # 定义球对象

while True:
    ball.ballMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

# tk.mainloop()

ch19_24.py

# ch19_24.py 
from tkinter import * 
from random import * 
import time 

class Ball:#class Ball():#这样写是一样的
    def __init__(self,canvas,color,winW,winH):
        self.canvas = canvas
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
        startPos = [-4, -3, -2, -1, 1, 2, 3, 4]   # 球最初x轴位移的随机数
        shuffle(startPos)                         # 打乱排序
        self.x = startPos[0]                      # 球最初水平移动单位
        self.y = step                             # 垂直移动单位

    def ballMove(self):
        self.canvas.move(self.id, self.x, self.y)        # step是正值表示往下移动
        ballPos = self.canvas.coords(self.id)
        if ballPos[0] <= 0:          # 侦测球是否超过画布左方
            self.x = step       
        if ballPos[1] <= 0:          # 侦测球是否超过画布上方
            self.y = step
        if ballPos[2] >= winW:       # 侦测球是否超过画布右方
            self.x = -step           
        if ballPos[3] >= winH:       # 侦测球是否超过画布下方
            self.y = -step

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.03    # 设置移动速度

tk = Tk()
tk.title("Bouncing Ball")                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH)  # 建立画布
canvas.pack()
tk.update()   

ball = Ball(canvas,'yellow',winW,winH)  # 定义球对象

while True:
    ball.ballMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

# tk.mainloop()

ch19_25.py

# ch19_25.py 
from tkinter import * 
from random import * 
import time 

class Ball:#class Ball():#这样写是一样的
    def __init__(self,canvas,color,winW,winH):
        self.canvas = canvas
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
        startPos = [-4, -3, -2, -1, 1, 2, 3, 4]   # 球最初x轴位移的随机数
        shuffle(startPos)                         # 打乱排序
        self.x = startPos[0]                      # 球最初水平移动单位
        self.y = step                             # 垂直移动单位
    def ballMove(self):
        self.canvas.move(self.id, self.x, self.y)        # step是正值表示往下移动
        ballPos = self.canvas.coords(self.id)
        if ballPos[0] <= 0:          # 侦测球是否超过画布左方
            self.x = step       
        if ballPos[1] <= 0:          # 侦测球是否超过画布上方
            self.y = step
        if ballPos[2] >= winW:       # 侦测球是否超过画布右方
            self.x = -step           
        if ballPos[3] >= winH:       # 侦测球是否超过画布下方
            self.y = -step
class Racket():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0,0,100,15,fill=color)  # 球拍对象
        self.canvas.move(self.id, 270, 400)

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.03    # 设置移动速度

tk = Tk()
tk.title("Bouncing Ball")                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH)  # 建立画布
canvas.pack()
tk.update()   

ball = Ball(canvas,'yellow',winW,winH)  # 定义球对象
racket = Racket(canvas,'purple')        # 定义紫色球拍
while True:
    ball.ballMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

# tk.mainloop()

ch19_26.py

# ch19_26.py 
from tkinter import * 
from random import * 
import time 

class Ball:#class Ball():#这样写是一样的
    def __init__(self,canvas,color,winW,winH):
        self.canvas = canvas
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
        startPos = [-4, -3, -2, -1, 1, 2, 3, 4]   # 球最初x轴位移的随机数
        shuffle(startPos)                         # 打乱排序
        self.x = startPos[0]                      # 球最初水平移动单位
        self.y = step                             # 垂直移动单位
    def ballMove(self):
        self.canvas.move(self.id, self.x, self.y)        # step是正值表示往下移动
        ballPos = self.canvas.coords(self.id)
        if ballPos[0] <= 0:          # 侦测球是否超过画布左方
            self.x = step       
        if ballPos[1] <= 0:          # 侦测球是否超过画布上方
            self.y = step
        if ballPos[2] >= winW:       # 侦测球是否超过画布右方
            self.x = -step           
        if ballPos[3] >= winH:       # 侦测球是否超过画布下方
            self.y = -step
class Racket():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0,0,100,15,fill=color)  # 球拍对象
        self.canvas.move(self.id, 270, 400)
        self.x = 0
        self.canvas.bind_all('<KeyPress-Right>',self.moveRight)   # 绑定按住右键 ##########################
        self.canvas.bind_all('<KeyPress-Left>',self.moveLeft)     # 绑定按住左键
    def racketMove(self):
        self.canvas.move(self.id,self.x,0)
        pos = self.canvas.coords(self.id)
        # self.x = 0
        if pos[0] <= 0:
            self.x = 0
        elif pos[2] >= winW:
            self.x = 0
    def moveLeft(self,event):
        print("按下左键")
        self.x = -3
    def moveRight(self,event):
        print("按下右键")
        self.x = 3

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.03    # 设置移动速度

tk = Tk()
tk.title("Bouncing Ball")                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH)  # 建立画布
canvas.pack()
tk.update()   

# 以下两行代码执行顺序决定了两者重合时哪一个对象被遮挡
racket = Racket(canvas,'purple')        # 定义紫色球拍
ball = Ball(canvas,'yellow',winW,winH)  # 定义球对象

while True:
    ball.ballMove()
    racket.racketMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

# tk.mainloop()

ch19_27.py

# ch19_27.py 
from tkinter import * 
from random import * 
import time 

class Ball:#class Ball():#这样写是一样的
    def __init__(self,canvas,color,winW,winH,racket):
        self.canvas = canvas
        self.racket = racket
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
        startPos = [-4, -3, -2, -1, 1, 2, 3, 4]   # 球最初x轴位移的随机数
        shuffle(startPos)                         # 打乱排序
        self.x = startPos[0]                      # 球最初水平移动单位
        self.y = step                             # 垂直移动单位
    def hitRacket(self,ballPos):
        racketPos = self.canvas.coords(self.racket.id)
        if ballPos[2] >= racketPos[0] and ballPos[0] <= racketPos[2]:
            if ballPos[3] >= racketPos[1] and ballPos[3] <= racketPos[3]:
                return True
        return False
    def ballMove(self):
        self.canvas.move(self.id, self.x, self.y)        # step是正值表示往下移动
        ballPos = self.canvas.coords(self.id)
        if ballPos[0] <= 0:          # 侦测球是否超过画布左方
            self.x = step       
        if ballPos[1] <= 0:          # 侦测球是否超过画布上方
            self.y = step
        if ballPos[2] >= winW:       # 侦测球是否超过画布右方
            self.x = -step           
        if ballPos[3] >= winH:       # 侦测球是否超过画布下方
            self.y = -step
        if self.hitRacket(ballPos):  # 侦测是否撞到球拍
            self.y = -step

class Racket():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0,0,100,15,fill=color)  # 球拍对象
        self.canvas.move(self.id, 270, 400)
        self.x = 0
        self.canvas.bind_all('<KeyPress-Right>',self.moveRight)   # 绑定按住右键 ##########################
        self.canvas.bind_all('<KeyPress-Left>',self.moveLeft)     # 绑定按住左键
    def racketMove(self):
        self.canvas.move(self.id,self.x,0)
        pos = self.canvas.coords(self.id)
        # self.x = 0
        if pos[0] <= 0:
            self.x = 0
        elif pos[2] >= winW:
            self.x = 0
    def moveLeft(self,event):
        print("按下左键")
        self.x = -3
    def moveRight(self,event):
        print("按下右键")
        self.x = 3

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.03    # 设置移动速度

tk = Tk()
tk.title("Bouncing Ball")                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH)  # 建立画布
canvas.pack()
tk.update()   

# 以下两行代码执行顺序决定了两者重合时哪一个对象被遮挡
racket = Racket(canvas,'purple')        # 定义紫色球拍
ball = Ball(canvas,'yellow',winW,winH,racket)  # 定义球对象

while True:
    ball.ballMove()
    racket.racketMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

# tk.mainloop()

ch19_28.py

# ch19_28.py 
from tkinter import * 
from tkinter import messagebox 
from random import * 
import time 
cntL = 1
cntR = 1
class Ball:#class Ball(): # 这样写是一样的
    def __init__(self,canvas,color,winW,winH,racket):
        self.canvas = canvas
        self.racket = racket
        self.id = canvas.create_oval(0, 0, 20, 20, fill=color) # 建立球对象
        self.canvas.move(self.id,winW/2,winH/2)   # 设置球最初位置
        startPos = [-4, -3, -2, -1, 1, 2, 3, 4]   # 球最初x轴位移的随机数
        shuffle(startPos)                         # 打乱排序
        self.x = startPos[0]                      # 球最初水平移动单位
        self.y = -step                            # 垂直移动单位
        self.notTouchBottom = True                       
    def hitRacket(self,ballPos):
        racketPos = self.canvas.coords(self.racket.id)
        if ballPos[2] >= racketPos[0] and ballPos[0] <= racketPos[2]:
            if ballPos[3] >= racketPos[1] and ballPos[3] <= racketPos[3]:
                return True
        return False
    def ballMove(self):
        self.canvas.move(self.id, self.x, self.y)        # step是正值表示往下移动
        ballPos = self.canvas.coords(self.id)
        if ballPos[0] <= 0:          # 侦测球是否超过画布左方
            self.x = step       
        if ballPos[1] <= 0:          # 侦测球是否超过画布上方
            self.y = step
        if ballPos[2] >= winW:       # 侦测球是否超过画布右方
            self.x = -step           
        if ballPos[3] >= winH:       # 侦测球是否超过画布下方
            self.y = -step
        if self.hitRacket(ballPos):  # 侦测是否撞到球拍
            self.y = -step
        if ballPos[3] >= winH:       # 侦测球是否超过画布下方
            self.notTouchBottom = False

class Racket():
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_rectangle(0,0,100,15,fill=color)  # 球拍对象
        self.canvas.move(self.id, 270, 400)
        self.x = 0
        self.canvas.bind_all('<KeyPress-Right>',self.moveRight)   # 绑定按住右键 ##########################
        self.canvas.bind_all('<KeyPress-Left>',self.moveLeft)     # 绑定按住左键
    def racketMove(self):
        self.canvas.move(self.id,self.x,0)
        racketPos = self.canvas.coords(self.id)
        # self.x = 0
        if racketPos[0] <= 0:
            self.x = 0
        elif racketPos[2] >= winW:
            self.x = 0
    def moveLeft(self,event):
        global cntL
        print("按下左键",cntL)
        cntL += 1
        self.x = -3
    def moveRight(self,event):
        global cntR
        print("按下右键",cntR)
        cntR += 1
        self.x = 3

winW = 640      # 定义画布宽度
winH = 480      # 定义画布高度
step = 3        # 定义速度可想成位移步长
speed = 0.01    # 设置移动速度

tk = Tk()
tk.title("    弹球小游戏  ----  " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))                    # 游戏窗口标题
tk.wm_attributes('-topmost',1)               # 确保游戏窗口在屏幕最上层
canvas = Canvas(tk,width=winW, height=winH,bg='black')  # 建立画布
canvas.pack()
tk.update()   

# 以下两行代码执行顺序决定了两者重合时哪一个对象被遮挡
racket = Racket(canvas,'purple')        # 定义紫色球拍
ball = Ball(canvas,'yellow',winW,winH,racket)  # 定义球对象

while ball.notTouchBottom:
    try:
        ball.ballMove()
    except:
        print("单击关闭按钮终止程序执行")
        break
    racket.racketMove()
    tk.update()
    time.sleep(speed)   # 可以控制移动速度

messagebox.showinfo("Game Over","游戏结束!!!")
# tk.mainloop()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值