小试Python的GUI

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33189961/article/details/97961902

花了两天的时间理了一下Python的基础语法,发现和C++、JAVA、JS之流的语言基础语法大同小异,控制台程序两天就枯燥了,于是手痒又瞄上了GUI,有画面才能出奇迹 ,略微看了下和JAVA的风格感觉差不多嘛,其实我还是同样的观点,任何语言搞清楚基础语法就可以看API文档做东西了,哪个模块都是这样,先从简单的搞清楚语言的特性,然后看文档!!!:)


目录

初始化一个界面

添加监听事件(按钮为例)

写一个小游戏(基于pygame)


初始化一个界面

import tkinter as tk

app = tk.Tk()   #创建一个窗口实例
app.title("tkinter_test")   #设置标题
theLable = tk.Label(app,text = "这是一个标签")    #创建一个标签实例
theLable.pack()   #py的布局管理方式之一,自动调整位置
app.mainloop()    #入到事件(消息)循环,简单来说就是没有这一句界面就不显示

大概是这个样子

在了解了大概用法了以后,以对象的方式再重构一下:

import tkinter as tk

class APP:
    def __init__(self,master):
        frame = tk.Frame(master)
        frame.pack()
        self.button = tk.Button(frame, text="这是一个按钮", fg="red" )
        self.button.pack()

root = tk.Tk()
app = APP(root)
root.mainloop()

如图:

 

添加监听事件(按钮为例)

在APP类里面添加say_hello()方法以及在button里面添加一个command属性指定响应监听的方法,这与JS的监听有点类似:

import tkinter as tk

class APP:
    def __init__(self,master):
        frame = tk.Frame(master)
        frame.pack()
        self.button = tk.Button(frame, text="这是一个按钮", fg="red", command=self.say_hello)
        self.button.pack()

    def say_hello(self):
        print("hello pygui")

root = tk.Tk()
app = APP(root)
root.mainloop()

写一个小游戏(基于pygame)

安装pygame扩展包

不会安装扩展包直接百度啥的吧,参考https://blog.csdn.net/a8458202458320/article/details/84101993

大概是这个亚子:

就不一一解释了,代码里有注释:

import pygame
import sys

#初始化pygame
pygame.init()
size = width,height = 800,500
speed = [-2,1]   #每次移动的步长
bg=(255,255,255)

screen = pygame.display.set_mode(size)  #创建窗口
pygame.display.set_caption("疯狂的滑稽")
turtle = pygame.image.load("images/huaji.png")  #加载图
position = turtle.get_rect()

#获得游戏窗口监听,当点击X时推出游戏
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    position = position.move(speed)  #图片移动

    if position.left < 0 or position.right > width:
        turtle = pygame.transform.flip(turtle,True,False) #图片水平翻转
        speed[0] = -speed[0]    #反向移动

    if position.top < 0 or position.bottom > height:
        speed[1] = -speed[1]

    screen.fill(bg)  #填充背景
    screen.blit(turtle,position)  #更新图像
    pygame.display.flip()   #更新窗口
    pygame.time.delay(5)    #延迟一下,不然图像会疯了一样的跑

因为是学py做机器学习的,GUI就不深究了,和JAVA差不多,也是那些组件的使用而已,千篇一律,看看api就差不多了(手动原谅).......

猜你喜欢

转载自blog.csdn.net/qq_33189961/article/details/97961902
今日推荐