GUI模块学习一

实例一 点击送花

from tkinter import *  # 窗口模块
from tkinter import messagebox  # 弹窗模块

# 1 创建根窗口对象root
root = Tk()

# 2 创建主键 把窗口root传进去 创建Button对象,把button放进窗口里面
btn01 = Button(root)
# 给主键上面添加内容
btn01['text'] = '点我就送花'
# 调用布局管理器,把主键合理地放到窗口里面
btn01.pack()  # pack()压缩紧缩


# 3 创建事件
def songhua(e):  # e就是事件对象
    messagebox.showinfo('Message', '送你一朵玫瑰花!')  # 弹窗 'M'
    print('送你一朵玫瑰花!')


# 4 事件绑定
btn01.bind('<Button-1>', songhua)  # 单击左键,送花

# 这句话必须要有
root.mainloop()  # 调用组件的mainloop()方法,进入事件循环

实例二 经典的gui写法

# 用面向对象的方式写一个经典的GUI程序

from tkinter import *
from tkinter import messagebox


class Application(Frame):
    """一个经典的GUI程序写法"""

    def __init__(self, master=None):  # root通过master传进去后,self就相当于root
        super().__init__(master)  # super()代表的是父类定义,而不是父类对象
        self.master = master  # 这个地方就是绑定事件
        self.pack()  # self就是组件 通过布局管理器显示窗口
        self.createWidget()  # 调用下一步的操作

    def createWidget(self):
        """创建组件"""
        self.btn01 = Button(self)  # 创建组件
        self.btn01['text'] = '点我送花'  # 定义组件文本
        self.btn01.pack()  # 通过布局管理器放到窗口
        self.btn01['command'] = self.songhua  # 创建一个事件

        # 创建一个退出按钮
        self.btnQuit = Button(self, text='退出', command=root.destroy)
        self.btnQuit.pack()

    def songhua(self):
        messagebox.showinfo('送花', '送你99朵玫瑰花!')

if __name__ == '__main__':
    root = Tk()
    root.geometry('400x200+200+200')
    root.title('一个经典的GUI程序写法')
    app = Application(master=root)
    root.mainloop()

实例三 组件属性设置方法

from tkinter import*


root = Tk()
root.title('设置选项')
root.geometry('500x300+200+200')

"""设置options选项的三种方法"""
# 方式1 创建对象时,使用关键字参数 ------常用
btn01 = Button(root, text='一个按钮', fg='red', bg='blue')
btn01.pack()
# 也可以在创建时传递一个字典
btn04 = Button(root, dict(text='传递字典的按钮', fg='black', bg='blue'))
btn04.pack()
# 方式2 创建对象后,使用字典索引
btn02 = Button(root)
btn02['text'] = '第二个按钮'
btn02['fg'] = 'pink'
btn02['bg'] = 'white'
btn02.pack()
# 方式3 创建对象后,使用config方法
btn03 = Button(root)
btn03.config(text='第三个按钮', fg='red', bg='yellow')  # 里面是关键字参数
btn03.pack()

root.mainloop()

实例四 label对象的基本用法

相当于一个显示对象(文本,图片)的窗口

"""测试label对象的基本用法"""

from tkinter import *


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""

        # 显示文本 不可更改
        self.label01 = Label(self, text='百战程序员', width=10, height=2, bg='black', fg='white')  # 文本 宽 高 背景 前景
        self.label01.pack()

        self.label02 = Label(self, text='高淇老师', width=10, height=2, bg='blue', fg='red', font=('黑体', 30))  # 文本 宽 高 背景 前景 字体 尺寸
        self.label02.pack()

        # 显示图片 只能显示gif位图
        global photo  # 把图像声明成全局变量 如果是局部变量 本方法执行完毕后 图像对象就会销毁 窗口显示不出图像
        photo = PhotoImage(file='images/fengjing1.gif')  # 加载图片 作为程序对象保存起来
        self.label03 = Label(self, image=photo)
        self.label03.pack()

        # 设置边界 边界效果 对齐方式
        self.label04 = Label(self, text='北京尚学堂\n百战程序员\n老高很帅,就是做饭不行.', borderwidth=1, relief='solid', justify='center')
        self.label04.pack()


if __name__ == '__main__':
    root = Tk()
    root.title('测试label用法')
    root.geometry('800x600+200+200')
    app = Application(master=root)
    root.mainloop()

实例五 Button按钮

点击会触发事件的组件

import tkinter.messagebox
from tkinter import *


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""
        # 文本
        self.btn01 = Button(self, text='登录', command=self.login)
        self.btn01.pack()
        # 图片
        global photo
        photo = PhotoImage(file='images/2.gif')
        self.btn02 = Button(self, image=photo, command=self.login)
        self.btn02.pack()
        # 设置灰色按键
        self.btn02.config(state='disabled')


    def login(self):
        tkinter.messagebox.showinfo('message', '登陆成功')


if __name__ == '__main__':
    root = Tk()
    root.title('button的简单应用')
    root.geometry('500x300+200+200')
    app = Application(master=root)
    root.mainloop()

实例六 entry组件

内外交互的组件

from tkinter import *
from tkinter import messagebox


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建登陆界面组件组件"""

        self.lobel01 = Label(self, text='用户名')
        self.lobel01.pack()
        # entry
        # stringvar变量绑定到指定组件。stringvar变量的值发生变化,组件内容也变化。组件内容变化stringvar变量的值也发生变化.
        v1 = StringVar()
        self.entry01 = Entry(self, textvariable=v1)
        self.entry01.pack()
        v1.set('admin')

        """创建密码框"""
        self.lobel02 = Label(self, text='密码')
        self.lobel02.pack()
        v2 = StringVar()
        self.entry02 = Entry(self, textvariable=v2, show="*")  # 隐藏密码
        self.entry02.pack()

        self.btn01 = Button(self, text='登录', command=self.login)
        self.btn01.pack()

    def login(self):
        username = self.entry01.get()
        pwd = self.entry02.get()
        print('去数据库比对数据')
        print('用户名:' + username)
        print('密码:' + pwd)
        lst = ['admin', 'jack', 'alx', 'jhn']
        dct = {'admin': '123456', 'jack': 'abcdef', 'alx': 'abc123', 'jhn': 'jhn123'}
        if username in lst and pwd == dct[username]:
            messagebox.showinfo('尚学堂学习系统', '登陆成功!欢迎开始学习!')
        else:
            messagebox.showinfo('尚学堂学习系统', '登录失败,用户名或密码错误!')


if __name__ == '__main__':
    root = Tk()
    root.title('测试entry')
    root.geometry('500x300+100+200')
    app = Application(master=root)
    root.mainloop()

实例七 text组件

from tkinter import *
import webbrowser


class Application(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""
        # 创建text
        self.w1 = Text(self, width=40, height=10, bg='gray')  # 1个字母宽度为1,一个汉字宽度为2,1行就是一个行高
        self.w1.pack()
        # 在text内插入内容 可在text文本框任意位置插入
        self.w1.insert(1.0, '0123456789\nabcdegfgh\n') # text文本框横向123456..纵向0123456...,其中1.0表示第一行第0列
        self.w1.insert(2.3, '白日依山尽,黄河入海流,欲穷千里目,更上一层楼.\n')
        # 创建Button组件
        Button(self, text='重复插入文本', command=self.insertText).pack(side='left')
        Button(self, text='返回文本', command=self.returnText).pack(side='left')
        Button(self, text='添加图片', command=self.addImage).pack(side='left')
        Button(self, text='添加组件', command=self.addWidget).pack(side='left')
        Button(self, text='通过Tag精确控制文本', command=self.textTag).pack(side='left')

    def insertText(self):
        # INSERT索引表示在光标处插入
        self.w1.insert(INSERT, '在光标处插入!')
        # END索引表示在最后插入
        self.w1.insert(END, '在最后插入!')
        # 在第一行第8列位置插入
        self.w1.insert(1.8, 'ga0qi')

    def returnText(self):
        # indexes索引是用于指向text组件中文本的位置,text组件索引也是对应字符之间的实际位置.
        # 核心:行号以1开始,列号以0开始
        print(self.w1.get(1.3, 1.8))  # 打印文本第一行第3列到第一行第8列的内容,前闭后开
        print('打印全部内容:\n' + self.w1.get(1.0, END))  # 从头到尾

    def addImage(self):
        # photo 可以定义成全局的global 也可以定义成对象的属性self.photo
        self.photo = PhotoImage(file='images/3.gif')
        self.w1.image_create(END, image=self.photo)

    def addWidget(self):
        b1 = Button(self.w1, text='爱尚学堂')
        # 在text中创建组件的命令
        self.w1.window_create(INSERT, window=b1)

    def textTag(self):
        # 全部删除
        self.w1.delete(1.0, END)
        # 在光标处插入新内容
        self.w1.insert(INSERT, 'good good study, up up day !\n北京尚学堂\n百战程序员\n百度,搜一下就能搜到\n')
        # 给选定文本做标记
        self.w1.tag_add('good', 1.0, 1.9)
        # 给标记(tag)添加属性
        self.w1.tag_config('good', background='yellow', foreground='red')

        self.w1.tag_add('baidu', 4.0, 4.2)
        self.w1.tag_config('baidu', background='pink', foreground='black')
        # 给标记绑定事件
        self.w1.tag_bind('baidu', '<Button-1>', self.webShow)

    def webShow(self, event):
        webbrowser.open('https://www.baidu.com')



if __name__ == '__main__':
    root = Tk()
    root.title('测试Text')
    root.geometry('800x600+200+100')
    app = Application(master=root)
    root.mainloop()

实例八 radiobutton与checkbutton组件

radiobutton:单选
checkbutton:复选

from tkinter import *
from tkinter import messagebox


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""
        self.v = StringVar()
        self.v.set('F')
        # 注意 variable与textvariable的区别,前者的值等于value,不会改变value的值,后者的值也等于text,value的值,且会改变它们的值
        # Radiobutton的r1,r2两个组件的variable指向的是同一个变量
        self.r1 = Radiobutton(self, text='男性', value='M', variable=self.v)
        self.r2 = Radiobutton(self, text='女性', value='F', variable=self.v)
        self.r1.pack(side='left'); self.r2.pack(side='left')

        Button(self, text='确定', command=self.confirm).pack(side='left')

    def confirm(self):
        messagebox.showinfo('message', '你选择的性别是' + self.v.get())


class Application01(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""
        self.codeHobby = IntVar()
        self.videoHobby = IntVar()
        print(self.codeHobby.get())  # 默认值为0
        # 注意 variable与textvariable的区别,前者的值等于value,不会改变value的值,后者的值也等于text,value的值,且会改变它们的值
        # Checkbutton的c1,c2两个组件的variable指向的是不同的变量
        self.c1 = Checkbutton(self, text='敲代码', variable=self.codeHobby, onvalue=1, offvalue=0)
        self.c2 = Checkbutton(self, text='看电影', variable=self.videoHobby, onvalue=1, offvalue=0)
        self.c1.pack(side='left'); self.c2.pack(side='left')

        Button(self, text='确定', command=self.confirm).pack(side='left')

    def confirm(self):
        if self.codeHobby.get() == 1:
            messagebox.showinfo('message', '活捉野生程序猿一只!')
        # 默认值为0,如果不选的话就执行下面这个操作
        # elif self.codeHobby.get() == 0:
        #     messagebox.showinfo('message', '不喜欢敲代码,那喜欢玩游戏了?')
        if self.videoHobby.get() == 1:
            messagebox.showinfo('message', '大家都爱看!')
        # elif self.videoHobby.get() == 0:
        #     messagebox.showinfo('message', '你喜欢什么游戏?')


if __name__ == '__main__':
    root = Tk()
    root.title('测试')
    root.geometry('400x200+200+100')
    app1 = Application01(master=root)
    app2 = Application(master=root)
    root.mainloop()

实例九 canvas画布组件

# 画布
from tkinter import *
import random


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""
        # 画布
        self.canvas = Canvas(self, width=400, height=250, bg='green')
        self.canvas.pack()

        # 画直线
        self.canvas.create_line(10, 10, 20, 30, 40, 50)

        # 画矩形 对角线两点坐标
        self.canvas.create_rectangle(30, 30, 100, 200)

        # 画椭圆 矩形对角线两点坐标 矩形的内切椭圆
        self.canvas.create_oval(30, 30, 100, 200)

        # 图片
        global photo
        photo = PhotoImage(file='images/3.gif')
        self.canvas.create_image(300, 200, image=photo)

        # 画10个随机矩形
        Button(self, text='画10个矩形', command=self.draw50Recg).pack()

    def draw50Recg(self):
        for i in range(10):
            x1 = random.randrange(int(int(self.canvas['width']) / 2))
            y1 = random.randrange(int(int(self.canvas['height']) / 2))
            x2 = x1 + random.randrange(int(int(self.canvas['width']) / 2))
            y2 = y1 + random.randrange(int(int(self.canvas['height']) / 2))
            self.canvas.create_oval(x1, y1, x2, y2)

if __name__ == '__main__':
    root = Tk()
    root.title('画布')
    root.geometry('600x400+200+100')
    app = Application(master=root)
    root.mainloop()

实例十 grid布局

grid布局相当于表格布局

from tkinter import *


class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建登陆界面"""
        self.label03 = Label(self, text='用户登陆').grid(row=0, column=0, columnspan=3)

        self.label04 = Label(self, text='认真填写').grid(row=0, column=0)

        self.label01 = Label(self, text='用户名:').grid(row=1, column=0)

        self.entry01 = Entry(self).grid(row=1, column=1)

        self.label02 = Label(self, text='输入手机或身份证').grid(row=1, column=2)

        self.label03 = Label(self, text='密 码:').grid(row=2, column=0)

        self.entry02 = Entry(self, show='*').grid(row=2, column=1)

        self.btn01 = Button(self, text='登录').grid(row=3, column=1, sticky=EW)

        self.btn02 = Button(self, text='取消').grid(row=3, column=2, sticky=E)





if __name__ == '__main__':
    root = Tk()
    root.title('grid布局测试')
    root.geometry('600x300+200+100')
    app = Application(master=root)
    root.mainloop()

实例十一 pack布局

from tkinter import *

root = Tk()
root.geometry('500x250+200+100')

# Frame是一个矩形区域,用来放置其他组件
f1 = Frame(root); f1.pack()
f2 = Frame(root); f2.pack()

btnText = ('流行风', '中国风', '经典风', '轻音乐', '重金属')

for txt in btnText:
    Button(f1, text=txt, borderwidth=1).pack(side='left', padx=10, pady=10)

for i in range(10):
    Label(f2, width=5, height=10, borderwidth=1, relief='solid',
          bg='black' if i % 2 == 0 else 'white').pack(side='left', padx=2)

root.mainloop()

实例十二 place布局

相当于坐标布局 更加灵活

from tkinter import *

root = Tk()
root.geometry('500x300+200+100')
f1 = Frame(root, width=200, height=200, bg='green')
f1.place(x=30, y=30)
# relx 相对于父对象root偏移 值为0-1之间; relx=0.2 x=100 相当于向右偏移0.2x500+100=200,
# relwidth 相对于父本root的宽度和高度,值为0-1
Button(root, text='尚学堂').place(relx=0.2, x=100, y=20, relwidth=0.2, relheight=0.5)
Button(f1, text='高淇老师').place(relx=0.6, rely=0.7)
Button(f1, text='百战程序员').place(x=10, y=10)
root.mainloop()

"""
1.x,y相对于root全局的偏移量,值为像素
2.relx,rely的值都等于root对象的值乘以relx,rely的值,但是偏移的时候要注意组件的父本是谁,例如第一个button的父本是root
第二个组件的父本是f1,所以偏移的时候要看相对偏移的父本与对象
3.relwidth,relheight相对于root的宽度高度
4.relx=0,左, relx=0.5中 relx=1右
5.auchor控制按钮在对象的位置
"""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值