作为一个Python初学者,我想通过写博客的方式来记录下来自己成长的过程,同时也分享一下自己学习到的知识。以下都是一个Python初学者对Python语言的一些浅见和个人理解。

from tkinter import *
from tkinter import messageboxroot = Tk()

‘’’
tkinter主窗口
主窗口位置和大小:通过geometry(‘wxh±x±y’)进行设置。w为宽度,h为高度、+x表示距离屏幕左边的距离;-x表示距离屏幕右边的距离;
+y表示距离屏幕上边的距离;-y表示距离屏幕下边的距离
‘’’

root.title("我的第一个GUI程序")
root.geometry("500x300+100+200")btn01 = Button(root)
btn01['text'] = '点我就送花'btn01.pack()def songhua(e):               # e就是事件对象messagebox.showinfo("Message", "送你一朵花,亲亲我吧")print("送你99朵玫瑰花")btn01.bind("<Button-1>", songhua)root.mainloop()   # 调用组件的mainloop()方法,进入事件循环

“”“测试一个经典的GUI程序的写法,使用面向对象的方式”""

from tkinter import *
from tkinter import messageboxclass Application(Frame):"""一个经典的GUI程序的类的写法"""def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.creatWidget()def creatWidget(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("400x100+200+300")root.title("一个经典的GUI程序类的测试")app = Application(master=root)root.mainloop()

“”“测试label,使用面向对象的方式”""

from tkinter import *class Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.creatWidget()def creatWidget(self):"""创建组件"""self.label01 = Label(self, text='中国加油', width=8, height=2, bg='black', fg='white')self.label01.pack()self.label02 = Label(self, text='中国最棒', width=9, height=2, bg='blue', fg='white', font=('黑体',30))self.label02.pack()#显示图像
#      global photo
#     photo = PhotoImage(file="Code07/GUI/imgs/yasuo.gif")
#     self.label03 = Label(self, image=photo)
#     self.label03.pack()#显示多行文本self.label04 = Label(self, text='中国\n中国加油\n中国无敌', borderwidth=5, relief='groove', justify='right')self.label04.pack()
if __name__ == '__main__':root = Tk()root.geometry("400x300+200+300")root.title("label测试")app = Application(master=root)root.mainloop()

#Button
‘’’
Button(按钮)用来执行用户的单击操作。Button可以包含文本,也可以包含图像。按钮被单击后会自动调用对应事件绑定的方法
‘’’

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(root, text='登录', command=self.login)self.btn01.pack()#        global photo
#        photo = PhotoImage(file='imgs/yasuo.gif')
#        self.btn02 = Button(root, image=photo, command=self.login)#       self.btn02.pack()def login(self):messagebox.showinfo("学籍管理系统", "登录成功!欢迎开始学习!")if __name__ == '__main__':root = Tk()root.geometry("400x130+200+300")app = Application(master=root)root.mainloop()

#Entry单行文本框
‘’’
Entry用来接收一行字符串的控件。如果用户输入的文字长度长于Entry控件的宽度时,文字会自动向后滚动
‘’’

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.label01 = Label(self, text="用户名")self.label01.pack()# StringVar变量绑定到指定的组件# StringVar变量的值发生变化,组件内容也变化# 组件内容发生变化,StringVar变量的值也发生变化v1 = StringVar()self.entry01 = Entry(self, textvariable=v1)self.entry01.pack()v1.set("admin")print(v1.get())print(self.entry01.get())# 创建密码框self.label02 = Label(self, text="密码")self.label02.pack()v2 = StringVar()self.entry02 = Entry(self, textvariable=v2,show="*")self.entry02.pack()Button(self, text="登录",command=self.login).pack()def login(self):username = self.entry01.get()pwd = self.entry02.get()print("去数据库比对用户名和密码!")print("用户名:"+username)print("密码"+pwd)if username=="haha" and pwd=="123456":messagebox.showinfo("学习系统", "登陆成功!欢迎开始学习!")else:messagebox.showinfo("学习系统", "登陆失败!用户名或密码错误!")if __name__ == '__main__':root = Tk()root.geometry("400x130+200+300")app = Application(master=root)root.mainloop()
from tkinter import *
import webbrowserclass Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.createWidget()def createWidget(self):self.w1 = Text(root, width=40, height=12, bg="gray")#宽度20个字母(10个汉字),高度一个行高self.w1.pack()self.w1.insert(1.0, "123456789\nabcdefg")self.w1.insert(2.3, "锄禾日当午,汗滴禾下土。谁知盘中餐,粒粒皆辛苦\n")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.testTag).pack(side="left")def insertText(self):#INSERT索引表示在光标处插入self.w1.insert(INSERT, 'haha')#END索引号表示在最后插入self.w1.insert(END, '[ayg]')def returnText(self):# Indexes(索引)是用来指向Text组件中文本的位置,Text的组件索引也是对应实际字符之间的位置# 核心:行号从1开始,列号从0开始print(self.w1.get(1.2, 1.6))print("所有文本内容:\n"+self.w1.get(1.0, END))def addImage(self):self.photo = PhotoImage(file="imgs/yasuo.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 testTag(self):self.w1.delete(1.0, END)self.w1.insert(INSERT, "good good study,day day up\n")self.w1.tag_add("good", 1.0, 1.9)self.w1.tag_config("good", background="yellow", foreground="red")self.w1.tag_add("baidu", 4.0, 4.2)self.w1.tag_config("baidu", underline=True)self.w1.tag_bind("baidu", "<Button-1>", self.webshow)def webshow(self,event):webbrowser.open("http://www.baidu.com")
if __name__ == '__main__':root = Tk()root.geometry("400x300+200+300")app = Application(master=root)root.mainloop()

“”“测试Radiobutton组件的基本用法,使用面向对象方式”""

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.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')self.b1 = Button(root, text='确定', command=self.confirm)self.b1.pack(side='left')def confirm(self):messagebox.showinfo('测试', '选择的性别:'+self.v.get())if __name__ == '__main__':root = Tk()root.title('性别选择器')root.geometry("400x50+200+300")app = Application(master=root)root.mainloop()

“”“测试Checkbutton组件基本用法,使用面向对象的方式”""

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.codeHobby = IntVar()self.videoHobby = IntVar()print(self.codeHobby.get())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.videoHobby.get() == 1:messagebox.showinfo("测试", "看视频")if self.codeHobby.get() == 1:messagebox.showinfo("测试", "写代码")if __name__ == '__main__':root = Tk()root.geometry('400x100+200+300')app = Application(master=root)root.mainloop()

canvas画布

“”"
canvas画布是一个矩形区域,可以放置图形、图像、组件等
“”"

import random
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.canvas = Canvas(self, width=300,height=200, bg="green")self.canvas.pack()#画一条直线line = self.canvas.create_line(10, 10, 30, 20, 40, 50)#画一个矩形rect = self.canvas.create_rectangle(50, 50, 100, 100)#画一个椭圆,坐标两双。为椭圆的边界矩形左上角和底部右下角oval = self.canvas.create_oval(50, 50, 100, 100)global photophoto = PhotoImage(file="F:\Python\Code07\imgs/yasuo.gif")self.canvas.create_image(150, 170, image=photo)Button(self, text="画10个矩形", command=self.draw50Recg).pack(side="left")def draw50Recg(self):for i in range(0, 10):x1 = random.randrange(int(self.canvas["width"])/2)y1 = random.randrange(int(self.canvas["height"])/2)x2 = x1 + random.randrange(int(self.canvas["width"])/2)y2 = y1 + random.randrange(int(self.canvas["height"])/2)self.canvas.create_rectangle(x1, y1, x2, y2)if __name__ == '__main__':root = Tk()root.geometry("400x400+300+300")app = Application(master=root)root.mainloop()

#grid布局管理器

from tkinter import *class Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.createWidget()def createWidget(self):"""通过grid布局实现登录界面"""self.label01 = Label(self, text="用户名")self.label01.grid(row=0, column=0)self.entry01 = Entry(self)self.entry01.grid(row=0, column=1)Label(self, text="用户名为手机号").grid(row=0, column=2)Label(self, text="密码").grid(row=1, column=0)Entry(self, show="*").grid(row=1, column=1)Button(self, text="登录").grid(row=2, column=1, sticky=EW)Button(self, text="取消").grid(row=2, column=2, sticky=E)if __name__ == '__main__':root = Tk()root.geometry("400x200+200+300")app = Application(master=root)root.mainloop()

#pack布局管理器
“”"
pack按照组件的创建顺序将子组件添加到父组件中,按照垂直或者水平的方向自然排布。如果不指定任何选项,默认在父组件中自顶向下垂直添加组件
“”"

from tkinter import *root = Tk()
root.title("钢琴")
root.geometry("700x220")#Frame是一个矩形区域,就是用来放置其他子组件
f1 = Frame(root)
f1.pack()
f2 = Frame(root)
f2.pack()btnText = ("流行风", "中国风", "日本风", "重金属", "轻音乐")for txt in btnText:Button(f1, text=txt).pack(side="left", padx="10")for i in range(1, 13):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布局管理器
“”"
place布局管理器可以通过坐标精确控制组件的位置,适用于一些布局更加灵活的场景
“”"
f

rom tkinter import *root = Tk()
root.geometry("500x300")
root.title("布局管理place")
root["bg"] = "white"f1 = Frame(root, width=200, height=200, bg="green")
f1.place(x=30, y=30)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(relx=0.5, rely=0.2)root.mainloop()

place布局管理-扑克牌游戏

from tkinter import *class Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.createWidget()def createWidget(self):"""通过place布局管理器实现扑克牌位置控制"""self.photos = [PhotoImage(file="F:\Python\Code07\imgs\puke/puke"+str(i+1)+".gif") for i in range(5)]self.pukes = [Label(self.master, image=self.photos[i]) for i in range(5)]for i in range(5):self.pukes[i].place(x=10+i*40, y=50)# 为所有的Label增加事件处理self.pukes[0].bind_class("Label", "<Button-1>", self.chupai)def chupai(self, event):print(event.widget.winfo_geometry())print(event.widget.winfo_y())if event.widget.winfo_y() == 50:event.widget.place(y=30)else:event.widget.place(y=50)if __name__ == "__main__":root = Tk()root.title("扑克牌游戏")root.geometry("300x270+200+300")app = Application(master=root)root.mainloop()

#计算器界面实现

from tkinter import *class Application(Frame):def __init__(self, master=None):super().__init__(master)self.master = masterself.pack()self.createWidget()def createWidget(self):"""通过grid布局实现计算器的界面"""btnText = (("MC", "M+", "M-", "MR"),("C", "±", "÷", "x"),(7, 8, 9, "+"),(1, 2, 3, "="),(0, "."))Entry(self).grid(row=0, column=0, columnspan=4, pady=10)for rindex,r in enumerate(btnText):for cindex,c in enumerate(r):if c == '=':Button(self, text=c, width=2).grid(row=rindex+1, column=cindex, rowspan=2, sticky=NSEW)elif c == 0:Button(self, text=c, width=2).grid(row=rindex+1, column=cindex, columnspan=2, sticky=NSEW)elif c == ".":Button(self, text=c, width=2).grid(row=rindex+1, column=cindex+1, sticky=NSEW)else:Button(self, text=c, width=2).grid(row=rindex+1, column=cindex, sticky=NSEW)if __name__ == '__main__':root = Tk()root.geometry("200x200+200+300")root.title("计算器")app = Application(master=root)root.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+1, event.y+1)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()

多种事件绑定汇总

from tkinter import *root = Tk()
root.geometry("270x30")def mouseTest1(event):print("bind()方式绑定,可以获取event对象")print(event.widget)def mouseTest2(a, b):print("a={0},b={1}".format(a, b))print("command方式绑定,不能直接获取event对象")def mouseTest3(event):print("右键单击事件,绑定给所有按钮")print(event.widget)b1 = Button(root, text="测试bind()绑定")
b1.pack(side="left")# bind方式绑定事件
b1.bind("<Button-1>", mouseTest1)# command属性直接绑定事件
b2 = Button(root, text="测试command2", command=lambda: mouseTest2("haha", "xixi"))
b2.pack(side="left")# 给所有Button按钮都绑定右键单击事件<Button-3>
b1.bind_class("Button", "<Button-3>", mouseTest3)root.mainloop()

#OptionMenu选择项
“”“OptionMenu(选择项)用来做多选一,选中的项在顶部显示”""

from tkinter import *root = Tk()
root.geometry("200x100+200+300")
v = StringVar(root)
v.set("程序员")
om = OptionMenu(root, v, "教师", "公务员", "销售")om["width"] = 10
om.pack()def test1():print("最喜爱的职业:", v.get())Button(root, text="确定", command=test1).pack()root.mainloop()

#Scale移动滑块
“”"
Scale(移动滑块)用于在指定的数值区间,通过滑块的移动来选择值
“”"

from tkinter import *root = Tk()
root.geometry("400x150")def test1(value):print("滑块的值:", value)newFont = ("宋体", value)a.config(font=newFont)s1 = Scale(root, from_=10, to=50, length=200, tickinterval=10, orient=HORIZONTAL, command=test1)
s1.pack()a = Label(root, text="加油好青年", width=10, height=1, bg="green", fg="white")
a.pack()root.mainloop()

#颜色选择框
“”"
颜色选择框可以帮助我们设置背景色、前景色、画笔颜色、字体颜色等
“”"

from tkinter import *
from tkinter.colorchooser import *root = Tk()
root.geometry("400x150+200+300")def test1():s1 = askcolor(color="red", title="背景色")print(s1)root.config(bg=s1[1])Button(root, text="选择背景色", command=test1).pack()root.mainloop()

#文件对话框
“”"
文件对话框帮助我们实现可视化的操作目录、操作文件。最后,将文件、目录的信息传入到程序中。
“”"

from tkinter import *
from tkinter.filedialog import *root =Tk()
root.geometry("400x100")def test1():with askopenfile(title="上传文件", initialdir="f:", filetypes=[("文本文件", "txt")]) as f:show["text"] = f.read()Button(root, text="选择读取的文本文件", command=test1).pack()show = Label(root, width=40, height=3, bg="green")
show.pack()root.mainloop()

#简单输入对话框

from tkinter import *
from tkinter.simpledialog import *root = Tk()
root.geometry("400x100")def test1():a = askinteger(title="输入年龄", prompt="请输入年龄", initialvalue=18, minvalue=1, maxvalue=150)show["text"]=aButton(root, text="年龄是多少?请输入", command=test1).pack()show = Label(root, width=40, height=3, bg="green")
show.pack()root.mainloop()

#通用消息框

from tkinter import *
from tkinter.messagebox import *root = Tk()
root.geometry("400x100")a1 = showinfo(title="程序员", message="好好写代码")
print(a1)root.mainloop()

Python---GUI相关推荐

  1. python gui框架_Python的GUI框架PySide的安装配置教程

    (一)说在前面 Python自带了GUI模块Tkinter,只是界面风格有些老旧.另外就是各种GUI框架了. 之前安装过WxPython,并做了简单的界面.遂最近又重新搜索了一下网上关于Python ...

  2. 入门 Python GUI 开发的第一个坑

    由于微信不允许外部链接,你需要点击文章尾部左下角的 "阅读原文",才能访问文中链接. 使用 Anaconda 3(conda 4.5.11)的 tkinter python 包(c ...

  3. python的电脑推荐_推荐8款常用的Python GUI图形界面开发框架

    作为Python开发者,你迟早都会用到图形用户界面来开发应用.本文将推荐一些 Python GUI 框架,希望对你有所帮助,如果你有其他更好的选择,欢迎在评论区留言. Python 的 UI 开发工具 ...

  4. Python GUI编程-了解相关技术[整理]

    Python GUI编程-了解相关技术[整理] 我们可以看到,其实python进行GUI开发并没有自身的相关库,而是借用第三方库进行开发.tkinter是tcl/tk相关,pyGTK是Gtk相关,wx ...

  5. 产生随机数的用户图形界面Python GUI

    前言: Python GUI(用户图形界面)创建可以使用Python自带的Tkinter包,不需要额外装包.下面通过随机数的产生的例子进行初步了解. 源代码 windows系统.python3.7 # ...

  6. python gui漂亮_python 漂亮的gui

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 我想知道如何为我的pythongui创建漂亮的ui. 就像这样: 或者像这样.. ...

  7. python的gui库哪个好_常用的13 个Python开发者必备的Python GUI库

    [Python](http://www.blog2019.net/tag/Python?tagId=4)是一种高级编程语言,它用于通用编程,由Guido van Rossum 在1991年首次发布.P ...

  8. python使用界面-推荐8款常用的Python GUI图形界面开发框架

    作为Python开发者,你迟早都会用到图形用户界面来开发应用.本文将推荐一些 Python GUI 框架,希望对你有所帮助,如果你有其他更好的选择,欢迎在评论区留言. Python 的 UI 开发工具 ...

  9. 好玩的python代码示例-这可能是最好玩的python GUI入门实例!

    image.png 简单的说,GUI编程就是给程序加上图形化界面. python的脚本开发简单,有时候只需几行代码就能实现丰富的功能,而且python本身是跨平台的,所以深受程序员的喜爱. 如果给程序 ...

  10. python入门代码示例-这可能是最好玩的python GUI入门实例!

    image.png 简单的说,GUI编程就是给程序加上图形化界面. python的脚本开发简单,有时候只需几行代码就能实现丰富的功能,而且python本身是跨平台的,所以深受程序员的喜爱. 如果给程序 ...

最新文章

  1. 文件重定向(hook IRP_MJ_CREATE)
  2. python软件加密、固定机器使用_如何用Python进行最常见的加密操作?(附最新400集Python教程)...
  3. C++五子棋(五)——实现AI落子
  4. NodeJS——模块全局安装路径配置以及关于supervisor的问题解释
  5. 富文本编辑器中空格转化为a_文本编辑器题解
  6. [Alpha阶段]发布说明
  7. Mysql: mysqlbinlog命令查看日志文件
  8. Excel图表如何更改坐标轴最大值
  9. 那些年我们一起上过的黑客网站
  10. 【地震数据处理】GAN网络基础知识
  11. android 悬浮窗截屏,GitHub - tyhjh/ScreenShot: Android截屏的封装
  12. 学生的认知风格类型有哪些_学生认知方式的类型
  13. nack fec心得
  14. tumblr_如何制作私人Tumblr博客
  15. 快递规模持续扩大,丰网加盟迎发展新机遇
  16. 3个小时学会wordpress模板制作
  17. linux 节点互信,Linux 集群节点互信ssh配置
  18. C++经典算法题-迭代法求方程根
  19. 微信小程序:从头开始(一)
  20. 常见的网络问题-初级

热门文章

  1. 编写一个能将给定非负整数列表中的数字排列成最大数字的函数
  2. kafka集群消费之ConsumerRecord类
  3. 【Teradata】DBQL使用
  4. P5.js图片旋转,自旋
  5. 【2021年新书推荐】Managing Microsoft Teams: MS-700 Exam Guide
  6. 【数据处理】 python 基于Basemap地理信息可视化
  7. 酒店押金预授权怎么开通?一台智能设备+收银APP完美解决方案
  8. GitHub页面基本知识
  9. Python_8h_Study
  10. 光源、照明方法、相机与镜头配套原则、PPI