Python tkinter 减少了路径但以完整目录打开
Python tkinter cut down path but open as full directory
这是我的完整 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文件的下拉列表。目前它显示完整的目录,如下所示:
我之前创建了一个 post 关于如何 trim 沿着这条路走下去并得到类似这样的东西:
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
但在后台打开上面的整个路径。
Copy comment: this is what I have tried
directory = os.path.splitdrive("C:/Users/eduards/Desktop/work/data/to-do")
choices = glob.glob(os.path.join(directory[1:], "*.jpg"))
, but says
expected str, bytes or os.Pathlike, not tuple.
Have added [1:]
because the path is split into 2 and returning the 2nd part of it.
Question: Show only the filename in OptionMenu
but get original full path from selection.
创建您自己的 OptionMenu
,它在 dict
中保存所有图像的完整路径,并仅显示文件名作为选项。
- 通过继承
(tk.OptionMenu)
定义您自己的小部件 FileNameOptionMenu
class FileNameOptionMenu(tk.OptionMenu):
def __init__(self, parent, directory, extension, callback):
- 从所有图像中获取完整路径并提取
filename
。
将每个完整路径保存在 dict
中,使用 filename
作为 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
定义一个变量来保存选定的选项供以后使用。
使用 dict
的 keys
的 list
初始化继承的 tk.OptionMenu
。
将 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
- 这个
class method
在每次单击选项选择时都会被调用。
在调用时,它调用 self.callback
,即 ImageLabel.configure
,并带有所选选项的完整路径。
def command(self, val):
self.callback(image=self.glob.get(self.selected.get()))
- 通过继承
(tk.Label)
来定义您自己的小部件 ImageLabel
。
class 扩展了 tk.Label.configure
以处理 .configure(image=<full path>
而不是 .configure(image=<image object>
。
class ImageLabel(tk.Label):
def __init__(self, parent):
super().__init__(parent, image=None)
重载继承的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
- 调用原
tk.Label.configure
显示图片
super().configure(**kwargs)
Usage:
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
这是我的完整 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文件的下拉列表。目前它显示完整的目录,如下所示:
我之前创建了一个 post 关于如何 trim 沿着这条路走下去并得到类似这样的东西:
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
但在后台打开上面的整个路径。
Copy comment: this is what I have tried
directory = os.path.splitdrive("C:/Users/eduards/Desktop/work/data/to-do") choices = glob.glob(os.path.join(directory[1:], "*.jpg"))
, but says
expected str, bytes or os.Pathlike, not tuple.
Have added
[1:]
because the path is split into 2 and returning the 2nd part of it.
Question: Show only the filename in
OptionMenu
but get original full path from selection.
创建您自己的 OptionMenu
,它在 dict
中保存所有图像的完整路径,并仅显示文件名作为选项。
- 通过继承
(tk.OptionMenu)
定义您自己的小部件FileNameOptionMenu
class FileNameOptionMenu(tk.OptionMenu): def __init__(self, parent, directory, extension, callback):
- 从所有图像中获取完整路径并提取
filename
。
将每个完整路径保存在dict
中,使用filename
作为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
定义一个变量来保存选定的选项供以后使用。
使用dict
的keys
的list
初始化继承的tk.OptionMenu
。
将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
- 这个
class method
在每次单击选项选择时都会被调用。 在调用时,它调用self.callback
,即ImageLabel.configure
,并带有所选选项的完整路径。def command(self, val): self.callback(image=self.glob.get(self.selected.get()))
- 通过继承
(tk.Label)
来定义您自己的小部件ImageLabel
。
class 扩展了tk.Label.configure
以处理.configure(image=<full path>
而不是.configure(image=<image object>
。class ImageLabel(tk.Label): def __init__(self, parent): super().__init__(parent, image=None)
重载继承的
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
- 调用原
tk.Label.configure
显示图片super().configure(**kwargs)
Usage:
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