我想在同一个窗口中选择更多目录。为了选择目录,我准备了课程SelectDir
。我从课程Gui
调用此对象(使用SelectDir
。OpenDirWnd()
)。现在,我无法从班级SelectDir
中tk.Entry
的班级Gui
获取目录名称。
import tkinter as tk
from tkinter.filedialog import askdirectory
class SelectDir():
def __init__(self,master, title,dirInit):
self.dir_opt = options = {}
self.dirInit = dirInit
options['parent'] = master
options['title'] = title
options['initialdir'] = self.dirInit
self.master = master
self.dirSelect = tk.StringVar()
self.dirSelect.set(self.dirInit)
def OpenDirWnd(self):
self.master.grab_set()
self.dirSelect = askdirectory(**self.dir_opt)
if self.dirSelect == "":
self.dirSelect.set(self.dirInit)
def NameSelectDir(self):
return self.dirSelect
class Gui(tk.Frame):
def __init__(self,master):
tk.Frame.__init__(self, master)
frMaster = tk.Frame(master)
seldir = SelectDir(master, " Select directory",
"D:\\MyPgm\\Python\\Tiles_8")
button = tk.Button(frMaster,text=">>>",command = seldir.OpenDirWnd )
frMaster.place(relx=0.04, rely=0.35)
button.grid(column = 0, row=0)
self.actDir = tk.StringVar()
self.actDir.set("D:\\MyPgm\\Python\\Tiles_8")
entry= tk.Entry(frMaster,textvariable = self.actDir,width = 30)
entry.grid(column = 0, row=1)
wndRoot = tk.Tk()
appapp = Gui(master=wndRoot)
appapp.mainloop()
答案 0 :(得分:0)
您应该在Gui
创建功能并分配给按钮 - 此功能应使用SelectDir
显示窗口,然后从SelectDir
获取信息并输入Entry
< / p>
BTW:我更改了一些代码(即名称,因为我们更喜欢函数/方法和变量的lower_case名称以及类的CamelCase名称。查看更多:PEP 8 -- Style Guide for Python Code)
import tkinter as tk
from tkinter.filedialog import askdirectory
# --- classes ---
class SelectDir():
def __init__(self, master, title, initial):
self.master = master
self.initial = initial
self.selected = initial
self.options = {
'parent': master,
'title': title,
'initialdir': initial,
}
def show(self):
result = askdirectory(**self.options)
if result:
self.selected = result
#self.options['initialdir'] = result
# or
#return self.selected
def get(self):
return self.selected
class Gui(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
frame = tk.Frame(master)
frame.pack()
self.seldir = SelectDir(self, "Select directory", "D:\\MyPgm\\Python\\Tiles_8")
button = tk.Button(frame, text=">>>", command=self.select_dir)
button.grid(column=0, row=0)
self.act_dir = tk.StringVar()
self.act_dir.set("D:\\MyPgm\\Python\\Tiles_8")
entry = tk.Entry(frame, textvariable=self.act_dir, width=30)
entry.grid(column=0, row=1)
def select_dir(self):
self.seldir.show()
self.act_dir.set(self.seldir.get())
# or
#result = seldir.show()
#self.act_dir.set(result)
# --- main ---
root = tk.Tk()
app = Gui(root)
root.mainloop()