0
点赞
收藏
分享

微信扫一扫

python—tkinter(GUI模块)

创建最基本的界面

import tkinter

# 创建GUI界面
window = tkinter.Tk()
window.title("tittle") # window标题
window.maxsize(300, 200) # window的大小
window.minsize(300, 200) # 通过设置最大最小一样,可以实现window不可缩放大小

# 进入消息循环, 只有执行mainloop才会显示窗体
window.mainloop()

效果如下图
python—tkinter(GUI模块)_缩放

设置一个按钮,点击后可选择文件, 并将文件路径显示到窗体上

import tkinter
from tkinter import ttk
from tkinter import filedialog
import re

# 文件路径和文件名称
filePath = ""
fileName = ""


# 打开文件 并获取路径和文件名
def openFile():
global filePath
global fileName
filePath = filedialog.askopenfilename()
fileName = "".join(re.findall(r'[^\\/:*?"<>|\r\n]+$', filePath))
mes.set(filePath) # 给mes设置新的字符串,可以实时显示到绑定到entry上


# 创建GUI界面
window = tkinter.Tk()
window.title("tittle") # window标题
window.maxsize(300, 200) # window的大小
window.minsize(300, 200) # 通过设置最大最小一样,可以实现window不可缩放大小

button = ttk.Button(window, text="选择文件", command=lambda: openFile()) # command为点击按钮触发的事件
button.place(x=0, y=0) # place用于设置按钮的位置

# 显示文件路径
mes = tkinter.StringVar()
entry = tkinter.Entry(window, textvariable=mes) # textvariable可以让消息和mes变量绑定
entry["state"] = "readonly" # 设置为只读类型
entry.place(x=90, y=0, width=200, height=27)

# 进入消息循环, 只有执行mainloop才会显示窗体.通常放在代码的最后
window.mainloop()

效果如下图

python—tkinter(GUI模块)_文件名_02

最终版,加上了message多行显示

import tkinter
from tkinter import ttk
from tkinter import filedialog
import re

# 文件路径和文件名称
filePath = ""
fileName = ""


# 打开文件 并获取路径和文件名
def openFile():
global filePath
global fileName
filePath = filedialog.askopenfilename()
fileName = "".join(re.findall(r'[^\\/:*?"<>|\r\n]+$', filePath))
mes.set(filePath) # 给mes设置新的字符串,可以实时显示到绑定到entry上
msg_txt.set("显示成功!")

# 创建GUI界面
window = tkinter.Tk()
window.title("tittle") # window标题
window.maxsize(300, 200) # window的大小
window.minsize(300, 200) # 通过设置最大最小一样,可以实现window不可缩放大小

button = ttk.Button(window, text="选择文件", command=lambda: openFile()) # command为点击按钮触发的事件
button.place(x=0, y=0) # place用于设置按钮的位置

# Entry控件
mes = tkinter.StringVar()
entry = tkinter.Entry(window, textvariable=mes) # textvariable可以让消息和mes变量绑定
entry["state"] = "readonly" # 设置为只读类型
entry.place(x=90, y=0, width=200, height=27)

# Message控件
msg_txt = tkinter.StringVar() # Message也可以进行显示变量的绑定
msg = tkinter.Message(window, textvariable=msg_txt, background="white", anchor="nw")
msg.place(x=10, y=40, width=280, height=150)

# 进入消息循环, 只有执行mainloop才会显示窗体.通常放在代码的最后
window.mainloop()

效果如下图
python—tkinter(GUI模块)_缩放_03


举报

相关推荐

0 条评论