栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python -TkinterGUI初识别

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python -TkinterGUI初识别

GUI初识别
  • 组件对象,事件
from tkinter import *
from tkinter import messagebox

root = TK()#创建窗口

btn01 = Button(root)
btn01["text"] = ""

btn01.pack()

def hua(e): #e是事件对象
		messagebox.showinfo("message","11")#message为名字
	print('song hua')
	
btn01.bind("",hua)#事件绑定(左键)
    
root.mainloop()#进入事件循环(监听用户点击或操作事件[必要])

主窗口位置
root.title('GUI')#标题
root.geometry("500x300+100+200")#+100距左边位置,+200距上边位置
GUI编程整体描述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1gu3VnIi-1653574569884)(C:Users86134AppDataRoamingTyporatypora-user-images1652092649243.png)]

GUI应用程序类的经典写法

####Frame

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.btn01=Button(self)
        self.btn01['text']='点点啦'
        self.btn01.pack()
        self.btn01['command']=self.hua

        self.btnQuit=Button(self, text='退出', command=root.destroy)
        self.btnQuit.pack()


    def hua(self):
        messagebox.showinfo('message','I love you')

if __name__ == '__main__':
    root=Tk()
    root.geometry('500x300+200+100')
    root.title('GUI经典面向对象')
    app = Application(master=root)
    root.mainloop()
菜单组件 Label 标签
  • 都为矩形
  • width,height,font,image,fg前景色,bg为背景色,justify 对齐left,center,right.
    def createWidget(self):
        self.label1=Label(self,font=('宋体',10),height=10,width=10,fg='white',bg='black')
        self.label1['text']='收到了芳建'
        self.label1.pack()
        self.label2 = Label(self, text='机构n我我公司高级n公司的',
                            borderwidth=1,relief='solid', justify='center' )

        self.label2.pack()
        global photo
        photo=PhotoImage(file="image/2.gif")
        self.label3=Label(self,image=photo)
        self.label3.pack()
option选项
#创建对象时,使用命名参数
fred=Button(self,fg='red',bg='blue')
#创建对象后,使用字典索引方式
fred['fg']='red'
fred['bg']='blue'
#创建对象后,使用config()方法
fred.config(fg='red',bg='blue')
Button
self.btn01=Button(self,text='k',command=self.hua)
        self.btn01.pack()
        global photo
        photo=PhotoImage(file="image/2.gif")#不加self
        self.btn02=Button(self,image=photo,comman=self.hua)
        self.btn02.pack()
Entry文本框
    def createWidget(self):
        self.label1=Label(self,text='用户名')
        self.label1.pack()

        '''
        StringVar变量绑定到组件中
        StringVar的值发生变化,同时组件的值也要发生变化
        '''
        a=StringVar()
        self.entry1=Entry(self,textvariable=a)
        a.set('admin')
        self.entry1.pack()

        self.label2 = Label(self, text='密码')
        self.label2.pack()

        b = StringVar()
        self.entry2 = Entry(self, textvariable=b,show='*')
        self.entry2.pack()

        # self.button1=Button(self,text='登录',command=self.login)
        # self.button1.pack()
        Button(self,text='登录',command=self.login).pack()
    def login(self):
        username=self.entry1.get()
        pwd=self.entry2.get()

        print('账户名:'+self.entry1.get())
        print('密码:'+self.entry2.get())
        if username=='大海' and pwd=='123' :
            messagebox.showinfo('hh','恭喜你登入成功')
        else:
            messagebox.showinfo('hh','账号或密码错误,请重新输入')
多行文本框
  • 行列文本操作,可以显示多行文本,还可以显示网页链接,图片,HTML页面,添加组件…
单选框
    def createWidget(self):

        self.v=StringVar()
        self.v.set('f')

        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.hua).pack(side='left')


    def hua(self):
        messagebox.showinfo("测试",'value值为: '+self.v.get())
复选框
def createWidget(self):
    self.code=IntVar()
    self.Video=IntVar()
    
    print(self.code.get())
    self.c1=Checkbutton(self,text='敲代码',variable=self.code,onvalue=1,offvalue=0)
    self.c2=Checkbutton(self,text='看视频',variable=self.video,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.video.get()==1:
        messagebox.showinfo(",",'kk')
    if self.code.get()==1:
        messagebox.showinfo(",",'kk')   
canvas(画布)
  • 矩形区域,可以放置图形,图像,组件等。
    def createWidget(self):
        self.canvas1=Canvas(self,width=200,height=100,bg='green')
        self.canvas1.pack()

        line = self.canvas1.create_line(10,10,20,20)#像素点(10,10)->(20,20)部分
        rec=self.canvas1.create_rectangle(50,50,100,100)
        oval=self.canvas1.create_oval(50,50,100,100)

        self.button1=Button(self,text='画一个椭圆',command=self.hua)
        self.button1.pack()

    def hua(self):
        x1=random.randint(0,int(self.canvas1["height"])/2)
        y1=random.randint(0,int(self.canvas1['width'])/2)
        x2 = x1+random.randint(0, int(self.canvas1["height"])/ 2)
        y2 = y1+random.randint(0, int(self.canvas1['width'])/ 2)
        self.canvas1.create_oval(x1,y1,x2,y2)
布局管理器

####grid布局

    def createWidget(self):
        self.label1=Label(self,text='账户')
        self.label1.grid(column=0,row=0)

        self.entry1=Entry(self)
        self.entry1.grid(column=1,row=0)

        self.label2=Label(self,text='密码')
        self.label2.grid(column=0,row=1)

        self.entry2 = Entry(self)
        self.entry2.grid(column=1, row=1, sticky='WE')

        Button(self,text='确定').grid(column=1,row=2,sticky='WE')
        Button(self,text='取消').grid(column=2,row=2,sticky='WE')
计算机

错误示范:

    def createWidget(self):
        self.entry11=Entry(self)
        self.entry11.grid(row=0,column=0,columnspan=4)

        self.button1 = Button(self, text='MC').grid(row=1,column=0,sticky='WE')
        self.button2 = Button(self, text='M+').grid(row=1,column=1,sticky='WE')
        self.button3 = Button(self, text='M-').grid(row=1,column=2,sticky='WE')
        self.button4 = Button(self, text='MR').grid(row=1,column=3,sticky='WE')

        self.button11 = Button(self, text='C').grid(row=2, column=0,sticky='WE')
        self.button21 = Button(self, text='1').grid(row=2, column=1,sticky='WE')
        self.button31 = Button(self, text='/').grid(row=2, column=2,sticky='WE')
        self.button41 = Button(self, text='x').grid(row=2, column=3,sticky='WE')

        self.button111 = Button(self, text='7').grid(row=3, column=0,sticky='WE')
        self.button211 = Button(self, text='8').grid(row=3, column=1,sticky='WE')
        self.button311 = Button(self, text='9').grid(row=3, column=2,sticky='WE')
        self.button411 = Button(self, text='-').grid(row=3, column=3,sticky='WE')

        self.button112 = Button(self, text='4').grid(row=4, column=0,sticky='WE')
        self.button212 = Button(self, text='5').grid(row=4, column=1,sticky='WE')
        self.button312 = Button(self, text='6').grid(row=4, column=2,sticky='WE')
        self.button412 = Button(self, text='+').grid(row=4, column=3,sticky='WE')

        self.button1121 = Button(self, text='1').grid(row=5, column=0,sticky='WE')
        self.button2121 = Button(self, text='2').grid(row=5, column=1,sticky='WE')
        self.button3121 = Button(self, text='3').grid(row=5, column=2,sticky='WE')
        self.button4121 = Button(self, text='=').grid(row=5, column=3,rowspan=2,sticky='NSWE')

        self.button1121 = Button(self, text='0').grid(row=6, column=0,columnspan=2,sticky='WE')
        self.button2121 = Button(self, text='.').grid(row=6, column=2,sticky='WE')
 

正确示范:

         def createWidget(self):
        self.entry11=Entry(self)
        self.entry11.grid(row=0,column=0,columnspan=4,pady=6,ipady=4)
        list1=[['MC','M+','M-','MR'],['c','±','÷','×'],[7,8,9,'-'],[4,5,6,'+'],[1,2,3,'='],[0,'.']]

        for rindex,value in enumerate(list1):
            for cindex,value2 in enumerate(value):
                if value2=='=':
                    Button(self, text=value2).grid(row=rindex + 1, column=cindex,rowspan=2,sticky=NSEW)
                elif value2 ==0:
                    Button(self, text=value2).grid(row=rindex + 1, column=cindex, columnspan=2, sticky=NSEW)
                elif value2 == '.':
                    Button(self, text=value2).grid(row=rindex + 1, column=cindex+1,sticky=NSEW)
                else:Button(self,text=value2).grid(row=rindex+1,column=cindex,sticky=NSEW)
Pack布局
root=Tk()
a1=Frame(root)
a1.pack()
a2=Frame(root)
a2.pack()
btntext=['中国风','日本风']
for text1 in btntext:
    Button(a1,text=text1).pack(side='left',padx=10)
for i in range(0,10):
    Button(a2,width=10,height=20,bg='black' if i%2==0 else 'white').pack(side='left')
mainloop()
Place布局
from tkinter import *
root=Tk()
root.geometry('500x300')
root.title('place布局管理器')
root['bg']='white'


f1=Frame(root,width=300,height=250,bg='green')
f1.place(x=30,y=40)

Button(root,text='hh').place(relx=0.2,x=100,y=20,relwidth=0.2,relheight=0.5)
Button(f1,text='22').place(relx=0.3,rely=0.4)
Button(f1,text='33').place(relx=0.1,rely=0.2)
mainloop()
扑克牌
from tkinter import *
root=Tk()
root.geometry('600x200+300+200')
def chuqu(event):
    print(event.widget.winfo_y())
    if event.widget.winfo_y()==50:
        event.widget.place(y=30)
    else:
       event.widget.place(y=50)
photos=[PhotoImage(file="i/txt"+str(i)+".gif") for i in range (2,8)]
buttons=[Button(root,image=photos[i-2]) for i in range(2,8)]

for i in range(2,8):
    buttons[i-2].place(x=10+i*40,y=50)
buttons[0].bind_class('Button','',chuqu)
mainloop()
事件处理 鼠标和键盘事件
from tkinter import *
root=Tk()
root.geometry('530x300')
c1=Canvas(root,width=200,height=200,bg='green')
c1.pack()

def mouseTest(event):
    print("鼠标左键单击位置(相对于父容器){0},{1}".format(event.x,event.y))
    print("鼠标左键单击位置(相对于屏幕){0},{1}".format(event.x_root,event.y_root))
    print("事件绑定的组件{0}".format(event.widget))

def testDrag(event):
    c1.create_oval(event.x,event.y,event.x+0.01,event.y+0.01)

def keyboardTest(event):
    print("键的keycode:{0},键的char:{1},键的keysym:{2}".format(event.keycode,event.char,event.keysym))

def press_a_test(event):
    print('press a')

def release_a_test(event):
    print('release a')

c1.bind('',mouseTest)
c1.bind('',testDrag)

root.bind("",keyboardTest)
root.bind("",press_a_test)
root.bind("",release_a_test)


root.mainloop()
lambda表达式

lambda 参数值列表:表达式(简单返回结果)

from tkinter import *
root=Tk()
root.geometry('270x50')

def mouseTest1():
    print("command方式,简单情况:不涉及获取event对象,可以使用")

def mouseTest2(a,b):
    print("a={0},b={1}".format(a,b))

Button(root,text="测试command1",command=mouseTest1).pack(side='left')
Button(root,text="测试command2",command=lambda :mouseTest2("1","2")).pack(side='left')

root.mainloop()
多种事件绑定方式

组件对象的绑定:commandbind()方法
组件类的绑定:bind_class()

from tkinter import *
root=Tk()
def mouseTest1(event):
    print('bind()方式绑定,可以获得event对象')
    print(event.widget)

def mouseTest2(a,b):
    print('a:',a,'b:',b)
    print('command方式绑定,不能直接获取event对象')

def mouseTest3(event):
    print('右键单击事件,已经绑定给所有的按钮了')
    print(event.widget)

b1=Button(root,text='测试mouseTest1')
b1.pack(side='left')
b1.bind('',mouseTest1)

b2=Button(root,text='测试mouseTest2',command=lambda :mouseTest2('hh','yy'))
b2.pack(side='left')

b1.bind_class('Button','',mouseTest3)


root.mainloop()

其他组件

####Option Menu

from tkinter import *
root=Tk()
root.geometry('500x500')

def show():
    print('你是:{0}'.format(a.get()))
a=StringVar(root)
a.set('学生')

a1=OptionMenu(root,a,'老师','管理人员','学生')
a1['width']=10
a1.pack()

b1=Button(root,text='确定',command=show)
b1.pack()
mainloop()
Scale移动滑块
from tkinter import *
root=Tk()
root.geometry('500x500')

def show(value):
    print('滑块的值为:',value)
    newFont=('宋体',value)
    a.config(font=newFont)
s1=Scale(root,from_=10,to=50,length=200,tickinterval=5,orient=HORIZONTAL,command=show)
s1.pack()

a=Label(root,text='hh',width=10,height=1,bg='black',fg='white')
a.pack()

mainloop()
颜色选择框 文件对话框 简单输入对话框

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0V5jeT6l-1653574569886)(C:Users86134AppDataRoamingTyporatypora-user-images1652775108083.png)]

from tkinter.simpledialog import *
root=Tk()
root.geometry('500x500')

def show():
    a=askinteger(title='输入年龄',prompt='请输入年龄',initialvalue=18,minvalue=1,maxvalue=150)
    show1["text"]=a

Button(root,text='how old',command=show).pack()
show1=Label(root,width=10,height=2,bg='green')
show1.pack()#先定义控件,再设置布局。

mainloop()
通用消息框

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zztx22kE-1653574569887)(C:Users86134AppDataRoamingTyporatypora-user-images1652776254095.png)]

之类的

ttk组件 菜单 主菜单
    def createWidget(self):
        #创建主菜单栏
        menubar=Menu(root)


        #创建字菜单栏
        menuFile=Menu(menubar)
        menuEdit=Menu(menubar)
        menuHelp=Menu(menubar)

        #将子菜单栏加入到主菜单栏
        menubar.add_cascade(label='文件',menu=menuFile)
        menubar.add_cascade(label='编辑',menu=menuEdit)
        menubar.add_cascade(label='帮助',menu=menuHelp)

        #增加菜单项
        menuFile.add_cascade(label='新建',accelerator='ctrl+n')
        menuFile.add_cascade(label='打开',accelerator='ctrl+o')
        menuFile.add_cascade(label='保存',accelerator='ctrl+s')
        #将主菜单栏添加到根窗口
        root['menu']=menubar
上下文菜单
self.contextmeum=Menu(root)    self.contextmeum.add_command(label='背景颜色',command=self.text)    root.bind('',self.creatcontextmeum)
def creatcontextmeum(self,event):    #菜单在鼠标右键点击时显示    self.contextmeum.post(event.x_root,event.y_root)def text(self):    pass
)

        #增加菜单项
        menuFile.add_cascade(label='新建',accelerator='ctrl+n')
        menuFile.add_cascade(label='打开',accelerator='ctrl+o')
        menuFile.add_cascade(label='保存',accelerator='ctrl+s')
        #将主菜单栏添加到根窗口
        root['menu']=menubar
上下文菜单
self.contextmeum=Menu(root)    self.contextmeum.add_command(label='背景颜色',command=self.text)    root.bind('',self.creatcontextmeum)
def creatcontextmeum(self,event):    #菜单在鼠标右键点击时显示    self.contextmeum.post(event.x_root,event.y_root)def text(self):    pass
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/932313.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号