0

这是我的完整 Python 代码:

from tkinter import *
import glob
import os
from PIL import Image, ImageTk, ImageGrab
import tkinter as tk
import pyautogui
import datetime

#date & time
now = datetime.datetime.now()

root = tk.Tk()
root.title("SIGN OFF")
root.minsize(840, 800)

# Add a grid
mainframe = tk.Frame(root)
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
mainframe.pack(pady=100, padx=100)

# Create a Tkinter variable
tkvar = tk.StringVar(root)


# Directory
directory = "C:/Users/eduards/Desktop/work/data/to-do"
choices = glob.glob(os.path.join(directory, "*.jpg"))
tkvar.set('...To Sign Off...') # set the default option

# Dropdown menu
popupMenu = tk.OptionMenu(mainframe, tkvar, *choices)
tk.Label(mainframe, text="Choose your sign off here:").grid(row=1, column=1)
popupMenu.grid(row=2, column=1)

label2 = tk.Label(mainframe, image=None)
label2.grid(row = 4, column = 1, rowspan = 10)

# On change dropdown callback.
def change_dropdown(*args):
    """ Updates label2 image. """
    imgpath = tkvar.get()
    img = Image.open(imgpath)
    img = img.resize((240,250))
    photo = ImageTk.PhotoImage(img)
    label2.image = photo
    label2.configure(image=photo)


tk.Button(mainframe, text="Open", command=change_dropdown).grid(row=3, column=1)


def var_states():
    text_file = open("logfile.txt", "a")
    text_file.write("TIME: %s, USER: %s, One %d, Two %d\n" % (now,os.getlogin(), var1.get(), var2.get()))
    text_file.close()
    print("One %d, Two %d" % (var1.get(), var2.get()))

var1 = IntVar()
Checkbutton(mainframe, text="Ingredients present in full (any allergens in bold with allergen warning if necessary)", variable=var1).grid(column = 2, row=1, sticky=W)
var2 = IntVar()
Checkbutton(mainframe, text="May Contain Statement.", variable=var2).grid(column = 2, row=2, sticky=W)
var3 = IntVar()
Checkbutton(mainframe, text="Cocoa Content (%).", variable=var3).grid(column = 2, row=3, sticky=W)
var4 = IntVar()
Checkbutton(mainframe, text="Vegetable fat in addition to Cocoa butter", variable=var4).grid(column = 2, row=4, sticky=W)
var5 = IntVar()
Checkbutton(mainframe, text="Instructions for Use.", variable=var5).grid(column = 2, row=5, sticky=W)
var6 = IntVar()
Checkbutton(mainframe, text="Additional warning statements (pitt/stone, hyperactivity etc)", variable=var6).grid(column = 2, row=6, sticky=W)
var7 = IntVar()
Checkbutton(mainframe, text="Nutritional Information Visible", variable=var7).grid(column = 2, row=7, sticky=W)
var8 = IntVar()
Checkbutton(mainframe, text="Storage Conditions", variable=var8).grid(column = 2, row=8, sticky=W)
var9 = IntVar()
Checkbutton(mainframe, text="Best Before & Batch Information", variable=var9).grid(column = 2, row=9, sticky=W)
var10 = IntVar()
Checkbutton(mainframe, text="Net Weight & Correct Font Size.", variable=var10).grid(column = 2, row=10, sticky=W)
var11 = IntVar()
Checkbutton(mainframe, text="Barcode - Inner", variable=var11).grid(column = 2, row=11, sticky=W)
var12 = IntVar()
Checkbutton(mainframe, text="Address & contact details correct", variable=var12).grid(column = 2, row=12, sticky=W)

def user():
    user_input = os.getlogin()
    tk.Label(mainframe, text = user_input, font='Helvetica 18 bold').grid(row = 0, column = 1)


user()


def save():
    # pyautogui.press('alt')
    # pyautogui.press('printscreen')
    # img = ImageGrab.grabclipboard()
    # img.save('paste.jpg', 'JPEG')

    var_states()


tk.Button(mainframe, text = "Save", command = save).grid(row = 20, column = 1)


root.mainloop()

当我运行代码时,会有一个 jpg 文件的下拉列表。目前它显示完整目录,如下所示:

在此处输入图像描述

我之前创建了一篇关于如何修剪路径的帖子,并得到了如下内容:

files = os.listdir("C:/Users/eduards/Desktop/work/data/to-do")
print(files)

但是如果我使用上面的代码,点击时它不会打开路径,open因为它没有完整的路径名。

我想要做的是,为了显示目的而减少路径名,并按照原始完整路径打开图像。

举个例子:

当前下拉菜单显示C:/Users/eduards/Desktop/work/data/to-do/img1.jpg 我想要的结果是img1.jpg但在后台打开上面的整个路径。

复制评论:这是我尝试过的

directory = os.path.splitdrive("C:/Users/eduards/Desktop/work/data/to-do")
choices = glob.glob(os.path.join(directory[1:], "*.jpg"))

,但说

expected str, bytes or os.Pathlike, not tuple. 

已添加[1:],因为路径被分成 2 并返回它的第二部分。

4

1 回答 1

0

问题:仅显示文件名,OptionMenu但从选择中获取原始完整路径。

创建您自己的OptionMenu,它从所有图像中保存 a 中的完整路径,dict并且仅将文件名显示为选项。


  1. FileNameOptionMenu通过继承定义您自己的小部件(tk.OptionMenu)
    class FileNameOptionMenu(tk.OptionMenu):
        def __init__(self, parent, directory, extension, callback):
    
  2. 从所有图像中获取完整路径并提取filename. 使用as
    将每个完整路径保存在 a中,并将完整路径保存为. dictfilenamekeyvalue
            # Save result from `glob` in a `dict`
            self.glob = {}
            for fpath in glob.glob(os.path.join(directory, "*.{}".format(extension))):
                filename, extension = os.path.splitext(os.path.split(fpath)[1])
                self.glob[filename] = fpath
    
  3. 定义一个变量来保存所选选项以供以后使用。用from 的init
    继承。 通过as 。 保存以备后用。tk.OptionMenulistkeysdict
    class method self.commandcommand=
    callback

            self.selected = tk.StringVar(parent, 'Select a image...')
            super().__init__(parent, self.selected, *list(self.glob),
                             command=self.command)
    
            self.callback = callback
    
    
  4. class method会在每次点击选项选择时调用。在调用时,它使用所选选项的完整路径 调用self.callback,即。ImageLabel.configure
        def command(self, val):
            self.callback(image=self.glob.get(self.selected.get()))
    
  5. ImageLabel通过继承来定义您自己的小部件(tk.Label)
    此类扩展了tk.Label.configureto 处理.configure(image=<full path>而不是.configure(image=<image object>.
    class ImageLabel(tk.Label):
        def __init__(self, parent):
            super().__init__(parent, image=None)
    
  6. 重载继承的class method tk.Label.configure.
    捕获 name 参数image=并将传递的完整路径替换为image object.

        def configure(self, **kwargs):
            key = 'image'
            if key in kwargs:
                # Replace the filepath with the image
                fpath = kwargs[key]
    
                img = Image.open(fpath)
                img = img.resize((240, 250))
                self._image = ImageTk.PhotoImage(img)
    
                kwargs[key] = self._image
    
  7. 调用原图tk.Label.configure显示图片
            super().configure(**kwargs)
    

用法

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

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        self.label_image = ImageLabel(parent=self)
        self.label_image.grid(row=2, column=0)

        self.option_menu = \
            FileNameOptionMenu(parent=self,
                               directory='C:/Users/eduards/Desktop/work/data/to-do',
                               extension='jpg',
                               callback=self.label_image.configure
                                               )
        self.option_menu.grid(row=0, column=0)


if __name__ == "__main__":
    App().mainloop()

用 Python 测试:3.5

于 2019-09-18T20:56:25.703 回答