【完结篇】《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()
### 回答1: TkinterPython语言的一个标准GUI库,可以用来创建各种图形界面应用程序。它是Python内置的库,无需额外安装。Tkinter提供了一系列的组件,如按钮、标签、文本框等,以及各种布局管理器,如Grid布局和Pack布局等,供开发者使用。 对于初学者来说,菜鸟编程PDF对于学习Tkinter非常有帮助。它通过简单明了的语言和大量实例代码,帮助读者快速入门并掌握Tkinter的基础知识和常用功能。 首先,这本PDF会介绍Tkinter的基本概念和使用方法,并通过一些简单的示例代码展示Tkinter的基本功能,帮助读者了解如何创建窗口、添加组件、设置布局等。 其次,该PDF还会详细介绍Tkinter中常用的组件,如按钮、标签、文本框等,并通过示例代码展示了它们的基本用法和常见功能。 此外,菜鸟编程的这本PDF还会介绍Tkinter中的事件处理和布局管理器等高级内容。事件处理可以让用户与程序进行交互,响应用户的操作,而布局管理器可以帮助开发者更方便地设置和调整界面的布局。 总的来说,这本菜鸟编程Tkinter PDF提供了丰富的例子和简单易懂的教程,对于想学习Python GUI编程的初学者来说,是一本非常好的指南。读者可以通过这本PDF快速入门Tkinter,并掌握基本的GUI开发技巧,为以后的项目开发打下良好的基础。 ### 回答2: Python GUI设计是使用Python编程语言开发图形用户界面(GUI)的过程。其中,TkinterPython内置库之一,提供了快速和简单的方法来创建GUI应用程序。 Tkinter的优势之一是它易于学习和使用。大部分用户只需要一些基本的Python知识,就能够开始使用Tkinter创建GUI应用程序。此外,Tkinter提供了丰富的控件(如按钮、文本输入框、列表框等),可以轻松地实现各种功能。 对于初学者来说,使用Tkinter创建GUI应用程序具有很高的可扩展性和灵活性。我们可以通过自定义控件的外观和行为,使应用程序更符合我们的需求。此外,Tkinter提供了丰富的布局管理器,可以帮助我们轻松地调整和排列控件。 编写图形用户界面时,我们通常需要处理用户的输入和操作。Tkinter提供了丰富的事件处理机制,可以捕获和响应用户的各种操作。我们可以编写相应的事件处理函数,根据用户的操作来更新界面和执行相应的逻辑。 最后,Tkinter提供了对像素级别的控制,可以使用绑定到特定控件的回调函数来实现对控件进行自定义的操作。这使得我们能够更加深入地控制应用程序的外观和行为。 总的来说,Python GUI设计使用Tkinter可以帮助我们快速、简单地创建各种GUI应用程序。即使对于刚开始学习的菜鸟编程者来说,也可以通过掌握基本的Tkinter知识,轻松地创建自己想要的GUI应用程序。 ### 回答3: 《Python GUI设计 Tkinter菜鸟编程 PDF》是一本以Python编程语言为基础,教授如何使用Tkinter库进行图形用户界面(GUI)设计的电子书。TkinterPython中一个内建的GUI库,它提供了一系列的组件和工具,使开发者能够轻松创建交互式的桌面应用程序。 这本PDF适合初学者或者菜鸟级别的编程者,它详细介绍了Tkinter库的基础知识和使用方法。读者可以通过学习这本书,了解如何使用Tkinter创建窗口、标签、按钮、文本框等常见的GUI组件,并将它们进行布局和设计,从而构建一个完整的用户界面。 这本书还介绍了一些高级的Tkinter技巧和功能,如使用事件处理机制实现交互性、添加图像和多媒体文件、使用缩放和滚动条控制部件等。读者将学会如何将这些技巧应用于自己的项目中,以便创建出更具吸引力和实用性的应用程序。 总的来说,这本《Python GUI设计 Tkinter菜鸟编程 PDF》是一本适合初学者的指南,它帮助读者快速入门GUI设计,并教授如何使用Tkinter库创建各种交互性强、功能丰富的应用程序。无论是想要开发一个小型工具还是一个全功能的应用程序,都可以从这本书中获取到所需的知识和技能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值