У меня две проблемы:
1. Я не могу получить возвращаемое значение (proj_info) при вызове класса из другого файла.
2. Как я могу импортировать мой интерфейс в другой скрипт без повторного импорта Tkinter?
Я все еще пытаюсь понять, как структурировать Tkinter с помощью классов и всех моих функций.
import os
try:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
except ImportError:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
class ChooseProjectInterface:
def __init__(self, master):
bgcol = "#28282e"
txtcol = "#848484"
htxtcol = "#ffffff"
orangehcol = '#e64b3d'
orangehcol1 = '#e56458'
bgwincol = '#1f1f1f'
window_height = 90
window_width = 385
# TK basic setup
self.master = master
self.master.title('Choose project')
# self.tk_root.overrideredirect(1)
# Set colors
self.master.configure(bg=bgcol)
# Center tk_root Window
self.master.resizable(False, False) # This code helps to disable windows from resizing
self.screen_width = self.master.winfo_screenwidth()
self.screen_height = self.master.winfo_screenheight()
self.x_cordinate = int((self.screen_width / 2) - (window_width / 2))
self.y_cordinate = int((self.screen_height / 2) - (window_height / 2))
self.master.geometry("{}x{}+{}+{}".format(window_width, window_height, self.x_cordinate, self.y_cordinate))
projects_on_nas = []
projects_on_nas_path = []
search_path = r"/Volumes/Project_Server/Projects/"
p = ''.join(["^", # Start of string being matched
"[0-2]", # First character a number 0 through 2 (less than 3)
"[6-9]", # Second character a number 6 through 9 (single digit greater than 5)
"(0(?=[0-9])|1(?=[0-2]))",
# (lookahead) A 0 followed only by any number 0 through 9 **OR** A 1 followed only by any number 0 through 2
"((?<=0)[1-9]|(?<=1)[0-2])",
# (lookbehind) Match 1-9 if the preceding character was a 0, match 0-2 if the preceding was a 1
"_", # Next char is a "_"
"[A-Z]", # Next char (only) is an upper A through Z
".*$" # Match anything until end of string
])
# Check if NAS path exists
print(os.path.exists(search_path))
if os.path.exists(search_path) is True:
# Search and store projectnames on NAS in projects_on_nas
for root, dirs, files in self.walklevel(search_path, level=1):
for projectname in dirs:
if re.match(p, projectname):
projects_on_nas.append(projectname)
projects_on_nas_path.append(root)
# temp_proj_dict = [projectname: root for name, path in projects_on_nas, projects_on_nas_path]
self.temp_proj_dict = dict(zip(projects_on_nas, projects_on_nas_path))
# Reverse list descending
projects_on_nas.reverse()
# Print found projects on NAS
print(projects_on_nas)
# Drop-down Menu Edit Stage
self.selected = StringVar()
self.selected.set('Choose Project') # (stages[3])
self.dpd0 = OptionMenu(self.master, self.selected, *projects_on_nas) # highlightcolor=htxtcol , bg=bgcol, fg=txtcol
self.dpd0.config(bg=bgcol, activebackground=bgcol, fg=txtcol, highlightcolor=htxtcol, activeforeground=htxtcol)
self.dpd0["menu"].configure(bg=bgcol, activebackground=bgcol, fg=txtcol, activeforeground=htxtcol)
self.dpd0.grid(column=0, row=0, padx=10, pady=10) # sticky=W
else:
print("Server was not found, please choose another directory")
# Insert Custom Project
self.selected = StringVar()
self.custom_Project_btn = Entry(self.master, textvar=self.selected, bg=bgwincol, fg=txtcol)
self.custom_Project_btn.grid(row=0, column=2, padx=10, pady=10, ipadx=120)
self.custom_Project_btn.insert(0, "Insert Project Name (Sample: (1911)_(CocaCola)_(XMasNow)")
# new_notes = cusnotes.get()
# Create Timeline Button
self.cproj_btn_frame = Frame(self.master, background=orangehcol, bo=1, relief="flat")
self.cproj_btn = Button(self.cproj_btn_frame, text="Choose project", command=self.get_project_infos, bg=bgcol, fg=txtcol, activebackground=bgcol, activeforeground=htxtcol, bd=0)
self.cproj_btn_frame.grid(row=3, column=2)
self.cproj_btn.grid(row=3, column=2, padx=1, pady=1, ipadx=30)
#
#
# # Custom Project Name Button
# self.cprojn_btn_frame = Frame(tk_root, background=orangehcol, bo=1, relief="flat")
# self.cprojn_btn = Button(cprojn_btn_frame, text="Use custom project name", command=create_cus_allin_timeline, bg=bgcol, fg=txtcol, activebackground=bgcol, activeforeground=htxtcol, bd=0)
# self.cprojn_btn_frame.grid(row=3, column=0, padx=10, pady=10)
# self.cprojn_btn.grid(row=3, column=0, padx=1, pady=1, ipadx=30)
def walklevel(self, some_dir, level=1):
"""Define a function to limit search dir depth called walklevel"""
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs, files
num_sep_this = root.count(os.path.sep)
if num_sep + level <= num_sep_this:
del dirs[:]
def get_project_infos(self):
proj_name_input = self.selected.get()
proj_name_path = self.temp_proj_dict[proj_name_input]
proj_info = proj_name_input, proj_name_path
print('Choosen project is: {} Path:{}'.format(proj_name_input, proj_name_path))
self.master.destroy()
return proj_info
if __name__ == '__main__':
root_tk = Tk()
ChooseProjectInterface(root_tk)
root_tk.mainloop()
То, что я делаю для вызова моего интерфейса: Я хочу избавиться от необходимости снова импортировать Tkinter и вернуть мой "proj_info".
from Choose_project_from_Server_class_v001 import ChooseProjectInterface
try:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
except ImportError:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
root_tk = Tk()
my_gui = ChooseProjectInterface(root_tk)
print(my_gui)
root_tk.mainloop()