GUI初识别

  • 组件对象,事件
from tkinter import *
from tkinter import messageboxroot = TK()#创建窗口btn01 = Button(root)
btn01["text"] = ""btn01.pack()def hua(e): #e是事件对象messagebox.showinfo("message","11")#message为名字print('song hua')btn01.bind("<Button-1>",hua)#事件绑定(左键)root.mainloop()#进入事件循环(监听用户点击或操作事件[必要])

主窗口位置

root.title('GUI')#标题
root.geometry("500x300+100+200")#+100距左边位置,+200距上边位置

GUI编程整体描述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1gu3VnIi-1653574569884)(C:\Users\86134\AppData\Roaming\Typora\typora-user-images\1652092649243.png)]

GUI应用程序类的经典写法

####Frame

from tkinter import *
from tkinter import messageboxclass Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.createWidget()def createWidget(self):self.btn01=Button(self)self.btn01['text']='点点啦'self.btn01.pack()self.btn01['command']=self.huaself.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 photophoto=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 photophoto=PhotoImage(file="image/2.gif")#不加selfself.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','<Button-1>',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('<Button-1>',mouseTest)
c1.bind('<B1-Motion>',testDrag)root.bind("<KeyPress>",keyboardTest)
root.bind("<KeyPress-a>",press_a_test)
root.bind("<KeyRelease-a>",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()

多种事件绑定方式

组件对象的绑定:command\bind()方法
组件类的绑定: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('<Button-1>',mouseTest1)b2=Button(root,text='测试mouseTest2',command=lambda :mouseTest2('hh','yy'))
b2.pack(side='left')b1.bind_class('Button','<Button-3>',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:\Users\86134\AppData\Roaming\Typora\typora-user-images\1652775108083.png)]

from tkinter.simpledialog import *
root=Tk()
root.geometry('500x500')def show():a=askinteger(title='输入年龄',prompt='请输入年龄',initialvalue=18,minvalue=1,maxvalue=150)show1["text"]=aButton(root,text='how old',command=show).pack()
show1=Label(root,width=10,height=2,bg='green')
show1.pack()#先定义控件,再设置布局。mainloop()

通用消息框

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zztx22kE-1653574569887)(C:\Users\86134\AppData\Roaming\Typora\typora-user-images\1652776254095.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('<Button-3>',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('<Button-3>',self.creatcontextmeum)
def creatcontextmeum(self,event):    #菜单在鼠标右键点击时显示    self.contextmeum.post(event.x_root,event.y_root)def text(self):    pass

Python -TkinterGUI初识别相关推荐

  1. 基于Python的人脸识别课堂考勤系统(毕设)

    一个菜鸟搞毕业设计的过程分享,可能对迷茫的你起到一点点作用! 序言 在着手开发项目之前我们一定要对系统进行一个初步的规划,比如系统可以实现什么功能,是否需要开发GUI页面(大部分导师都会让你搞一个,仅 ...

  2. 读《Hands-On Transfer Learning with Python》初体验

    读<Hands-On Transfer Learning with Python>初体验 最近由于工作原因及个人兴趣,对迁移学习兴趣盎然,很想深入了解该领域知识,偶得该领域最新力作,现分享 ...

  3. 基于Python的验证码识别技术

    基于Python的验证码识别技术 作者:强哥 概述 前言 准备工作 识别原理 图像处理 切割图像 人工标注 训练数据 检测结果 搞笑一刻 福利一刻 推荐阅读 前言 很多网站登录都需要输入验证码,如果要 ...

  4. python使用正则表达式识别大写字母并在大写字母前插入空格

    python使用正则表达式识别大写字母并在大写字母前插入空格 #python使用正则表达式识别大写字母并在大写字母前插入空格 import redef putSpace(input):# regex ...

  5. python实现人脸识别抓取人脸并做成熊猫头表情包(2)之优化

    上次做完python实现人脸识别抓取人脸并做成熊猫头表情包之后就放了一下,因为还要好好学习Springboot毕竟这才是找工作的硬实力.但是优化这个代码心里面一直很想,借用<clean code ...

  6. 关于利用python进行验证码识别的一些想法

    关于利用python进行验证码识别的一些想法 - 小五义 - 博客园 关于利用python进行验证码识别的一些想法 转载请注明:@小五义http://www.cnblogs.com/xiaowuyi ...

  7. python人脸识别训练模型_开源 | 基于Python的人脸识别:识别准确率高达99.38%!

    原标题:开源 | 基于Python的人脸识别:识别准确率高达99.38%! 该库使用 dlib 顶尖的深度学习人脸识别技术构建,在户外脸部检测数据库基准(Labeled Faces in the Wi ...

  8. python颜色识别原理_电脑控制手机 Python实现颜色识别功能

    原标题:电脑控制手机 Python实现颜色识别功能 用电脑控制手机好几年了,Total Control作为安卓手机的多控系统,是我用过各方面都比较稳定的一款软件了.通过脚本实现识别颜色是其强大功能之一 ...

  9. python 图像处理与识别书籍_Python图像处理之识别图像中的文字(实例讲解)

    ①安装PIL:pip install Pillow(之前的博客中有写过) ②安装pytesser3:pip install pytesser3 ③安装pytesseract:pip install p ...

最新文章

  1. 关于手机已处理里重复单据的处理办法
  2. 可解释机器学习发展和常见方法!
  3. ES6解构赋值学习总结
  4. EL之GB(GBC):利用GB对二分类问题进行建模并评估
  5. java 的对象强制转换后的调用
  6. JavaFX其他事件
  7. [Java]LeetCode138. 复制带随机指针的链表 | Copy List with Random Pointer
  8. 高中计算机室名言,高中班级激励格言
  9. 动态规划——乘积为正数的最长子数组长度(Leetcode 1567)
  10. Ibatis SqlMapclient对象
  11. matlab虚拟现实之vrbuild2模型导入
  12. 【阿圆总结】关于平时阅读的推荐
  13. [转]C#综合揭秘——细说进程、应用程序域与上下文之间的关系
  14. ubuntu 18.04桌面版启动错误: Unable to mount root fs on unknown-block(0,0)
  15. LayaAir 定时器 Timer
  16. java企业员工考勤请假工资人事管理系统springboot+vue
  17. html连接有道词典api,调用有道翻译API
  18. 百度披露被黑原委 黑客骗得邮箱
  19. 共享打印机提示服务器没有运行,提示无法共享打印机: “无法显示该属性,后台打印程序服务未运行”...
  20. MySQL当前读和快照读

热门文章

  1. VS2010编译出来的程序不兼容Win7 再解
  2. 30-Figma-常规配图添加方式-批量配图
  3. 2019 0828浦发银行面经
  4. 学习机?原来是中了文件夹变exe文件的病毒Trojan-Dropper.Win32.Flystud.yo
  5. 变异注释软件VEP安装
  6. NSX-T 系列:第 10部分 - 添加和配置T0网关
  7. PCB模块化设计05——晶体晶振PCB布局布线设计规范
  8. ios预览在线pdf
  9. Steam VR设备连接问题,求解答!
  10. 确认访问用户身份的验证