Python GUI: 选择图片并运行程序
使用 Python Tkinter 创建简单的图片选择和运行程序界面
这篇文章将使用 Python 的 Tkinter 库创建一个简单的图形用户界面 (GUI),实现选择图片文件并显示在界面上的功能,并模拟运行程序返回结果。
代码:
from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
def open_file():
file_path = filedialog.askopenfilename(filetypes=[('Image files', '*.jpg;*.jpeg;*.png')])
image = Image.open(file_path)
image = image.resize((300, 300))
photo = ImageTk.PhotoImage(image)
image_label.config(image=photo)
image_label.image = photo
def run_program():
result_label.config(text='Program is running...')
root = Tk()
root.title('Image Program')
# Open File Button
open_button = Button(root, text='Open File', command=open_file)
open_button.pack(pady=10)
# Image Display
image_label = Label(root)
image_label.pack(pady=10)
# Run Program Button
run_button = Button(root, text='Run Program', command=run_program)
run_button.pack(pady=10)
# Result Label
result_label = Label(root, text='')
result_label.pack(pady=10)
root.mainloop()
运行结果:

代码解释:
- 导入库: 导入
tkinter库用于创建 GUI,filedialog用于打开文件,PIL库用于处理图像。 open_file()函数: 当点击“Open File”按钮时调用此函数,它使用filedialog.askopenfilename()打开文件选择对话框,选择图片文件后,打开图片并将其调整大小,然后使用ImageTk.PhotoImage()将图片转换为 Tkinter 可以显示的格式,最后设置image_label显示图片。run_program()函数: 当点击“Run Program”按钮时调用此函数,它模拟程序运行,将结果标签result_label的文本设置为 'Program is running...'。- 创建主窗口: 使用
Tk()创建主窗口,并设置标题为 'Image Program'。 - 创建按钮: 创建“Open File”和“Run Program”按钮,并设置点击事件分别为
open_file()和run_program()。 - 创建标签: 创建
image_label用来显示图片,result_label用来显示程序运行结果。 - 运行主窗口: 使用
root.mainloop()运行主窗口,保持窗口一直运行直到关闭。
注意: 此代码仅演示了如何创建界面,实际运行程序需要根据你的程序逻辑编写 run_program() 函数。
相关内容:
希望这篇文章能够帮助你使用 Python 创建简单的 GUI。
原文地址: https://www.cveoy.top/t/topic/nPAc 著作权归作者所有。请勿转载和采集!