环境包内容:
windows10环境运行
前言 windows10安装python环境
python环境安装
双击python-3.10.4-amd64.exe按照如下步骤安装
1.勾选Add Python 3.10 to PATH
点击’Customize installation’
2.默认全选单击Next
3.可选修改安装目录后点击’Install’
4.安装完毕后点击’DisablePath length limit’(关闭路径长度的限制)
5.点击’是’
6/点击’Close’完成安装
7.验证安装成果在cmd命令提示符中输入’python’得到一下信息证明安装成功
python开发工具安装
安装pyCharm软件
1.双击pycharm-community-2023.1.exe 在弹出的安装程序点击’Next’
2.可选安装路径后点击’Next’
3.默认什么都不勾选点击’Next’
4.点击’Install’
5.安装完成后勾选‘Run PyCharm Community Edition’ 后点击’Finlsh’
6.勾选接受协议后点击’Continue’
7.点击不发送
8.创建第一个工程点击’New Project’
9.设置工程路径:Location
10.选择pytho解释器
11.点击Create完成创建
12.进入窗口后点击Always download
13.Hello World!!!
1 小窗口+按钮绑定事件
from tkinter import *
from tkinter import messagebox
"""
1.小窗口+按钮绑定事件
"""
root = Tk()
root.title("第一个GUI程序")
root.geometry("500x300+100+200")
btn01 = Button(root) # 组件
btn01["text"] = "点我"
btn01.pack()
def songhua(e): # e就是事件对象
messagebox.showinfo("Message", "送你一朵花")
print("送出")
btn01.bind("<Button-1>", songhua)
root.mainloop() # 小窗口 进入事件循环
2 测试一个经典的GUI程序的写法,使用面向对象的方式
"""测试一个经典的GUI程序的写法,使用面向对象的方式"""
from tkinter import *
from tkinter import messagebox
class Application(Frame):
"""一个经典的GUI程序类的写法"""
def __init__(self, master=None):
super().__init__(master) # super()代表的是父类的定义,而不是父类对象
self.pack()
self.master = master
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("送花", "送出送出送出送出送出送出送出送出")
if __name__ == '__main__':
root = Tk()
root.geometry("400x100+200+300")
root.title("一个经典的GUI程序类的写法")
app = Application(master=root)
root.mainloop()
3 测试一个经典的GUI程序的写法,使用面向对象的方式
"""测试一个经典的GUI程序的写法,使用面向对象的方式"""
from tkinter import *
class Application(Frame):
"""一个经典的GUI程序类的写法"""
def __init__(self, master=None):
super().__init__(master) # super()代表的是父类的定义,而不是父类对象
self.pack()
self.master = master
self.createWidget()
def createWidget(self):
"""创建组件"""
self.label01 = Label(self,text="程序员" ,width=10, height=2, bg="black", fg="white")
self.label01["text"] == "员序程"
self.label01.pack()
self.label02 = Label(self, text="经理", width=10, height=2, bg="blue", fg="white",font=("黑体,30"))
self.label02.pack()
#显示图像
global photo
# photo = PhotoImage(file="c:/zk/a.gif")
photo = PhotoImage(file="../imgs/1.gif")
self.label03 = Label(self, image=photo)
self.label03.pack()
self.label04 = Label(self, text="第一行\n第二行\n第三行", borderwidth=1, relief="solid", justify="right")
self.label04.pack()
if __name__ == '__main__':
root = Tk()
root.geometry("400x800+200+300")
root.title("Label测试")
app = Application(master=root)
root.mainloop()
4 测试Button组件的基本用法,使用面向对象的方式
"""测试Button组件的基本用法,使用面向对象的方式"""
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidght()
def createWidght(self):
"""创建组件"""
self.btn01 = Button(root, text="登录",
width=6, height=3, anchor=E, command=self.login)
self.btn01.pack()
global photo
photo = PhotoImage(file="c:/zk/b.gif")
self.btn02 = Button(root, image=photo, command=self.login)
self.btn02.pack()
#self.btn02.config(state="disabled") #设置按钮为禁用
def login(self):
messagebox.showinfo("学习系统","登录成功")
if __name__ == '__main__':
root = Tk()
root.geometry("400x600+200+300")
app = Application(master=root)
root.mainloop()
5 测试Entry组件的基本用法,使用面向对象的方式
"""测试Entry组件的基本用法,使用面向对象的方式"""
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__(self, master=None):
super().__init__(master) #super()代表的是父类的定义,而不是父类对象
self.master = master
self.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 =="gaoqi" and pwd=="123456":
messagebox.showinfo("学习系统","登录成功!开始学习")
else:
messagebox.showinfo("登录失败","请重新登录")
if __name__ == '__main__':
root = Tk()
root.geometry("400x130+200+300")
app = Application(master=root)
root.mainloop()
6 按钮
from tkinter import *
import webbrowser
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.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,"1234566789\nnabcdefg")
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):
#INSTER索引表示在光标处插入
self.w1.insert(1.0, 'Gaoqi')
# END索引号表示在最后插入
self.w1.insert(END, '[sxt]')
self.w1.insert(1.8, "gaoqi")
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):
# global photo
self.photo = PhotoImage(file="c:/zk/a.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程序\n百度\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("450x300+200+300")
app = Application(master=root)
root.mainloop()
7 测试Radiobutton组件的基本用法,使用面向对象的方式
"""测试Radiobutton组件的基本用法,使用面向对象的方式"""
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")
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("测试","选择性别"+self.v.get())
if __name__ == '__main__':
root = Tk()
root.geometry("450x50+200+300")
app = Application(master=root)
root.mainloop()
8 测试Checkbutton组件的基本用法,使用面向对象方式
"""测试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.codeHobby = IntVar();
self.videoHobby = IntVar()
print(self.codeHobby.get()) #默认值是0
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("450x50+200+300")
app = Application(master=root)
root.mainloop()
9 测试Canvas组件的基本用法,使用面向对象的方式
"""测试Canvas组件的基本用法,使用面向对象的方式"""
import random
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.canvas = Canvas(self, width=300, height=500, 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 photo
photo = PhotoImage(file="")
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("450x700+200+300")
app = Application(master=root)
root.mainloop()
10 过grid布局实现登录管理
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):
"""通过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("450x90+200+300")
app = Application(master=root)
root.mainloop()
11 通过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):
"""通过grid布局计算器"""
btnText = (("MC","M+","M-","MR"),
("C","±","/","x"),
("7","8","9","-"),
("4","5","6","+"),
("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,sticky=NSEW,rowspan=2)
elif c=="0":
Button(self,text=c,width=2).grid(row=rindex+1,column=cindex,sticky=NSEW,columnspan=2)
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("220x230+200+300")
app = Application(master=root)
root.mainloop()
12 测试pack布局管理
#测试pack布局管理
from tkinter import *
root = Tk();root.geometry("700x220")
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,20):
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()
13 布局管理器place
from 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()
14 通过place布局管理器实现扑克牌位置控制
from tkinter import *
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
"""通过place布局管理器实现扑克牌位置控制"""
# self.photo= PhotoImage(file="../imgs/1.gif")
# self.puke1 = Label(self.master,image=self.photo)
# self.puke1.place(x=10,y=50)
self.photos = [PhotoImage(file="../imgs/"+str(i+1)+".gif") for i in range(10)]
self.pukes=[Label(self.master,image=self.photos[i]) for i in range(10)]
for i in range(10):
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.geometry("600x350+200+300")
app = Application(master=root)
root.mainloop()
15 测试键盘和鼠标事件
# coding=utf-8
# 测试键盘和鼠标事件
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()
16 测试command属性绑定事件,测试lambda表达式帮助传参
#coding=utf-8
#测试command属性绑定事件,测试lambda表达式帮助传参
from tkinter import *
root = Tk();root.geometry("270x50")
def mouseTest1():
print("commadn方式,简单情况:不涉及获取event对象,可以使用")
def mouseTest2(a,b):
print("a={0},b={1}".format(a,b))
Button(root,text="测试commadn1",command=mouseTest1).pack(side="left")
Button(root,text="测试command2",command=lambda:mouseTest2("mingzhu","azhu")).pack(side="left")
root.mainloop()
17 多种事件绑定方式汇总
#coding = utf-8
#多种事件绑定方式汇总
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)
#commadn属性直接绑定事件
b2= Button(root,text="测试command2",command=lambda: mouseTest2("mingzhu","azhu"))
b2.pack(side="left")
#给所有Button按钮都绑定右键单击事件<Button-2>
b1.bind_class("Button","<Button-2>",mouseTest3)
root.mainloop()
18 optionmenu的使用测试
"""optionmenu的使用测试"""
from tkinter import *
root =Tk();root.geometry("200x100")
v=StringVar(root)
v.set("程序员")
om= OptionMenu(root,v,"尚学堂","程序员","巴拉巴拉")
om["width"] = 10
om.pack()
def test1():
print("最爱的机构",v.get())
# v.set("尚学堂") #直接修改了optionmenu中选中的值
Button(root,text="确定", command=test1).pack()
root.mainloop()
19 sacale滑块的使用测试
"""sacale滑块的使用测试"""
from tkinter import *
root = Tk();root.geometry("400x150")
def test1(value):
print("滑块的值:",value)
newFont = ("宋体",value)
a.config(font=newFont)
# 10到50 长200 间隔5 水平 不写为垂直
s1 = Scale(root,from_=10,to=50,length=200,tickinterval=5,orient=HORIZONTAL,command=test1)
s1.pack()
a = Label(root,text="程序员",width=10,height=1,bg="black",fg="white")
a.pack()
root.mainloop()
20 askcolor颜色选择框的测试,改变背景色
"""askcolor颜色选择框的测试,改变背景色"""
from tkinter import *
from tkinter.colorchooser import *
root = Tk();root.geometry("400x150")
def test1():
s1=askcolor(color="red",title="选择背景色")
print(s1)
#s1的值是:((0.0,0.0,255.99609375),'#0000ff')
root.config(bg=s1[1])
Button(root,text="选择背景色",command=test1).pack()
root.mainloop()
21 文件对话框获取文件
"""文件对话框获取文件"""
from tkinter import *
from tkinter.filedialog import *
root = Tk();root.geometry("400x100")
def test1():
#filetypes实现文件过滤
f = askopenfilename(title="上传文件",
initialdir="c:",filetypes=[("视频文件",".mp4")])
#pring(f)
show["text"]=f
Button(root,text="选择编辑的视频文件",command=test1).pack()
show = Label(root,width=40,height=3,bg="green")
show.pack()
root.mainloop()
22 上传文件
from tkinter import *
from tkinter.filedialog import *
root = Tk();root.geometry("400x100")
def test1():
with askopenfile(title="上传文件",
initialdir="c:",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()
23 简单对话框
"""简单对话框"""
from tkinter import *
from tkinter.simpledialog import *
root = Tk();root.geometry("400x100")
def test1():
a = askinteger(title="输入年龄",prompt="请输入年龄",initialvalue=18,minvalue=1,maxvalue=150)
# askstring,askfloat框使用方式一样
show["text"]=a
Button(root,text="老高你多大了?请输入",command=test1).pack()
show = Label(root,width=40,height=3,bg="green")
show.pack()
root.mainloop()
24 通用消息框
"""通用消息框"""
from tkinter import *
from tkinter.messagebox import *
root = Tk();root.geometry("400x100")
a1 = showinfo(title="尚学堂",message="Python400")
print(a1)
root.mainloop()
25 通用消息框2
"""通用消息框"""
from tkinter import *
from tkinter.messagebox import *
root = Tk();root.geometry("400x100")
a1 = showinfo(title="尚学堂",message="Python400")
print(a1)
root.mainloop()
26 开发记事本软件的菜单
"""开发记事本软件的菜单"""
from tkinter.filedialog import *
from tkinter import *
class Application(Frame):
def __init__(self,master=None):
super().__init__(master)
self.master = master
self.textpad = None
self.pack()
self.createWidget()
def createWidget(self):
#创建主菜单
menubar = Menu(root)
#创建子菜单
menuFile = Menu(menubar)
menuEdit = Menu(menubar)
menuHelp = Menu(menubar)
#将子菜单加入到主菜单
menubar.add_cascade(label="文件(F)",menu=menuFile)
menubar.add_cascade(label="编辑(E)",menu=menuEdit)
menubar.add_cascade(label="帮助(H)",menu=menuHelp)
#添加菜单项
menuFile.add_command(label="新建",accelerator="ctrl+n",command=self.test)
menuFile.add_command(label="打开",accelerator="ctrl+o",command=self.openfile)
menuFile.add_command(label="保存",accelerator="ctrl+s",command=self.savefile)
menuFile.add_separator() #添加分割线
menuFile.add_command(label="退出",accelerator="ctrl+q",command=self.test)
#将主菜单拦加到根窗口
root["menu"] = menubar
#文本编辑区
self.textpad = Text(root,width=50,height=30)
self.textpad.pack()
#创建上下菜单
self.contextMenu = Menu(root)
self.contextMenu.add_command(label="背景颜色",command=self.test)
#为右键绑定事件
root.bind("<Button-3>",self.createContextMenu)
def openfile(self):
self.textpad.delete("1.0","end")
with askopenfile(title="打开文本文件") as f:
self.textpad.insert(INSERT,f.read())
self.filename = f.name
def savefile(self):
with open(self.filename,"w", encoding="utf-8") as f:
c = self.textpad.get(1.0,END)
f.write(c)
def test(self):
pass
def createContextMenu(self,event):
#菜单在鼠标右键单击的坐标处显示
self.contextMenu.post(event.x_root,event.y_root)
if __name__=='__main__':
root=Tk()
root.geometry("450x300+200+300")
root.title("简易记事本")
app = Application(master=root)
root.mainloop()
27 参考