Tkinter图片幻灯片程序实现启动弹窗选择图片文件夹路径
Tkinter图片幻灯片路径选择功能需求
我使用Python3搭配Tkinter开发了一款图片幻灯片程序,核心播放逻辑运行正常,但目前仅支持在代码内部硬编码指定图片文件夹路径。由于程序面向的分享用户不具备修改代码的能力,需要新增以下功能:
- 程序启动时弹出Tkinter窗口,提示用户指定本地图片文件夹路径
- 支持用户将图片文件夹路径复制粘贴到窗口内的文本输入框中
初始版本代码
初始编写的幻灯片代码如下:
import tkinter as Tk from PIL import Image, ImageTk import random import glob class GUI: def __init__(self, mainwin): self.mainwin = mainwin self.mainwin.title("Our Photos") self.mainwin.configure(bg="yellow") self.counter = 0 self.frame = Tk.Frame(mainwin) self.frame.place(relheight=0.85, relwidth=0.9, relx=0.05, rely=0.05) self.img = Tk.Label(self.frame) self.img.pack() self.pic_list = glob.glob("/home/maheswar/Pictures/*") self.colours = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace', 'linen', 'antique white', 'papaya whip', 'blanched almond'] self.colour() self.pic() def colour(self): selected = random.choice(self.colours) self.mainwin.configure(bg=selected) root.after(4000, self.colour) def pic(self): filename = self.pic_list[self.counter] image = Image.open(filename) real_aspect = image.size[0]/image.size[1] width = int(real_aspect * 800) image = image.resize((width, 800)) self.photo = ImageTk.PhotoImage(image) self.img.config(image=self.photo) self.counter += 1 if self.counter >= len(self.pic_list): self.counter = 0 root.after(2000, self.pic) root = Tk.Tk() myprog = GUI(root) root.geometry("1000x1000") root.mainloop()
补充:可直接运行的测试代码
以下为提供给有需要的用户测试使用的完整可运行代码:
import tkinter as Tk from PIL import Image, ImageTk import random import glob from tkinter import filedialog class GUI: def __init__(self, mainwin): self.mainwin = mainwin self.mainwin.title("Our Photos") self.mainwin.configure(bg="yellow") self.counter = 0 self.frame = Tk.Frame(mainwin) self.frame.place(relheight=0.85, relwidth=0.9, relx=0.05, rely=0.05) self.img = Tk.Label(self.frame) self.img.pack() #self.pic_list = glob.glob("/home/maheswar/Pictures/*") directory = filedialog.askdirectory(parent=mainwin, title='Path asker', initialdir='/home') self.pic_list = glob.glob(f"{directory}/*") self.colours = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace', 'linen', 'antique white', 'papaya whip', 'blanched almond', 'bisque', 'peach puff', 'navajo white', 'lemon chiffon'] self.colour() self.pic() def colour(self): selected = random.choice(self.colours) self.mainwin.configure(bg=selected) root.after(4000, self.colour) def pic(self): filename = self.pic_list[self.counter] image = Image.open(filename) real_aspect = image.size[0]/image.size[1] width = int(real_aspect * 800) image = image.resize((width, 800)) self.photo = ImageTk.PhotoImage(image) self.img.config(image=self.photo) self.counter += 1 if self.counter >= len(self.pic_list): self.counter = 0 root.after(2000, self.pic) root = Tk.Tk() myprog = GUI(root) root.geometry("1000x1000") root.mainloop()
内容的提问来源于stack exchange,提问作者mahiatlinux
相关产品推荐
相关产品推荐

