本文最后更新于:3 years ago

gui界面设计和pygame

tkinter 库

Label 和Button标签

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

var = tk.StringVar() #tk字符串变量
l = tk.Label(window,textvariable=var,bg='green',font=('Arial',12),width=15,height=2) #Label的配置
l.pack() #放置Label标签

on_hit = False
#设置点击事件
def hitMe():
    global on_hit
    if on_hit == False:
        on_hit = True
        var.set("you hit me")
    else:
        on_hit = False
        var.set('')

bt = tk.Button(window,text='hit me',width=15,height=2,command=hitMe) #Button标签,command是事件方法
bt.pack()
window.mainloop() #不断刷新界面

Entry 和Text 输入,文本框

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

e = tk.Entry(window,show=None) #show可以设置字符样式 例如*
e.pack()
#设置点击事件
def insertPoint():
    var = e.get()
    t.insert('insert',var) #设置insert方法
def insertEnd():
    var = e.get()
    t.insert('end',var) #插入到最后面
def insertIndex():
    var = e.get()
    t.insert(1.1,var)  #插入到第一行第二列
bt1 = tk.Button(window,text='insert point',width=15,height=2,command=insertPoint) #Button标签,command是事件方法
bt1.pack()
bt2 = tk.Button(window,text='insert end' ,width=15,height=2,command=insertEnd)
bt2.pack()
bt3 = tk.Button(window,text='insert index',width=15,height=2,command=insertIndex)
bt3.pack()

t = tk.Text(window,height=2) #Text标签
t.pack()
window.mainloop() #不断刷新界面

Listbox 列表组件

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

var1 = tk.StringVar()
l = tk.Label(window,textvariable=var1,bg='green',width=4)
l.pack()

#设置点击事件
def insertPoint():
    value = lstBox.get(lstBox.curselection()) #获取光标选定的值
    var1.set(value)

bt1 = tk.Button(window,text='print selection',width=15,height=2,command=insertPoint) #Button标签,command是事件方法
bt1.pack()

var2 = tk.StringVar()
var2.set((11,22,33,44,55))
lstBox = tk.Listbox(window,listvariable=var2) #listBox标签,用listvariable定义list
lstBox.pack()
#插入listBox第二种方法
list_items = [1,2,3,4,5]
for item in list_items:
    lstBox.insert('end',item)
#插入listBox第三种方法
lstBox.insert(1,'first')
lstBox.insert(2,'second')
# lstBox.delete(1)

window.mainloop() #不断刷新界面

Radiobutton 选择按钮

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

var = tk.StringVar()
l = tk.Label(window,text='empty',bg='green',width=20)
l.pack()

def printSelection():
    l.config(text='you have selected ' + var.get())
r1 = tk.Radiobutton(window,text='Option A',variable=var,value='A',command=printSelection) #Radiobutton标签,将value赋值给variable,command是点击按钮方法
r1.pack()
r2 = tk.Radiobutton(window,text='Option B',variable=var,value='B',command=printSelection) #Radiobutton标签,将value赋值给variable
r2.pack()

window.mainloop() #不断刷新界面

Scale 尺度

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

var = tk.StringVar()
l = tk.Label(window,text='empty',bg='green',width=20)
l.pack()

def printSelection(v):
    '''
    :param v: value的值
    :return: 
    '''
    l.config(text='you have selected ' + v)

s = tk.Scale(window,label='try me',from_=5,to=11,orient=tk.HORIZONTAL,length=300,showvalue=1,tickinterval=3,resolution=0.01,command=printSelection) #Scale标签,从5到10,横项的,长度300,是否显示0,步长3,精度0.01
s.pack()
window.mainloop() #不断刷新界面

Checkbutton 勾选项

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

var = tk.StringVar()
l = tk.Label(window,text='empty',bg='green',width=20)
l.pack()

def printSelection():
    print(var1.get(),var2.get())
    if var1.get() == 1 and var2.get() == 0:
        l.config(text='I love only Python')
    elif var1.get() == 0 and var2.get() == 1:
        l.config(text='I love only C++')
    elif var1.get() == 0 and var2.get() == 0:
        l.config(text='I do not love either')
    else:
        l.config(text='I love both')

var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window,text='Python',variable=var1,onvalue=1,offvalue=0,command=printSelection) #Checkbutton标签,选中赋值var1为1,不选中为0
c2 = tk.Checkbutton(window,text='C++',variable=var2,onvalue=1,offvalue=0,command=printSelection) #Checkbutton标签,选中赋值var1为1,不选中为0
c1.pack()
c2.pack()
window.mainloop() #不断刷新界面

Canvas 画布

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

canvas = tk.Canvas(window,bg='blue',height=150,width=300,)
image_file = tk.PhotoImage(file='tk.gif') #获取图片,只能是gif
image = canvas.create_image(10,10,anchor='nw',image=image_file) #创建图片,锚定的点为nw方向
x0,y0,x1,y1 = 50,50,80,80
line = canvas.create_line(x0,y0,x1,y1) #画线从(x0,y0)画到(x1,y1)
oval = canvas.create_oval(x0,y0,x1,y1,fill='red') #画圆
arc = canvas.create_arc(x0+30,y0+30,x1+30,y1+30,start=0,extent=180) #扇形
rect = canvas.create_rectangle(200,20,200+30,20+30) #矩形
canvas.pack()

def moveIt():
    canvas.move(rect,0,2) #移动平移0,下移2
b = tk.Button(window,text='move',command=moveIt).pack()

window.mainloop() #不断刷新界面
# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

l = tk.Label(window,text='',bg='green',width=20)
l.pack()

count = 0
def doJob():
    global count
    l.config(text='do' + str(count))
    count += 1
menubar = tk.Menu(window) #Menu标签

file_menu = tk.Menu(menubar,tearoff=0) #tearoff能否被分开
menubar.add_cascade(label='File',menu=file_menu) #将file_menu放在Menu上
file_menu.add_command(label='New',command=doJob) #增加菜单的功能
file_menu.add_command(label='Open',command=doJob)
file_menu.add_command(label='Save',command=doJob)
file_menu.add_separator() #加一条分离线
file_menu.add_command(label='Exit',command=window.quit)

edit_menu = tk.Menu(menubar,tearoff=0) #tearoff能否被分开
menubar.add_cascade(label='Edit',menu=edit_menu) #将file_menu放在Menu上
edit_menu.add_command(label='Cut',command=doJob) #增加菜单的功能
edit_menu.add_command(label='Copy',command=doJob)
edit_menu.add_command(label='Paste',command=doJob)

sub_menu = tk.Menu(menubar,tearoff=0) #file_menu中的分支
file_menu.add_cascade(label='Import',menu=sub_menu,underline=0)
sub_menu.add_command(label='Submenu1',command=doJob)

window.config(menu=menubar)
window.mainloop() #不断刷新界面

Frame 框架布局

# coding=gbk
import tkinter as tk

#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

tk.Label(window,text='on the window').pack()

frm = tk.Frame(window) #创建一个frame
frm.pack()
frm_left = tk.Frame(frm) #将frm_left放在frm中
frm_right = tk.Frame(frm)
frm_left.pack(side='left')   #放在左边
frm_right.pack(side='right')

tk.Label(frm_left,text='on the frm_l1').pack()
tk.Label(frm_left,text='on the frm_l2').pack()
tk.Label(frm_right,text='on the frm_r1').pack()
window.mainloop() #不断刷新界面

Messagebox 弹窗

# coding=gbk
import tkinter as tk
from tkinter import messagebox
#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素
def hitMe():
    # tk.messagebox.showinfo(title='hi',message='哈哈哈') #弹窗
    # tk.messagebox.showwarning(title='hi',message='no') #警告
    # tk.messagebox.showerror(title='hi',message='哈哈哈') #程序不能运行
    # tk.messagebox.askquestion(title='hi',message='哈哈哈') #return yes or no
    # r = tk.messagebox.askyesno(title='hi',message='哈哈哈') #return True or False
    # tk.messagebox.askretrycancel(title='hi',message='哈哈哈') #return True or False
    tk.messagebox.askyesnocancel(title='hi',message='哈哈哈') #return True or False
tk.Button(window,text='hit me',command=hitMe).pack()
window.mainloop() #不断刷新界面

pack grid place 放置位置

# coding=gbk
import tkinter as tk
from tkinter import messagebox
#界面配置
window = tk.Tk() #设置一个window界面
window.title('my window') #设置界面标题
window.geometry('300x300') #设置界面大小300x300像素

#pack用法
# tk.Label(window,bg='green',text=1).pack(side='top')
# tk.Label(window,bg='green',text=1).pack(side='bottom')
# tk.Label(window,bg='green',text=1).pack(side='left')
# tk.Label(window,bg='green',text=1).pack(side='right')

#grid用法
# for i in range(4):
#     for j in range(3):
#         tk.Label(window,bg='green',text=1).grid(row=i,column=j,padx=10,pady=10)#间隔

#place用法
tk.Label(window,bg='green',text=1).place(x=10,y=100,anchor='nw')
window.mainloop() #不断刷新界面

登录实例

pygame 库

相关对象

#屏幕尺寸和模式
pygame.display.set_mode(size) #设置窗口大小
	#一个参数设置大小
    #另一个参数设置屏幕模式
    	pygame.RESIZABLE #可调节
        pygame.FULLSCREEN #全屏
        pygame.NOFRAME #无边框
pygame.display.Info() #生成屏幕相关信息,return 分辨率xXy
	#对象有
    current_w #横
    current_h #纵
#窗口图标和标题
pygame.display.set_icon() #设置图标信息
pygame.display.set_caption() #设置窗口标题 
pygame.display.get_caption() #获得标题和小标题(title,icontitle)
#窗口感知和刷新
pygame.display.get_active() #当窗口在系统中显示时返回True or False
pygame.display.filp() #重新绘制整个屏幕对应的窗口
pygame.display.update() #刷新屏幕

#事件 event.type
pygame.KEYDOWN #键盘事件 返回event.key,event.unicode编码,event.mod修饰符
	pygame.k_UP
    pygame.k_DOWN
    pygame.k_LEFT
    pygame.k_RIGHT
pygame.QUIT #退出事件 
pygame.VIDEORESIZE #窗口大小更改事件 返回event.size
	pygame.size[0] #宽度
    pygame.size[1] #高度
pygame.image.load('ball.gif') #加载图片
get_rect() #使得图片对象有一个矩形边
fclock = pygame.time.Clock() #用于操作时间
fclock.tick(fps) #控制帧的刷新速度每秒进行fps次帧
screen.fill(BLACK)  #填充黑色
screen.blit(ball,ballrect) #将ball图像绘制到ballrect上
pygame.KEYDOWN #键盘敲击事件

#处理事件
pygame.event.get()
pygame.event.poll()
pygame.event.clear()
#操作事件队列
pygame.event.set_blocked(type or typelist) #控制事件不允许保存到事件队列中
pygame.event.get_blocked(type) #判断事件是否被禁止,返回True or False
pygame.event.set_allowed(type or typelist) #控制事件允许保存到事件队列中
#生成事件
pygame.event.post(Event) #产生一个事件放入事件队列,一般用于用户自定义事件(pygame.USEREVENT)
pygame.event.Event(type,dict) #创建给定类型的事件

#鼠标事件
pygame.event.MOUSEMOTION #鼠标移动事件
	event.pos #鼠标当前坐标(x,y),相对于窗口左上角
    event.rel #鼠标相对运动距离(x,y),相当于上次事件
    event.buttons #鼠标移动的三个键状态对应位置值为1反之为0
pygame.event.MOUSEBUTTONUP #鼠标释放事件
	event.pos #鼠标当前坐标(x,y),相对于窗口左上角
    event.button #鼠标的键分别对应0/1/2
pygame.event.MOUSEBUTTONDOWN #鼠标键按下事件
	event.pos #鼠标当前坐标(x,y),相对于窗口左上角
    event.button #鼠标的键左键为1,右键为3

#颜色
pygame.Color(rgba or color) #a可选 默认255 不透明为0
	.r #红色通道 0-255
    .g #绿色通道 0-255
	.b #蓝色通道 0-255
    
#图形绘制机制
pygame.Rect() #返回(left,top) width height
	.copy()
    .move() #移动,传入速度
    .inflate()
    .clamp()
    .clip()
    .union()
    .unionall()
    .fit()
    .normalize()
    #详情可参考http://www.pygame.org/docs/ref/rect.html
pygame.draw 
	.rect() #矩形
    	#参数
        Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
        Rect #矩形绘制的区域
        width #绘制边缘的宽度,默认为0,即填充图形
    .line() #直线
    	Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
        (start_pos,end_pos) #直线起始坐标
        width #直线的宽度,默认为1
    .polygon() #多边形
    	Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
        pointlist #多变形顶点坐标列表
        width #绘制边缘的宽度,默认为0,即填充图形
    .circle() #圆形
    	Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
    	pos #圆心坐标
        radius #半径
        width
    .ellipse() #椭圆形
    	Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
    	Rect #矩形绘制的区域
        width
    .arc() #椭圆弧形
    .lines() #连续多线
    	Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
        closed #如果为True,起止节点自动增加封闭直线
        postlist #直线起始坐标列表
        width #直线的宽度,默认为1
    .aaline() #无锯齿线
    .aalines() #连续无锯齿线
    	Surface #矩形绘制的屏幕
        Color #矩形绘制的颜色
        closed #如果为True,起止节点自动增加封闭直线
        postlist #直线起始坐标列表
        blend = 1 #不为0时,线条所在的背景颜色进行混合
#文字绘制机制
pygame.freetype #需要额外impot
pygame.freetype.Font(字体路径,大小) #生成字体对象
	.render_to() #返回Rect对象
    	#参数
        surf #绘制字体的屏幕
        dest #具体位置(x,y)
        text #绘制的文字内容
        fgcolor #文字颜色
        bgcolor #背景颜色
        rotation #逆时针旋转角度
        size #字体大小
    .render() #绘制具体文字 返回Rect和Surface对象
    	#参数
        text #文字内容
        fgcolor,bgcolor
        rotation
        size

pygame最小开发框架

# coding=gbk
import pygame,sys

pygame.init() #初始化游戏设置
screen = pygame.display.set_mode((600,400)) #设置屏幕大小
pygame.display.set_caption('游戏开发之旅') #设置标题

#实现事件无线循环,直到游戏退出
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    pygame.display.update()

小球碰壁

# coding=gbk
import pygame,sys

#游戏初始化
pygame.init() #初始化游戏设置
size = width,height = 600,400
speed = [1,1]
print(speed[0])
BLACK = 0,0,0
still = False
bgcolor = pygame.Color('black')
screen = pygame.display.set_mode(size,pygame.RESIZABLE) #设置屏幕大小
pygame.display.set_caption('小球碰壁') #设置标题
ball = pygame.image.load('ball.gif')
icon = pygame.image.load('ball.gif')
pygame.display.set_icon(icon)
ballrect = ball.get_rect()
fps =300
fclock = pygame.time.Clock() #用于操作时间
def RGBChannel(a):
    return 0 if a<0 else (255 if a>255 else int(a))
#实现事件无线循环,直到游戏退出
while True:
    #事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1) * int(speed[0]/abs(speed[0]))
            elif event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1
            elif event.key == pygame.K_UP:
                speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1
            elif event.key == pygame.K_DOWN:
                speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1) * int(speed[1]/abs(speed[1]))
            elif event.key == pygame.K_ESCAPE:
                sys.exit()
        elif event.type == pygame.VIDEORESIZE:
            size = width,height = event.size[0],event.size[1]
            screen = pygame.display.set_mode(size,pygame.RESIZABLE)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                still = True
        elif event.type == pygame.MOUSEBUTTONUP:
            still = False
            if event.button == 1:
                ballrect = ballrect.move(event.pos[0] - ballrect.left,event.pos[1] - ballrect.top)
        elif event.type == pygame.MOUSEMOTION:
            ballrect = ballrect.move(event.pos[0] - ballrect.left,event.pos[1] - ballrect.top)
    if pygame.display.get_active() and not still:
        ballrect = ballrect.move(speed[0],speed[1]) #移动
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
        if ballrect.right > width and ballrect.right + speed[0] > ballrect.right:
            speed[0] = -speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
        if ballrect.bottom > height and ballrect.bottom + speed[1] > ballrect.bottom:
            speed[1] = -speed[1]
    bgcolor.r = RGBChannel(ballrect.left*255/width)
    bgcolor.g = RGBChannel(ballrect.top*255/height)
    bgcolor.b = RGBChannel(min(speed[0],speed[1])*255/max(speed[0],speed[1],1))
    screen.fill(bgcolor)  #填充黑色
    screen.blit(ball,ballrect) #将ball图像绘制到ballrect上
    pygame.display.update()
    fclock.tick(fps) #控制帧的刷新速度每秒进行fps次帧

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

Docker介绍和演示 Previous
Django rest framework Next