GUI(Graphics User Interface)
常用的GUI库
-
Tkinter
-
wxPython
-
PyQT
第一个GUI
from tkinter import *
from tkinter import messagebox
root = Tk()
btn = Button(root)
btn['text'] = '点我就送花'
btn.pack()
def flowers(e):
messagebox.showinfo('Message','送你一朵玫瑰花')
print('送你99朵玫瑰花')
btn.bind('<Button-1>',flowers)
#调用组件的mainloop方法进入事件循环
root.mainloop()
tkinter主窗口
主窗口位置和大小
通过geometry('wxh±x±y')进行设置。w为宽度,h为高度。+x表示距离屏幕左边的距离;-x表示距离屏幕右边的距离;+y表示距离频幕上边的距离;-y表示距屏幕下边的距离。
root.geometry('300x250+500+240')
GUI编程整体描述
图形用户界面是由一个个组件组成,就像小孩“搭积木”一样最终组成了整个界面,有的组件还能再里面放置其他组件,称为“容器”
常见组件汇总列表
GUI应用程序类的经典写法
通过类Application组织整个GUI程序,类Application继承了Frame及通过继承拥有了父类的特性,通过构造函数__ init __()初始化窗口中的对象,通过createWidgets()方法创建窗口中的对象
-
Frame框架是一个tkinter组件,表示一个矩形的区域,frame一般作为容器使用,可以放置其他组件,从而实现复杂的布局
'''使用面向对象分方式'''
from tkinter import *
from tkinter import messagebox
class Application(Frame):
'''经典的GUI程序类的写法'''
def __init__(self,master=None):
super().__init__(master)
self.master=master
self.pack()
self.createWidget()
def createWidget(self):
'''创建组件'''
self.btn = Button(self)
self.btn['text'] = '双击加关注'
self.btn.pack()
self.btn['command'] = self.flowers
'''创建退出按钮'''
self.btnQuit = Button(self,text='退出',command=root.destroy)
self.btnQuit.pack()
def flowers(self):
messagebox.showinfo('欢迎关注')
if __name__ == '__main__':
root = Tk()
root.geometry('300x250+500+240')
root.title('hello world')
app = Application(master=root)
root.mainloop()
简单组件
Lebel标签
主要用于显示文本信息,也可以显示图像,常见属性
-
width,height:用于指定区域大小,如果显示是文本,则以单个英文字符大小为单位(一个汉字占2个字符位置,高度和英文字符一样);如果显示是图像,则以像素为单位,默认值是根据具体显示的内容动态调整
-
font:指定字体和字体大小,font=(font_name,size)
-
image:显示在label上的图像,目前只支持gif格式
-
fg和bg:前景色和背景色
-
justify:针对多行文字的对齐,可选填“left”,“center”,“riaht”
'''使用面向对象分方式'''
from tkinter import *
from tkinter import messagebox
class Application(Frame):
'''经典的GUI程序类的写法'''
def __init__(self,master=None):
super().__init__(master)
self.master=master
self.pack()
self.createWidget()
def createWidget(self):
'''创建组件'''
self.Label = Label(self)
self.Label = Label(self,text="百战程序员",width=10,height=2,bg='black',fg='white')
self.Label.pack()
self.Label1 = Label(self)
self.Label1 = Label(self, text="百战程序员", width=10, height=2, bg='blue', fg='white',font=('黑体',15))
self.Label1.pack()
#显示图像
global photo #把photo声明成全局变量,如果是局部变量,本方法执行完毕后,图像对象销毁,窗口显示不出来
photo = PhotoImage(file="image/R-C.gif")
self.Label3 = Label(self,image=photo)
self.Label3.pack()
'''显示多行的文本'''
self.Label4 = Label(self,text='你好zpx\n我想你啦\n',borderwidth=1,relief='solid',justify='right')
self.Label4.pack()
if __name__ == '__main__':
root = Tk()
root.geometry('1000x1000+500+240')
root.title('hello world')
app = Application(master=root)
root.mainloop()
Options选项详解
可以通过三种方式设置options选项
-
创建对象时,使用命令参数
fred = Button(self,fg='red',bg='blue')
-
创建对象后,使用字典索引方式
fred['fg'] = 'red' fred['bg'] = 'blue'
-
创建对象后,使用config()方法
fred.config(fg='red',bg='blue')
知识点回顾:
常用选项