这是我当前的Python代码:
from tkinter import *
import glob
import os
root = Tk()
root.title("SIGN OFF")
root.minsize(840, 800)
# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
# Create a Tkinter variable
tkvar = StringVar(root)
# Dictionary with options
options = glob.glob("C:/Users/eduards/Desktop/[![enter image description here][1]][1]work/data/to-do/*.jpg*")
choices = {*options}
tkvar.set('...To Sign Off...') # set the default option
popupMenu = OptionMenu(mainframe, tkvar, *choices)
Label(mainframe, text="Choose your sign off here:").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
# on change dropdown value
def change_dropdown(*args):
directory = (tkvar.get())
os.startfile(directory)
def open():
img = change_dropdown()
photo = ImageTK.PhotoImage(img)
root.label2 = Label(image=photo)
root.label2.image = photo
root.label2.grid(column = 3 , row = 5)
Button(mainframe, text="Open", command = change_dropdown).grid(row = 3, column = 1)
root.mainloop()
这是输出:
当我选择图像上所示的目录时,单击“确定”时,它将在单独的窗口中打开图像。如何在同一窗口的侧面打开它?喜欢,预览某种东西?
答案 0 :(得分:0)
我不确定我是否完全理解您的问题-并认为您真正想做的是在同一窗口(而非目录)中显示选择的图像。您当前的代码正在单独的窗口中打开图像,因为它在os.startfile()
回调函数中通过change_dropdown()
调用显示了该图像,该函数将打开与系统上的.jpg
文件关联的任何应用程序-在我的系统上恰好是Windows Photo Viewer
。
无论如何,这是我认为至少可以完成您要完成的工作的基本代码的代码:
import glob
import os
from PIL import Image, ImageTk
import tkinter as tk
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 = "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
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)
# On change dropdown callback.
def change_dropdown(*args):
""" Updates label2 image. """
imgpath = tkvar.get()
img = Image.open(imgpath)
photo = ImageTk.PhotoImage(img)
label2.image = photo
label2.configure(image=photo)
tk.Button(mainframe, text="Open", command=change_dropdown).grid(row=3, column=1)
root.mainloop()
这是我从下拉列表OptionMenu
中选择一个图像,然后单击 Open Button
后在我的系统上运行的屏幕快照: