Python Tkinter削减了路径,但以完整目录打开

时间:2019-09-17 22:37:39

标签: python tkinter listdir tkinter.optionmenu

这是我完整的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文件下拉列表。当前它显示完整的目录,如下所示:

enter image description here

我早些时候发表了一篇关于如何缩小路径的文章,并得到了这样的内容:

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个并返回了它的第二部分。

1 个答案:

答案 0 :(得分:0)

  

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

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


  1. 通过继承FileNameOptionMenu来定义自己的窗口小部件(tk.OptionMenu)
    class FileNameOptionMenu(tk.OptionMenu):
        def __init__(self, parent, directory, extension, callback):
    
  2. 从所有图像获取完整路径并提取filename
    使用dictfilename保存为key,并将完整路径另存为value,将每个完整路径保存在 # 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 中。
    tk.OptionMenu
  3. 定义一个变量,该变量保留选定的选项以供以后使用。
    使用listkeys的{​​{1}}中继承的dict
    class method self.command作为command=传递。
    保存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.configure扩展为处理.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
    捕获名称参数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