【问题标题】:Skip files on button click [tkinter + Python 3.5]单击按钮时跳过文件 [tkinter + Python 3.5]
【发布时间】:2020-06-01 19:36:49
【问题描述】:

假设我想通过 tkinter 控制台查看目录 filedir 中有“n”个图像文件。现在,我想在必要时跳过一些文件,使用调用函数 nextFile() 的按钮单击事件。

例如

import os


def nextFile():
    global img
    img_2 = process(img)
    return img_2


window = tk.Tk()
window.title("File Viewer")
files = os.listdir(filedir)
button1 = tk.Button(window, text="Browse Files...", fg="black", command=askopenfilename)
button2 = tk.Button(window, text="SELECT", width=50, command=nextFile)
canvas = tk.Canvas(window, width=width, height=height)
button1.pack(side=tk.LEFT)
button2.pack(side=tk.BOTTOM)
canvas.pack()

for f in files:
    img = cv2.cvtColor(cv2.imread(filedir + '/' + f), cv2.COLOR_BGR2RGB)
    photo = ImageTk.PhotoImage(image=Image.fromarray((img))
    canvas.create_image(0, 0, image=photo, anchor=tk.CENTER)

window.mainloop() 

感谢任何帮助。谢谢!

【问题讨论】:

  • 您的函数中不需要return。此外,此函数每次调用时都会创建一个 tk 的新实例。我会做一些改变。那或者你的缩进搞砸了。您将根窗口命名为my_window,然后告诉您的小部件放置在window 上。这不起作用,应该出错。
  • 抱歉缩进。我现在编辑了它。
  • command=askopenfilename 对你没有任何好处。按钮不能对任何函数/方法返回的值做任何事情。
  • 我需要从文件夹中递归加载图像,并在必要时跳过。
  • 您可以做的就是将该目录中的所有文件名加载到一个列表中。然后构建一个函数,根据列表索引在点击时加载图像。

标签: python-3.x image tkinter


【解决方案1】:

这是一个简单的示例,使用 PIL 加载初始图像,然后使用按钮和函数加载每个下一个图像。

import tkinter as tk
from PIL import ImageTk, Image
import os

path = 'C:/your/file/path/here'

def nextFile():
    # the global is needed to keep track of current index and also keep
    # a reference of the image being displayed so its is not garbage collected.
    global current_ndex, image
    current_ndex += 1
    if current_ndex < len(files):
        img = Image.open('{}/{}'.format(path, files[current_ndex]))
        image = ImageTk.PhotoImage(img)
        # clear the canvas before adding the new image.
        canvas.delete("all")
        canvas.create_image(0, 0, image=image, anchor=tk.CENTER)


my_window = tk.Tk()
my_window.title("File Viewer")
files = os.listdir(path)

current_ndex = 0

button2 = tk.Button(my_window, text="Next", width=50, command=nextFile)
canvas = tk.Canvas(my_window, width=100, height=100)
button2.pack(side=tk.BOTTOM)
canvas.pack()

first_image = files[0]

img = Image.open('{}/{}'.format(path, first_image))
image = ImageTk.PhotoImage(img)
canvas.create_image(0, 0, image=image, anchor=tk.CENTER)
my_window.mainloop()

【讨论】:

  • 感谢您的回答。当我为单个图像运行时,它会在画布上加载图像,但是当我尝试从目录中递归加载文件时,它会引发以下错误:TclError: image "pyimage77" doesn't exist
  • 也许这篇文章会有所帮助。 stackoverflow.com/questions/24274072/…。我没有你提到的错误。我的结果适用于多张图片。
  • 是的,这就是问题所在。谢谢!
猜你喜欢
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-25
  • 2020-12-07
  • 1970-01-01
  • 2020-10-03
  • 2021-05-17
  • 1970-01-01
相关资源
最近更新 更多