class Sobre: def __init__(self, master): self.master = master self.sobre_janela = Toplevel() self.sobre_janela.resizable(0, 0) self.sobre_janela.title("Sobre") self.sobre_janela.geometry("400x300") self.sobre_janela.protocol("WM_DELETE_WINDOW", self.on_close) self.sobre_janela.withdraw() self.sobre_janela.grid() self.sobre_janela.transient(self.master) self.sobre_janela.grab_set() sobre_frame = Frame(self.sobre_janela, relief=RAISED, borderwidth=1) sobre_frame.pack(fill=BOTH, expand=True) ok_btn = ttk.Button(self.sobre_janela, text="Ok", width=10, command=self.on_close) ok_btn.pack(side=RIGHT) # frame_kiri grid_frame = Frame(sobre_frame, bd=10) grid_frame.pack(fill=BOTH, expand=YES, side=LEFT) centro_(self.sobre_janela) self.sobre_janela.deiconify() self.master.wait_window(self.sobre_janela) def on_close(self): self.sobre_janela.destroy()
def display_help_text(): """Show help text in a scrolled text box in a child window.""" helptext_frame = Toplevel(root) helptext_frame.grid() help_text = scrolledtext.ScrolledText(helptext_frame, bg='skyblue', fg='black', width=78, height=30) help_text.grid() with open(r'cards/tpm-help.txt', 'r') as f: text_contents = f.read() help_text.insert(INSERT, text_contents)
class T_GUI: def __init__(self, root): self.language = { '阿尔巴尼亚语': 'sq', '阿拉伯语': 'ar', '阿姆哈拉语': 'am', '阿塞拜疆语': 'az', '爱尔兰语': 'ga', '爱沙尼亚语': 'et', '巴斯克语': 'eu', '白俄罗斯语': 'be', '保加利亚语': 'bg', '冰岛语': 'is', '波兰语': 'pl', '波斯尼亚语': 'bs', '波斯语': 'fa', '布尔语南非荷兰语': 'af', '丹麦语': 'da', '德语': 'de', '俄语': 'ru', '法语': 'fr', '菲律宾语': 'tl', '弗里西语': 'fy', '高棉语': 'km', '格鲁吉亚语': 'ka', '古吉拉特语': 'gu', '哈萨克语': 'kk', '海地克里奥尔语': 'ht', '韩语': 'ko', '豪萨语': 'ha', '荷兰语': 'nl', '吉尔吉斯语': 'ky', '加利西亚语': 'gl', '加泰罗尼亚语': 'ca', '捷克语': 'cs', '卡纳达语': 'kn', '科西嘉语': 'co', '克罗地亚语': 'hr', '库尔德语': 'ku', '拉丁语': 'la', '拉脱维亚语': 'lv', '老挝语': 'lo', '立陶宛语': 'lt', '卢森堡语': 'lb', '罗马尼亚语': 'ro', '马尔加什语': 'mg', '马耳他语': 'mt', '马拉地语': 'mr', '马拉雅拉姆语': 'ml', '马来语': 'ms', '马其顿语': 'mk', '毛利语': 'mi', '蒙古语': 'mn', '孟加拉语': 'bn', '缅甸语': 'my', '苗语': 'hmn', '南非科萨语': 'xh', '南非祖鲁语': 'zu', '尼泊尔语': 'ne', '挪威语': 'no', '旁遮普语': 'pa', '葡萄牙语': 'pt', '普什图语': 'ps', '齐切瓦语': 'ny', '日语': 'ja', '瑞典语': 'sv', '萨摩亚语': 'sm', '塞尔维亚语': 'sr', '塞索托语': 'st', '僧伽罗语': 'si', '世界语': 'eo', '斯洛伐克语': 'sk', '斯洛文尼亚语': 'sl', '斯瓦希里语': 'sw', '苏格兰盖尔语': 'gd', '宿务语': 'ceb', '索马里语': 'so', '塔吉克语': 'tg', '泰卢固语': 'te', '泰米尔语': 'ta', '泰语': 'th', '土耳其语': 'tr', '威尔士语': 'cy', '乌尔都语': 'ur', '乌克兰语': 'uk', '乌兹别克语': 'uz', '希伯来语': 'iw', '希腊语': 'el', '西班牙语': 'es', '夏威夷语': 'haw', '信德语': 'sd', '匈牙利语': 'hu', '修纳语': 'sn', '亚美尼亚语': 'hy', '伊博语': 'ig', '意大利语': 'it', '意第绪语': 'yi', '印地语': 'hi', '印尼巽他语': 'su', '印尼语': 'id', '印尼爪哇语': 'jw', '英语': 'en', '约鲁巴语': 'yo', '越南语': 'vi', '中文繁体': 'zh-TW', '中文简体': 'zh-CN' } self.common_list = [['英语'], ['西班牙语'], ['中文简体'], ['日语']] lan_sort_1 = sorted( self.language.keys(), key=lambda char: lazy_pinyin(char)[0][0]) # 排好序的语种list table_len, lan_sort = len(self.language), [] # 按扭最大宽度,表格横竖比 button_max_width, table = len(max(lan_sort_1, key=len)) + 2, (ceil( table_len / 7), 7) for i in range(0, len(lan_sort_1), table[0]): # 格式化成二维数组, lan_sort.append(lan_sort_1[i:i + table[0]]) # 由于后面会进行行纵交换操作,这里取最大值为列数 # print(button_max_width) var, var_1 = StringVar(), StringVar() var.set('自动检测') var_1.set(lan_sort_1[-1]) self.root = root self.root.title('书香年华的专用翻译小工具') self.font = Font() self.frame = ttk.Frame(self.root) self.text = Text(self.frame, width=20, height=10) self.text_out = Text(self.frame) self.button_1 = ttk.Button(self.frame, text='自动检测') self.button_2 = ttk.Button(self.frame, text='<=>') self.button_3 = ttk.Button(self.frame, text='中文简体') self.button_4 = ttk.Button(self.frame, text='翻译') self.top_1 = Toplevel(self.button_1) self.top_2 = Toplevel(self.button_3) self.foc_button = None self.top_3 = Toplevel(self.button_1) self.tree_1 = ttk.Treeview(self.top_1) self.tree_2 = ttk.Treeview(self.top_2) self.tree_3 = ttk.Treeview(self.top_3) self.canvas_1 = Canvas(self.tree_1) self.canvas_2 = Canvas(self.tree_2) self.canvas_3 = Canvas(self.tree_3) self.canvas_1_text = self.canvas_1.create_text(0, 0) self.canvas_2_text = self.canvas_2.create_text(0, 0) self.canvas_3_text = self.canvas_3.create_text(0, 0) self.sizegrip = ttk.Sizegrip(self.frame) # 方便调整窗口大小的部件 # 菜单按钮没写,已完成2018.07.30 # 位置布局 self.frame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W)) self.text_out.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W)) self.button_1.grid(row=1, column=0, sticky=E) self.button_2.grid(row=1, column=1) self.button_3.grid(row=1, column=2, sticky=W) self.button_4.grid(row=1, column=3) self.text.grid(row=2, column=0, columnspan=4, sticky=(N, S, E, W)) self.top_1.grid() self.top_2.grid() self.top_3.grid() self.tree_1.grid() self.tree_2.grid() self.tree_3.grid() self.sizegrip.grid(row=2, column=3, sticky=(S, E)) self.root.rowconfigure(0, weight=1) self.root.columnconfigure(0, weight=1) self.frame.columnconfigure(0, weight=2) self.frame.columnconfigure(1, weight=1) self.frame.columnconfigure(2, weight=1) self.frame.columnconfigure(3, weight=4) self.frame.rowconfigure(0, weight=3) self.frame.rowconfigure(2, weight=1) # 字体设置 self.text_out.tag_configure('font', foreground='#476042', font=('Tempus Sans ITC', 35, 'bold')) self.text_out.tag_configure('font_normal', font=20) self.text_out.tag_configure('font_error', foreground='red', font=('Segoe Print', 16, 'bold')) self.text.insert(END, '输入框', 'SUNKEN') self.text.focus_set() self.text.tag_add('sel', 1.0, END) # 全选文本 # self.frame.tk_focusFollowsMouse() self.text_out.insert(END, '输出框', ('GROOVE', 'font_normal')) self.all_var = [self.text.get(0.0, END), var, var_1, True] self.text_out.configure(state=DISABLED) # 忽略并隐藏窗口 self.top_1.wm_overrideredirect(True) self.top_2.wm_overrideredirect(True) self.top_3.wm_overrideredirect(True) self.top_1.withdraw() self.top_2.withdraw() self.top_3.withdraw() # 事件0 self.text_out.bind('<Button-3>', self._right_click) # 右键复制文本 self.button_1.bind('<Enter>', self._button_menu) self.button_1.bind('<Leave>', self._button_leave) self.button_3.bind('<Enter>', self._button_menu) self.button_3.bind('<Leave>', self._button_leave) # self.top_3.bind('Leave', lambda e: self.top_3.withdraw()) self.top_1.bind('<FocusOut>', self._lose_focus) # 失去焦点隐藏窗口 self.top_2.bind('<FocusOut>', self._lose_focus) self.top_3.bind('<FocusOut>', self._lose_focus) # 在同一个位置,第一次按是tree部件,第二次是canvas部件 self.canvas_1.bind('<ButtonPress-1>', lambda evt: self.top_1.withdraw()) # 画布按下时,隐藏窗口 self.tree_1.bind( '<Configure>', lambda evt: self.canvas_1.grid_forget()) # place_forget()取消选中状态 self.tree_1.bind('<ButtonPress-1>', self._tree_pressed) self.tree_1.bind('<Leave>', lambda e: self.top_1.withdraw()) # 离开某组件,隐藏窗口 self.canvas_2.bind('<ButtonPress-1>', lambda evt: self.top_2.withdraw()) # 画布按下时,隐藏窗口 self.tree_2.bind( '<Configure>', lambda evt: self.canvas_2.grid_forget()) # place_forget()取消选中状态 self.tree_2.bind('<ButtonPress-1>', self._tree_pressed) self.tree_2.bind('<Leave>', lambda e: self.top_2.withdraw()) # 离开某组件,隐藏窗口 self.canvas_3.bind('<ButtonPress-1>', lambda evt: self.top_3.withdraw()) self.tree_3.bind('<Configure>', lambda evt: self.canvas_3.grid_forget()) self.tree_3.bind('<ButtonPress-1>', self._tree_pressed) self.tree_3.bind('<Leave>', lambda e: self.top_3.withdraw()) # 表格设置 # print(table, lan_sort) # 7列 15行 self.tree_1.configure(show='', selectmode='none', height=table[0]) self.tree_2.configure(show='', selectmode='none', height=table[0]) self.tree_3.configure(show='', selectmode='none', height=4) self.tree_1['columns'] = tuple([lan_sort[i] for i in range(table[1])]) # 7行,循环7次 self.tree_2['columns'] = tuple([lan_sort[i] for i in range(table[1])]) self.tree_3['columns'] = ('', ) # 列数 self.items_1 = [ self.tree_1.insert('', 'end', values='') for _ in range(table[0]) ] self.items_2 = [ self.tree_2.insert('', 'end', values='') for _ in range(table[0]) ] self.items_3 = [ self.tree_3.insert('', 'end', values='') for _ in range(4) ] for i in range(1 + 1): # 由于后面会进行行列交换,所以这里添的是列数 self.tree_3.column('#%d' % i, width=button_max_width * 10 + 4) for i in range( table[1] + 1): # 列头不像行头(不纳入计数),默认保留列头(#0),所以得加一,才能显示正确,不然最后一列无法配置width self.tree_1.column('#%d' % i, width=button_max_width * 10 + 4) self.tree_2.column('#%d' % i, width=button_max_width * 10 + 4) if lan_sort[-2] != lan_sort[-1]: # 填补空白数据,使表格在后续处理中不会丢失数据 lan_sort[-1].extend([' '] * (len(lan_sort[-2]) - len(lan_sort[-1]))) table_list = tuple(map(list, zip(*lan_sort))) # 行列交换 # common_table_list = tuple(map(list, zip(*self.common_list))) # print(self.items_2, self.items_3) # table_list = [[row[i] for row in lan_sort] for i in range(len(lan_sort[0]))] for index, item in enumerate(self.items_3): self.tree_3.item(item, values=self.common_list[index]) # print(self.common_list[index]) for index, (item_1, item_2) in enumerate(zip(self.items_1, self.items_2)): self.tree_1.item(item_1, values=table_list[index]) self.tree_2.item(item_2, values=table_list[index]) # print(item_2, table_list[index]) table_list[-2][-1] = '自动检测' # 补充数据 self.tree_1.item('I00E', values=table_list[-2]) self.button_1.config(width=(button_max_width - 3) * 2) self.button_3.config(width=(button_max_width - 3) * 2) self.button_1.configure(command=self._button_menu_1) self.button_3.configure(command=self._button_menu_2) self.button_2.configure(command=self._swap_key) self.button_4.configure(command=self._button_translation) # self.root.attributes('-alpha') # self.root.attributes('-alpha', 0.8) # 设置窗口属性,这里是设置透明度 # 队列 self.q = queue.LifoQueue(9) # self.q.put(list([proxy_main.run, None])) # Thread_0(self.q) # 这里开线程运行附加程序 # list_script = (startup_script, '', self._text_1_show) # self.q.put(list_script) # Thread_0(self.q) self._real_translation() # def _thread_update(self, e): # 创建线程 # Thread_0(e) def _real_update(self, src_text): # 加入数据到队列 fun_list = (self._translator_word, src_text, self._text_1_show) self.q.put(fun_list) # print(threading.activeCount()) 获取线程数 MyTread_0(self.q) def _swap_key(self): # 交换语种 a_var, b_var = self.all_var[1].get(), self.all_var[2].get() if a_var == '自动检测': a_var = '中文简体' if a_var == b_var: return a_var, b_var = b_var, a_var # 这里添加判断语种,根据情况是否put数据到队列 self.button_1.config(text=a_var) self.button_3.config(text=b_var) self._real_update(self.text.get(0.0, END)) sleep(0.1) def _real_translation(self): """实时翻译""" src_text = self.text.get(0.0, END) if not self._is_change(src_text): # print('产生变化') self._real_update(src_text) # print('dd%s无变化' % src_text) self.root.after(2500, self._real_translation) def _right_click(self, _): """右键事件,可能会添加激活控件再操作,已添加聚焦""" self.text_out.focus_set() text_txt = self.text_out.get(0.0, END) copy(text_txt) def _translator_word(self, string_var): # 翻译 """翻译""" # print('数据来了') if self._is_change(string_var) or string_var.strip( ) == '': # 交换语种后与显示语种相同直接返回,字符为空也返回 return # print('有谁', len(string_var.strip()), bool(string_var.strip() == '')) # return self.all_var[1].set(self.button_1['text']) self.all_var[2].set(self.button_3['text']) self.all_var[0] = string_var self._text_1_show(' \n IN translation...\n', 3.5, 3.5, ('GROOVE', 'font')) des_language, src_language = self.all_var[2].get( ), self.all_var[1].get() src_1 = 'auto' if src_language == '自动检测' else self.language[ src_language] # try: # print(string_var, '开始翻译了') des_string = google_tran(string_var, des_1=self.language[des_language], src_1=src_1).text self._text_1_show(des_string, style=('GROOVE', 'font_normal')) # except Exception as e: # 异常处理 # self._text_1_show(e) def _is_change(self, src_text): """判断文本是否变化,判断语种是否改变, 无变化则返回真""" if src_text.strip() == self.all_var[0].strip() and self.all_var[1].get( ) == self.button_1['text']: if self.all_var[2].get() == self.button_3['text']: return True else: return False def _button_translation(self): """翻译按钮""" sleep(0.1) src_text = self.text.get(0.0, END) # print(src_text) if not self._is_change(src_text): self._real_update(src_text) # self.all_var[0] = src_text def _button_menu(self, event): button = event.widget sleep(0.6) in_button = button.winfo_pointerxy() sleep(0.2) out_button = button.winfo_pointerxy() if in_button != out_button: # 在button中停留太短时间不展示菜单 return self.foc_button = button menu_3_geometry = button.winfo_geometry() # print(menu_3_geometry, '在里面') if self.top_1.state() == 'withdrawn' and self.top_2.state( ) == 'withdrawn': x3, y3 = self._position(menu_3_geometry, self.top_3) self._set_top_windows(self.top_3, x3, y3) # sleep(2000) # self.top_3.withdraw() # print('正常', self.top_1.state(), self.top_2.state()) def _button_menu_1(self): """按键菜单""" self.foc_button = self.button_1 menu_1_geometry = self.button_1.winfo_geometry() x1, y1 = self._position(menu_1_geometry) self._set_top_windows(self.top_1, x1, y1) # root x + button x # print(self.top_1.winfo_geometry()) def _button_menu_2(self): self.foc_button = self.button_3 menu_2_geometry = self.button_3.winfo_geometry() x1, y1 = self._position(menu_2_geometry) self._set_top_windows(self.top_2, x1, y1) # print(x1, y1) # root x + button x def _set_top_windows(self, top, x1, y1): # 设置窗口状态 if top is self.top_1: self.button_1.state(['!pressed']) elif top is self.top_2: self.button_3.state(['!pressed']) top.geometry('+%i+%i' % (x1, y1)) top.focus_force() top.deiconify() def _text_1_show(self, snap_string, x=0.0, y=END, style=tuple('GROOVE')): # 刷新输出框 self.text_out.configure(state=NORMAL) self.text_out.delete(x, y) self.text_out.grid(row=0, column=0, columnspan=4) self.text_out.insert(y, snap_string, style) self.text_out.configure(state=DISABLED) def _set_font(self, snap_string=' \n IN translation...\n'): # 字体设置 self._text_1_show(snap_string, x=3.5, y=3.5, style=('GROOVE', 'font')) def _lose_focus(self, event): # 表格失去焦点 if event.widget == self.top_1: self.top_1.withdraw() self.tree_1.state(['!pressed']) else: self.top_2.withdraw() self.tree_2.state(['!pressed']) def _position(self, widget_geometry, top_3=None): """计算语种表格位置""" menu_geometry = widget_geometry # 按扭geometry root_geometry, top_geometry = self.root.winfo_geometry( ), self.top_1.winfo_geometry() menu_position = [int(i) for i in split('[+x]', menu_geometry)] root_position, top_position = [int(i) for i in split('[+x]', root_geometry)], \ [int(i) for i in split('[+x]', top_geometry)] child_window_x = root_position[2] + menu_position[2] + 9 child_window_y = root_position[3] + menu_position[3] - top_position[ 1] + 31 if top_3: top_3_geometry = top_3.winfo_geometry() top_position = [int(i) for i in split('[+x]', top_3_geometry)] # print(top_position) child_window_y = root_position[3] + menu_position[ 3] - top_position[1] + 31 return child_window_x, child_window_y return child_window_x, child_window_y def _button_leave(self, e): x, y, widget_geometry = e.x, e.y, e.widget.winfo_geometry() widget_geometry = [int(i) for i in split('[+x]', widget_geometry)] if not 0 < x < widget_geometry[1] and not y < 0: if self.top_3.state() == 'withdraw': sleep(1) self.top_3.withdraw() # print(x, y, widget_geometry) def _tree_pressed(self, event): # self.top_3.withdraw() x, y, widget = event.x, event.y, event.widget item = widget.identify('item', 0, y) column = widget.identify('column', x, 0) tree_widget = widget.winfo_toplevel() item_values = widget.item(item)['values'] tree_widget.withdraw() if not len(item_values): # 点击到空白表格(行),返回 return text = item_values[int(column[1]) - 1] # 默认tkinter保留列头(#0),所以列数得减一 if not text: # 数据为空,返回 return # button_widget = tree_widget.winfo_toplevel() # print(tree_widget, item_values, text) self.foc_button.config(text=text) bbox = widget.bbox(item, column) self._reveal_selection(text, bbox, widget) def _reveal_selection(self, text, bbox, tree): x, y, width, height = bbox # print(bbox) if tree == self.tree_1: canvas_ = self.canvas_1 canvas_text = self.canvas_1_text elif tree == self.tree_2: canvas_ = self.canvas_2 canvas_text = self.canvas_2_text else: canvas_ = self.canvas_3 canvas_text = self.canvas_3_text self.font.measure(text) canvas_['background'] = 'SystemHighlight' canvas_.configure(width=width, height=height) canvas_.coords(canvas_text, width / 2 - 1, height / 2 - 1) # 居中显示 canvas_.itemconfigure(canvas_text, text=text) canvas_.place(in_=tree, x=x, y=y)
class Gui(Frame): #============================================================================== # Metodos Basicos #============================================================================== def __init__(self, parent=None): Frame.__init__(self, parent) # Atributos GUI self.parent = parent self.file_opt = self.flopt = {} w, h = self.parent.winfo_screenwidth(), self.parent.winfo_screenheight( ) self.largura = w - 20 self.altura = h - 20 # Atributos funcionais self.img = None self.imgOld = None self.arqImg = StringVar() self.arqImg.set('') self.formatos = {} self.formatos['gif'] = 'GIF' self.formatos['jpg'] = 'JPEG' self.formatos['jpeg'] = 'JPEG' self.formatos['png'] = 'PNG' self.formatos['bmp'] = 'BMP' self.formatos['tif'] = 'TIFF' self.formatos['tiff'] = 'TIFF' self.formatos['ppm'] = 'PPM' self.formatos['pbm'] = 'PPM' self.formatos['pgm'] = 'PPM' self.tipos = [('Imagens', ('*.jpg', '*.png', '*.gif', '*.bmp', '*.ppm', '*.pgm', '*.pbm')), ('JPEG', '*.jpg'), ('PNG', '*.png'), ('GIF', '*.gif'), ('BMP', '*.bmp'), ('PPM', '*.ppm'), ('PGM', '*.pgm'), ('PBM', '*.pbm'), ('Todos arquivos', '*')] # Cria/atualiza GUI self.createWidgets() self.update_idletasks() #============================================================================== # Metodos relacionados ao comportamento da GUI #============================================================================== def createWidgets(self): self.canvas = Canvas(self.parent, width=1366, height=768) self.scroll = Scrollbar(self.parent, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.scroll.set) self.scroll.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) # Configura barra de menus self.menubar = Menu(self.parent) self.parent.config(menu=self.menubar) # Menu arquivo e suas opcoes self.menuArquivo = Menu(self.menubar) self.menuArquivo.add_command(label='Abrir', underline=0, command=self.abrir) self.menuArquivo.add_separator() self.menuArquivo.add_command(label='Salvar', underline=0, command=self.salvar) self.menuArquivo.add_command(label='Salvar Como...', underline=0, command=self.salvarComo) self.menuArquivo.add_separator() self.menuArquivo.add_command(label='Fechar imagem(ns)', underline=0, command=self.fecharArquivo) self.menuArquivo.add_command(label="Sair", underline=3, command=self.onExit) self.menubar.add_cascade(label="Arquivo", underline=0, menu=self.menuArquivo) # Menu editar e suas opcoes self.menuEditar = Menu(self.menubar) self.menuEditar.add_command(label='Desfazer', underline=0, command=self.desfazer) self.menubar.add_cascade(label="Editar", underline=0, menu=self.menuEditar) # Menu Imagem e suas opcoes self.menuImagem = Menu(self.menubar) self.submenuConverte = Menu(self.menuImagem) self.submenuConverte.add_command(label='Colorido RGB', underline=0, command=lambda: self.converte('RGB')) self.submenuConverte.add_command(label='Colorido RGBA', underline=0, command=lambda: self.converte('RGBA')) self.submenuConverte.add_command(label='Escala de cinza', underline=0, command=lambda: self.converte('L')) self.submenuConverte.add_command(label='Binario', underline=0, command=lambda: self.converte('1')) self.menuImagem.add_command(label='Informacoes gerais', underline=0, command=self.info) self.menuImagem.add_separator() self.menuImagem.add_cascade(label='Converter', underline=0, menu=self.submenuConverte) self.menubar.add_cascade(label="Imagem", underline=0, menu=self.menuImagem) # Menu de operacoes sobre cores e suas opcoes self.menuCores = Menu(self.menubar) self.submenuCinza = Menu(self.menuCores) self.submenuCinza.add_command(label='Decomposicao de Maximo', underline=18, command=self.emConstrucao) self.submenuCinza.add_command(label='Decomposicao de Minimo', underline=18, command=self.emConstrucao) self.submenuCinza.add_command(label='Average', underline=0, command=lambda: self.mudaCor('average')) self.submenuCinza.add_command(label='Lightness', underline=0, command=self.emConstrucao) self.submenuCinza.add_command(label='Luminosity', underline=0, command=self.emConstrucao) self.submenuCinza.add_command(label='Componente R', underline=11, command=lambda: self.mudaCor('r')) self.submenuCinza.add_command(label='Componente G', underline=11, command=self.emConstrucao) self.submenuCinza.add_command(label='Componente B', underline=11, command=self.emConstrucao) self.submenuCinza.add_command(label='Quantidade arbitraria de tons', underline=0, command=self.emConstrucao) self.submenuHalftone = Menu(self.menuCores) self.submenuHalftone.add_command( label='Bayer 2x2', underline=6, command=lambda: self.halftoning('bayer2')) self.submenuHalftone.add_command(label='Bayer 5x5', underline=6, command=self.emConstrucao) self.submenuHalftone.add_command(label='Atkinson', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command(label='Sierra Lite', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command(label='Jarvis, Judice, and Ninke', underline=0, command=self.emConstrucao) self.submenuHalftone.add_command( label='Floyd-Steinberg', underline=0, command=lambda: self.halftoning('floyd')) self.menuCores.add_cascade(label='Tons de cinza', underline=0, menu=self.submenuCinza) self.menuCores.add_command(label='Inverter', underline=0, command=lambda: self.mudaCor('inv')) self.menuCores.add_command(label='Sepia', underline=0, command=self.emConstrucao) self.menuCores.add_separator() self.menuCores.add_command(label='Pseudo Binaria', underline=0, command=self.binaria) self.menuCores.add_cascade(label='Halftoning', underline=0, menu=self.submenuHalftone) self.menuCores.add_separator() self.menuCores.add_command(label='Cisalhamento de Cor', underline=0, command=self.emConstrucao) self.menuCores.add_command(label='Balanco de cores', underline=0, command=self.balancoCor) self.menuCores.add_command(label='Quantizacao de cores', underline=0, command=self.emConstrucao) self.menubar.add_cascade(label="Cores", underline=0, menu=self.menuCores) # Menu de operacoes topologicas e suas opcoes self.menuTopologia = Menu(self.menubar) self.menuTopologia.add_command(label='Rotular Componentes', underline=0, command=self.emConstrucao) self.menuTopologia.add_command(label='Transformada da Distancia', underline=0, command=self.emConstrucao) self.menuTopologia.add_command(label='Esqueletizacao', underline=0, command=self.emConstrucao) self.menubar.add_cascade(label="Topologia", underline=0, menu=self.menuTopologia) # Menu do trabalho e suas opcoes self.trabalho = Menu(self.menubar) self.trabalho.add_command(label='Tarefa 01', underline=20, command=self.abrir) # Grupo principal, onde serao atualizados os widgets self.grupoPrincipal = Frame(self.canvas, width=self.largura, height=self.altura, bd=1, padx=10, pady=10) self.grupoPrincipal.pack() #self.grupoPrincipal.grid_propagate(False) # Faz com que o Frame nao seja redimensionado com a mudanca dos widgets self.canvas.create_window((4, 20), window=self.grupoPrincipal, anchor="nw", tags="self.grupoPrincipal") self.grupoPrincipal.bind("<Configure>", self.OnFrameConfigure) def OnFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all")) def onExit(self): self.parent.destroy() def limpaTela(self): for widget in self.grupoPrincipal.winfo_children(): widget.destroy() def emConstrucao(self): tkm.showinfo(title="Em construcao", message="Recurso em Construcao...") def load_file(self, titulo, varFile, tipos): if os.path.isfile(varFile.get()): path = os.path.dirname(varFile.get()) self.flopt['initialdir'] = path else: self.flopt['initialdir'] = os.path.curdir self.flopt['filetypes'] = tipos arquivo = tkf.askopenfilename(title=titulo, **self.flopt) if arquivo: varFile.set(arquivo) def widgetFile(self, master, titulo, texto, varFile, tuplaFiletype): esteFrame = LabelFrame(master, text=titulo, padx=5, pady=5) j = 0 varFile.set("Nenhum arquivo informado") labelRotulo = Label(esteFrame, text=texto) labelRotulo.grid(row=j, column=0, sticky=cte.E) botao = Button( esteFrame, text="Procurar", command=lambda: self.load_file(texto, varFile, tuplaFiletype), width=10) botao.grid(row=j, column=1, pady=5, sticky=cte.W) j += 1 labelArq = Label(esteFrame, textvariable=varFile, bg='white') labelArq.grid(row=j, column=0, columnspan=2) return esteFrame def refreshImg(self): try: self.grupoPrincipal.photo = ImageTk.PhotoImage(self.img.img) if hasattr(self.grupoPrincipal, 'canvas'): self.grupoPrincipal.canvas.destroy() self.grupoPrincipal.canvas = Canvas(self.grupoPrincipal) self.grupoPrincipal.canvas.create_image( 0, 0, image=self.grupoPrincipal.photo, anchor=cte.NW) self.grupoPrincipal.canvas.config(bg='white', width=self.img.altura, height=self.img.largura) #self.grupoPrincipal.canvas.place(x=self.parent.winfo_screenwidth()/2, y=self.parent.winfo_screenheight()/2, anchor=cte.CENTER) self.grupoPrincipal.canvas.place(x=0, y=0, anchor=cte.NW) self.grupoPrincipal.update_idletasks() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao meno Arquivo #============================================================================== def abrir(self): try: self.limpaTela() self.load_file('Arquivos de Imagem', self.arqImg, self.tipos) self.img = Imagem(self.arqImg.get()) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def saveFile(self): try: nome, extensao = os.path.splitext(self.arqImg.get()) extensao = extensao.replace('.', '') self.img.salva(self.arqImg.get(), self.formatos[extensao.lower()]) tkm.showinfo( 'Sucesso', 'Arquivo %s salvo com sucesso' % os.path.basename(self.arqImg.get())) except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def salvar(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto para ser salvo') else: try: self.saveFile() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def salvarComo(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto para ser salvo') else: try: if os.path.isfile(self.arqImg.get()): path = os.path.dirname(self.arqImg.get()) self.flopt['initialdir'] = path else: self.flopt['initialdir'] = os.path.curdir self.flopt['filetypes'] = self.tipos nomeArq = tkf.asksaveasfilename(title='Salvar imagem como...', **self.flopt) if nomeArq: self.arqImg.set(nomeArq) self.saveFile() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def fecharArquivo(self): if not hasattr( self.grupoPrincipal, 'canvas') or self.grupoPrincipal.canvas.find_all() == (): tkm.showwarning('Aviso', 'Nao ha imagens abertas') else: try: self.img = self.imgOld = None self.grupoPrincipal.canvas.delete('all') self.grupoPrincipal.update_idletasks() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Editar #============================================================================== def desfazer(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') elif self.imgOld is None: tkm.showwarning('Aviso', 'Impossivel Desfazer') else: try: temp = self.img self.img = self.imgOld self.imgOld = temp self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Cores #============================================================================== def mudaCor(self, metodo): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img self.img = cor.mudaCor(self.imgOld, metodo) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def binaria(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img self.img = cor.binaria(self.imgOld) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def getFatoresBalanco(self): self.fatores = [float(self.escalaFatorR.get())] self.fatores.append(float(self.escalaFatorG.get())) self.fatores.append(float(self.escalaFatorB.get())) self.w.destroy() def formBalanco(self): self.fator = None self.fatores = None self.w = Toplevel(self) self.w.wm_title("Informar os fatores de ajuste") self.w.geometry("+%d+%d" % (self.winfo_rootx() + 50, self.winfo_rooty() + 50)) self.w.focus_set() i = 0 self.labelFatorR = Label(self.w, text='Ajuste em R', width=25) self.labelFatorR.grid(row=i, column=0) self.escalaFatorR = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorR.set(0.5) self.escalaFatorR.grid(row=i, column=1) i += 1 self.labelFatorG = Label(self.w, text='Ajuste em G', width=25) self.labelFatorG.grid(row=i, column=0) self.escalaFatorG = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorG.set(0.5) self.escalaFatorG.grid(row=i, column=1) i += 1 self.labelFatorB = Label(self.w, text='Ajuste em B', width=25) self.labelFatorB.grid(row=i, column=0) self.escalaFatorB = Scale(self.w, from_=0, to=2, resolution=0.05, length=350, orient=cte.HORIZONTAL) self.escalaFatorB.set(0.5) self.escalaFatorB.grid(row=i, column=1) i += 1 self.botaoFator = Button(self.w, text='Ok', command=self.getFatoresBalanco, width=10) self.botaoFator.grid(row=i, column=0, columnspan=2) self.w.grid() def balancoCor(self): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.formBalanco() self.wait_window(self.w) if self.fatores is not None: self.imgOld = self.img self.img = cor.balanco(self.imgOld, self.fatores[0], self.fatores[1], self.fatores[2]) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def halftoning(self, metodo='bayer2'): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img if metodo == 'bayer2': self.img = cor.bayer(self.imgOld) elif metodo == 'floyd': self.img = cor.floyd(self.imgOld) else: raise Exception('Metodo de halftoning desconhecido') self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) #============================================================================== # Metodos relacionados ao menu Imagem #============================================================================== def converte(self, modo='RGB'): if self.arqImg.get() == '' or self.img is None: tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: self.imgOld = self.img.copia() self.img.converte(modo) self.refreshImg() except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args)) def info(self): if self.arqImg.get() == '': tkm.showwarning('Aviso', 'Nao ha arquivo aberto') else: try: texto = 'Imagem %s, modo: %s (%d x %d pixels)' % ( self.img.img.format, self.img.img.mode, self.img.img.size[0], self.img.img.size[1]) tkm.showinfo('Aviso', texto) except Exception as e: tkm.showerror('Erro', 'O seguinte erro ocorreu: %s' % str(e.args))
class Relat: #Janela prncipal def __init__(self, parent, db): self.parent = parent self.db = db self.parent.title("Relat") self.parent.geometry("700x450") self.parent.protocol("WM_DELETE_WINDOW", self.fechar_janela_ctrl) main_frame = Frame(self.parent) main_frame.pack(fill=BOTH, expand=YES) # TOOLBAR toolbar = Frame(main_frame) toolbar.pack(side=TOP, fill=X) self.projeto_img = tk.PhotoImage(file="./imagens/projetos.png") self.lista_projetos_btn = ttk.Button(toolbar, image=self.projeto_img, command=self.lista_projetos) self.lista_projetos_btn.pack(side=LEFT, padx=2, pady=2) self.iniciar_img = tk.PhotoImage(file="./imagens/iniciar.png") self.iniciar_btn = ttk.Button(toolbar, image=self.iniciar_img, command=self.iniciar_ctrl) self.iniciar_btn.state( ['disabled']) # set the disabled flag, disabling the button self.iniciar_btn.pack(side=LEFT, pady=1) self.cancelar_img = tk.PhotoImage(file="./imagens/stop.png") self.cancelar_btn = ttk.Button(toolbar, image=self.cancelar_img, command=self.cancelar_ctrl) self.cancelar_btn.state( ['disabled']) # set the disabled flag, disabling the button # self.cancelar_btn.state(['!disabled']) self.cancelar_btn.pack(side=LEFT, pady=1) self.sair_img = tk.PhotoImage(file="./imagens/sair.png") self.sair_btn = ttk.Button(toolbar, image=self.sair_img, command=self.fechar_janela_ctrl) self.sair_btn.pack(side=LEFT, pady=1) status_bar = Frame(main_frame) status_bar.pack(side=BOTTOM, fill=X) self.text_status_bar = Label(status_bar, text="www.KlinikPython.Wordpress.Com", relief=SUNKEN, bd=1) self.text_status_bar.pack(side=LEFT, fill=X, expand=True) self.id_status_bar = Label(status_bar, text="") self.id_status_bar.pack(side=RIGHT) frame_central = ttk.Notebook(main_frame) grid_frame = Frame(frame_central, bd=10) grid_frame.pack(fill=BOTH, expand=YES, side=LEFT) self.dataCols = ('nome', 'ultima_atualizacao') self.relatorios_grid = ttk.Treeview(grid_frame, selectmode='browse', columns=self.dataCols) self.relatorios_grid.bind("<Double-1>", self.alterar_relatorio_click) self.relatorios_grid.bind("<Button-1>", self.habilita_btn_relat) scroll_y = ttk.Scrollbar(grid_frame, orient=VERTICAL, command=self.relatorios_grid.yview) scroll_x = ttk.Scrollbar(grid_frame, orient=HORIZONTAL, command=self.relatorios_grid.xview) self.relatorios_grid['yscroll'] = scroll_y.set self.relatorios_grid['xscroll'] = scroll_x.set scroll_y.configure(command=self.relatorios_grid.yview) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.configure(command=self.relatorios_grid.xview) scroll_x.pack(side=BOTTOM, fill=X) # setup column headings self.relatorios_grid['show'] = 'headings' self.relatorios_grid.heading('nome', text='Nome', anchor=W) self.relatorios_grid.column('nome', stretch=0, width=200) self.relatorios_grid.heading('ultima_atualizacao', text='Última Atualização', anchor=W) # self.projetos_grid.column('ultima_atualizacao', stretch=0, width=100) self.relatorios_grid.pack(fill=BOTH, side=LEFT, expand=True) self.relatorios_grid.bind("<Double-1>", self.alterar_relatorio_click) frame_central.add(grid_frame, text="Relatórios") frame_central.add(Frame(), text="Configurações") frame_central.pack(side=LEFT, fill=BOTH, expand=1) frame_botoes = Frame(main_frame, width=200, padx=20, pady=30) frame_botoes.pack(side=RIGHT, fill=Y) self.novo_relatorio_img = tk.PhotoImage(file="./imagens/incluir.png") self.novo_relatorio_btn = ttk.Button(frame_botoes, width=20, text="Incluir", image=self.novo_relatorio_img, compound=LEFT, command=self.novo_relatorio) self.novo_relatorio_btn.state(['disabled']) self.novo_relatorio_btn.pack(side=TOP, pady=2) self.alterar_relatorio_img = tk.PhotoImage( file="./imagens/alterar.png") self.alterar_relatorio_btn = ttk.Button( frame_botoes, width=20, text="Alterar", image=self.alterar_relatorio_img, compound=LEFT, command=self.alterar_relatorio) self.alterar_relatorio_btn.state(['disabled']) self.alterar_relatorio_btn.pack(side=TOP, pady=2) self.excluir_relatorio_img = tk.PhotoImage( file="./imagens/excluir.png") self.excluir_relatorio_btn = ttk.Button( frame_botoes, width=20, text="Excluir", image=self.excluir_relatorio_img, compound=LEFT, command=self.excluir_relatorio_ctrl) self.excluir_relatorio_btn.state(['disabled']) self.excluir_relatorio_btn.pack(side=TOP, pady=2) self.move_up_img = tk.PhotoImage(file="./imagens/up.png") self.move_up_btn = ttk.Button(frame_botoes, width=20, text="Mover para cima", image=self.move_up_img, compound=LEFT, command=self.move_up_ctrl) self.move_up_btn.state(['disabled']) self.move_up_btn.pack(side=TOP, pady=2) self.move_down_img = tk.PhotoImage(file="./imagens/down.png") self.move_down_btn = ttk.Button(frame_botoes, width=20, text="Mover para baixo", image=self.move_down_img, compound=LEFT, command=self.move_down_ctrl) self.move_down_btn.state(['disabled']) self.move_down_btn.pack(side=TOP, pady=2) menu_bar = tk.Menu(main_frame) projeto_menu = tk.Menu(menu_bar, tearoff=0) projeto_menu.add_command(label="Projetos", command=self.lista_projetos) projeto_menu.add_command(label="Fechar Projeto", command=self.fechar_projeto_ctrl) projeto_menu.add_separator() projeto_menu.add_command(label="Sair", command=self.fechar_janela_ctrl) menu_bar.add_cascade(label="Projetos", menu=projeto_menu) ajuda_menu = tk.Menu(menu_bar, tearoff=0) ajuda_menu.add_command(label="Ajuda", command=self.sobre_ctrl) ajuda_menu.add_command(label="Licença", command=self.sobre_ctrl) ajuda_menu.add_separator() ajuda_menu.add_command(label="Sobre", command=self.sobre_ctrl) menu_bar.add_cascade(label="Sobre", menu=ajuda_menu) self.parent.config(menu=menu_bar) def lista_projetos(self): self.projeto_janela = Toplevel(self.parent) self.projeto_janela.title("Projetos") self.projeto_janela.geometry("400x400") self.projeto_janela.protocol("WM_DELETE_WINDOW", self.fechar_projeto_janela_ctrl) self.projeto_janela.withdraw() self.projeto_janela.grid() self.projeto_janela.transient(self.parent) self.projeto_janela.grab_set() projeto_frame = Frame(self.projeto_janela) projeto_frame.pack(fill=BOTH, expand=True) fechar_proj_btn = ttk.Button(self.projeto_janela, text="Fechar", width=10, command=self.fechar_projeto_janela_ctrl) fechar_proj_btn.pack(side=RIGHT, padx=5, pady=5) self.excluir_proj_btn = ttk.Button(self.projeto_janela, text="Excluir", width=10, command=self.excluir_projeto_ctrl) self.excluir_proj_btn.pack(side=RIGHT, padx=5, pady=5) self.excluir_proj_btn.state(["disabled"]) self.abrir_proj_btn = ttk.Button(self.projeto_janela, text="Abrir", width=10, command=self.abrir_projeto_ctrl) self.abrir_proj_btn.pack(side=RIGHT) self.abrir_proj_btn.state(["disabled"]) self.alterar_proj_btn = ttk.Button(self.projeto_janela, text="Alterar", width=10, command=self.alterar_projeto) self.alterar_proj_btn.pack(side=RIGHT) self.alterar_proj_btn.state(["disabled"]) novo_proj_btn = ttk.Button(self.projeto_janela, text="Novo", width=10, command=self.novo_projeto) novo_proj_btn.pack(side=RIGHT, padx=5, pady=5) grid_frame = Frame(projeto_frame, bd=10) grid_frame.pack(fill=BOTH, expand=YES, side=LEFT) self.dataCols = ('nome', 'ultima_atualizacao') self.projetos_grid = ttk.Treeview(grid_frame, selectmode='browse', columns=self.dataCols) self.projetos_grid.bind("<Double-1>", self.abrir_projeto_click) self.projetos_grid.bind("<Button-1>", self.habilita_btn_proj) scroll_y = ttk.Scrollbar(grid_frame, orient=VERTICAL, command=self.projetos_grid.yview) scroll_x = ttk.Scrollbar(grid_frame, orient=HORIZONTAL, command=self.projetos_grid.xview) self.projetos_grid['yscroll'] = scroll_y.set self.projetos_grid['xscroll'] = scroll_x.set scroll_y.configure(command=self.projetos_grid.yview) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.configure(command=self.projetos_grid.xview) scroll_x.pack(side=BOTTOM, fill=X) # setup column headings self.projetos_grid['show'] = 'headings' self.projetos_grid.heading('nome', text='Nome', anchor=W) self.projetos_grid.column('nome', stretch=0, width=200) self.projetos_grid.heading('ultima_atualizacao', text='Última Atualização', anchor=W) # self.projetos_grid.column('ultima_atualizacao', stretch=0, width=100) self.projetos_grid.pack(fill=BOTH, side=LEFT, expand=True) dados = ProjetosDb(self.db).listar_projetos() for row in dados: self.projetos_grid.insert('', END, row[0], values=(row[1], row[9])) centro_(self.projeto_janela) self.projeto_janela.deiconify() self.parent.wait_window(self.projeto_janela) def novo_projeto(self): self.novo_projeto_janela = Toplevel(self.parent) self.novo_projeto_janela.resizable(0, 0) self.novo_projeto_janela.title("Novo Projeto") self.novo_projeto_janela.geometry("700x400") self.novo_projeto_janela.protocol("WM_DELETE_WINDOW", self.fechar_novo_projeto_ctrl) self.novo_projeto_janela.withdraw() self.novo_projeto_janela.grid() self.novo_projeto_janela.transient(self.parent) self.novo_projeto_janela.grab_set() projeto_frame = Frame(self.novo_projeto_janela) projeto_frame.pack(fill=BOTH, expand=True) cancelar_btn = ttk.Button(self.novo_projeto_janela, text="Cancelar", width=10, command=self.fechar_novo_projeto_ctrl) cancelar_btn.pack(side=RIGHT, padx=5, pady=5) ok_btn = ttk.Button(self.novo_projeto_janela, text="Salvar", width=10, command=self.incluir_projeto_ctrl) ok_btn.pack(side=RIGHT) info_frame = Frame(projeto_frame, bd=10) info_frame.pack(fill=BOTH, expand=YES, side=RIGHT) group_info = ttk.LabelFrame(info_frame, text="Informações", padding=(6, 6, 12, 12)) group_info.grid(row=0, column=0, sticky='nsew') ttk.Label(group_info, text='Nome', width=10).grid(row=0, column=0, sticky=W) self.nome = ttk.Entry(group_info, width=25) self.nome.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Descrição', width=10).grid(row=1, column=0, sticky=W) self.descricao = Text(group_info, height=4, width=19) self.descricao.grid(row=1, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Autor', width=10).grid(row=2, column=0, sticky=W) self.autor = ttk.Entry(group_info, width=25) self.autor.grid(row=2, column=1, sticky=W, pady=2) group_db = ttk.LabelFrame(info_frame, text="Acesso ao banco", padding=(6, 6, 12, 12)) group_db.grid(row=1, column=0, sticky=NSEW) ttk.Label(group_db, text='Tipo', width=10).grid(row=0, column=0, sticky=W) self.box_value = tk.StringVar() self.box = ttk.Combobox(group_db, textvariable=self.box_value, width=22) self.box['values'] = ('', 'Oracle', 'Mysql', 'PostgreSql') self.box.current(0) self.box.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Servidor', width=10).grid(row=1, column=0, sticky=W) self.servidor = ttk.Entry(group_db, width=25) self.servidor.grid(row=1, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Porta', width=10).grid(row=2, column=0, sticky=W) self.porta = ttk.Entry(group_db, width=15) self.porta.grid(row=2, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Banco', width=10).grid(row=3, column=0, sticky=W) self.senha = ttk.Entry(group_db, width=25) self.senha.grid(row=3, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Usuário', width=10).grid(row=4, column=0, sticky=W) self.usuario = ttk.Entry(group_db, width=25) self.usuario.grid(row=4, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Senha', width=10).grid(row=5, column=0, sticky=W) self.senha = ttk.Entry(group_db, show="*", width=25) self.senha.grid(row=5, column=1, sticky=W, pady=2) centro_(self.novo_projeto_janela) self.novo_projeto_janela.deiconify() self.parent.wait_window(self.novo_projeto_janela) def alterar_projeto(self): self.alterar_projeto_janela = Toplevel(self.parent) self.alterar_projeto_janela.resizable(0, 0) self.alterar_projeto_janela.title("Novo Projeto") self.alterar_projeto_janela.geometry("700x500") self.alterar_projeto_janela.protocol("WM_DELETE_WINDOW", self.fechar_alterar_projeto_ctrl) self.alterar_projeto_janela.withdraw() self.alterar_projeto_janela.grid() self.alterar_projeto_janela.transient(self.parent) self.alterar_projeto_janela.grab_set() projeto_frame = Frame(self.alterar_projeto_janela, relief=RAISED, borderwidth=1) projeto_frame.pack(fill=BOTH, expand=True) cancelar_btn = ttk.Button(self.alterar_projeto_janela, text="Cancelar", width=10, command=self.fechar_alterar_projeto_ctrl) cancelar_btn.pack(side=RIGHT, padx=5, pady=5) ok_btn = ttk.Button(self.alterar_projeto_janela, text="Salvar", width=10, command=self.salvar_projeto_ctrl) ok_btn.pack(side=RIGHT) info_frame = Frame(projeto_frame, bd=10) info_frame.pack(fill=BOTH, expand=YES, side=RIGHT) group_info = ttk.LabelFrame(info_frame, text="Informações", padding=(6, 6, 12, 12)) group_info.grid(row=0, column=0, sticky='nsew') ttk.Label(group_info, text='Nome', width=10).grid(row=0, column=0, sticky=W) self.nome = ttk.Entry(group_info, width=25) self.nome.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Descrição', width=10).grid(row=1, column=0, sticky=W) self.descricao = Text(group_info, height=4, width=19) self.descricao.grid(row=1, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Autor', width=10).grid(row=2, column=0, sticky=W) self.autor = Text(group_info, height=4, width=19) self.autor.grid(row=2, column=1, sticky=W, pady=2) group_db = ttk.LabelFrame(info_frame, text="Acesso ao banco", padding=(6, 6, 12, 12)) group_db.grid(row=1, column=0, sticky='nsew') ttk.Label(group_db, text='Tipo', width=10).grid(row=0, column=0, sticky=W) self.bancos_value = tk.StringVar() self.bancos = ttk.Combobox(group_db, textvariable=self.box_value, width=22) self.bancos['values'] = ('', 'Oracle', 'Mysql', 'PostgreSql') self.bancos.current(0) self.bancos.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Servidor', width=10).grid(row=1, column=0, sticky=W) self.servidor = ttk.Entry(group_db, width=25) self.servidor.grid(row=2, column=0, sticky=W, pady=2) ttk.Label(group_db, text='Porta', width=10).grid(row=1, column=0, sticky=W) self.porta = ttk.Entry(group_db, width=25) self.usuario.grid(row=2, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Banco', width=10).grid(row=3, column=0, sticky=W) self.senha = ttk.Entry(group_db, width=25) self.senha.grid(row=3, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Usuário', width=10).grid(row=4, column=0, sticky=W) self.usuario = ttk.Entry(group_db, width=25) self.usuario.grid(row=4, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Senha', width=10).grid(row=5, column=0, sticky=W) self.usuario = ttk.Entry(group_db, show="*", width=25) self.usuario.grid(row=5, column=1, sticky=W, pady=2) centro_(self.alterar_projeto_janela) self.alterar_projeto_janela.deiconify() self.parent.wait_window(self.projeto_janela) def salvar_projeto_ctrl(self): arr = [] arr.append(self.nome.get()) arr.append(self.descricao.get()) arr.append(self.autor.get()) arr.append(self.bancos.get()) arr.append(self.nome.get()) arr.append(self.usuario.get()) arr.append(self.senha.get()) retorno = ProjetosDb(self.db).incluir_projeto(arr) if retorno.isnumeric: self.projetos_grid.insert('', END, arr[0], values=(row[1], row[9])) self.fechar_projeto_janela_ctrl() def excluir_projeto_ctrl(self): if deleteBox("Excluir", "Deseja realmente excluir o projeto selecionado?"): item = self.projetos_grid.selection()[0] self.projetos_grid.delete(item) ProjetosDb(self.db).excluirProjeto(item) print("Projeto excluído: ", item) def fechar_janela_ctrl(self): self.parent.destroy() def fechar_projeto_ctrl(self): for child in self.relatorios_grid.get_children(): print(self.relatorios_grid.item(child)["values"]) #self.projetos_grid.delete(item) self.iniciar_btn.state(["disabled"]) self.cancelar_btn.state(["disabled"]) self.novo_relatorio_btn.state(["disabled"]) self.alterar_relatorio_btn.state(["disabled"]) self.excluir_relatorio_btn.state(["disabled"]) self.move_up_btn.state(["disabled"]) self.move_down_btn.state(["disabled"]) #Limpar a lista de relatórios self.relatorios_grid.delete(*self.relatorios_grid.get_children()) def fechar_projeto_janela_ctrl(self): self.projeto_janela.destroy() def fechar_novo_projeto_ctrl(self): self.novo_projeto_janela.destroy() def fechar_alterar_projeto_ctrl(self): self.alterar_projeto_janela.destroy() def iniciar_ctrl(self): self.lista_projetos_btn.state(["disabled"]) self.sair_btn.state(["disabled"]) self.novo_relatorio_btn.state(["disabled"]) self.alterar_relatorio_btn.state(["disabled"]) self.excluir_relatorio_btn.state(["disabled"]) self.move_up_btn.state(["disabled"]) self.move_down_btn.state(["disabled"]) self.iniciar_btn.state(["disabled"]) self.cancelar_btn.state(["!disabled"]) def cancelar_ctrl(self): self.lista_projetos_btn.state(["!disabled"]) self.sair_btn.state(["!disabled"]) self.novo_relatorio_btn.state(["!disabled"]) self.iniciar_btn.state(["!disabled"]) self.cancelar_btn.state(["disabled"]) def abrir_projeto_ctrl(self): projeto_id = self.projetos_grid.selection()[0] relatorios_lista = RelatoriosDb(self.db).listar_relatorios(projeto_id) #print(relatorios_lista) self.lista_relatorios_ctrl(relatorios_lista) self.fechar_projeto_janela_ctrl() self.habilita_btn_abrir_proj() def abrir_projeto_click(self, event): projeto_id = self.projetos_grid.selection()[0] relatorios_lista = RelatoriosDb(self.db).listar_relatorios(projeto_id) #print(relatorios_lista) self.lista_relatorios_ctrl(relatorios_lista) self.fechar_projeto_janela_ctrl() self.habilita_btn_abrir_proj() def habilita_btn_proj(self, event): self.alterar_proj_btn.state(["!disabled"]) self.abrir_proj_btn.state(["!disabled"]) self.excluir_proj_btn.state(["!disabled"]) def habilita_btn_abrir_proj(self): self.novo_relatorio_btn.state(["!disabled"]) self.iniciar_btn.state(["!disabled"]) def novo_relatorio(self): self.novo_relatorio_janela = Toplevel() self.novo_relatorio_janela.resizable(0, 0) self.novo_relatorio_janela.title("Novo Relatório") self.novo_relatorio_janela.geometry("500x300") self.novo_relatorio_janela.protocol("WM_DELETE_WINDOW", self.fechar_novo_relatorio_ctrl) self.novo_relatorio_janela.withdraw() self.novo_relatorio_janela.grid() self.novo_relatorio_janela.transient(self.parent) self.novo_relatorio_janela.grab_set() relatorio_frame = Frame(self.novo_relatorio_janela, relief=RAISED, borderwidth=1) relatorio_frame.pack(fill=BOTH, expand=True) self.relatorio_tab = ttk.Notebook(relatorio_frame) self.relatorio_tab.pack(fill=BOTH, expand=True) cancelar_btn = ttk.Button(self.novo_relatorio_janela, text="Cancelar", width=10, command=self.fechar_novo_relatorio_ctrl) cancelar_btn.pack(side=RIGHT, padx=5, pady=5) ok_btn = ttk.Button(self.novo_relatorio_janela, text="Incluir", width=10, command=self.salvar_relat_ctrl) ok_btn.pack(side=RIGHT) frame_informacaoes = ttk.Frame(self.relatorio_tab) frame_informacaoes.pack(side=BOTTOM, expand=YES) informacoes_bas = ttk.LabelFrame(frame_informacaoes) frame_informacaoes.pack(side=BOTTOM, expand=YES) # data Nomor ttk.Label(frame_informacaoes, text='Nomor Urut').grid(row=0, column=0, sticky=W) self.entNomor = ttk.Entry(frame_informacaoes) self.entNomor.grid(row=0, column=1) # data Nama ttk.Label(frame_informacaoes, text='Nama Lengkap').grid(row=1, column=0, sticky=W) self.entNama = ttk.Entry(frame_informacaoes) self.entNama.grid(row=1, column=1) # data Alamat ttk.Label(frame_informacaoes, text='Alamat').grid(row=2, column=0, sticky=W) self.entAlamat = ttk.Entry(frame_informacaoes) self.entAlamat.grid(row=2, column=1) # data NoTelp ttk.Label(frame_informacaoes, text='No. Telp').grid(row=3, column=0, sticky=W) self.entTelp = ttk.Entry(frame_informacaoes) self.entTelp.grid(row=3, column=1) # data Kelas ttk.Label(frame_informacaoes, text='Kelas').grid(row=4, column=0, sticky=W) self.entKelas = ttk.Entry(frame_informacaoes) self.entKelas.grid(row=4, column=1) f2 = ttk.Frame(self.relatorio_tab) # second page f3 = ttk.Frame(self.relatorio_tab) # second page self.relatorio_tab.add(frame_informacaoes, text='Informações') self.relatorio_tab.add(f2, text='Consulta') self.relatorio_tab.add(f3, text='Configuração') centro_(self.novo_relatorio_janela) self.novo_relatorio_janela.deiconify() self.parent.wait_window(self.novo_relatorio_janela) def alterar_relatorio(self): self.alterar_relatorio_janela = Toplevel() self.alterar_relatorio_janela.resizable(0, 0) self.alterar_relatorio_janela.title("Alterar Relatório") self.alterar_relatorio_janela.geometry("500x300") self.alterar_relatorio_janela.protocol( "WM_DELETE_WINDOW", self.fechar_alterar_relatorio_ctrl) self.alterar_relatorio_janela.withdraw() self.alterar_relatorio_janela.grid() self.alterar_relatorio_janela.transient(self.parent) self.alterar_relatorio_janela.grab_set() relatorio_frame = Frame(self.alterar_relatorio_janela, relief=RAISED, borderwidth=1) relatorio_frame.pack(fill=BOTH, expand=True) self.relatorio_tab = ttk.Notebook(relatorio_frame) self.relatorio_tab.pack(fill=BOTH, expand=True) cancelar_btn = ttk.Button(self.alterar_relatorio_janela, text="Cancelar", width=10, command=self.fechar_alterar_relatorio_ctrl) cancelar_btn.pack(side=RIGHT, padx=5, pady=5) ok_btn = ttk.Button(self.alterar_relatorio_janela, text="Incluir", width=10, command=self.salvar_relat_ctrl) ok_btn.pack(side=RIGHT) f1 = ttk.Frame(self.relatorio_tab ) # first page, which would get widgets gridded into it f1.pack(side=BOTTOM, expand=YES) f2 = ttk.Frame(self.relatorio_tab) # second page f3 = ttk.Frame(self.relatorio_tab) # second page self.relatorio_tab.add(f1, text='Informações') self.relatorio_tab.add(f2, text='Consulta') self.relatorio_tab.add(f3, text='Configuração') centro_(self.alterar_relatorio_janela) self.alterar_relatorio_janela.deiconify() self.parent.wait_window(self.alterar_relatorio_janela) def lista_relatorios_ctrl(self, relatorios): self.relatorios = relatorios for row in self.relatorios: self.relatorios_grid.insert("", END, row[0], values=(row[2], row[8])) def fechar_novo_relatorio_ctrl(self): self.novo_relatorio_janela.destroy() def fechar_alterar_relatorio_ctrl(self): self.alterar_relatorio_janela.destroy() def salvar_relat_ctrl(self): self.projeto_janela.destroy() def habilita_btn_relat(self, event): self.alterar_relatorio_btn.state(["!disabled"]) self.excluir_relatorio_btn.state(["!disabled"]) self.move_up_btn.state(["!disabled"]) self.move_down_btn.state(["!disabled"]) def novo_relatorio_ctrl(self): arr = [] arr.append(self.nome.get()) arr.append(self.descricao.get()) arr.append(self.autor.get()) arr.append(self.bancos.get()) arr.append(self.nome.get()) arr.append(self.usuario.get()) arr.append(self.senha.get()) retorno = ProjetosDb(self.db).incluir_projeto(arr) if retorno.isnumeric: self.projetos_grid.insert('', END, arr[0], values=(row[1], row[9])) self.fechar_novo_relatorio_ctrl() def alterar_relatorio_ctrl(self): item = self.relatorios_grid.selection()[0] print("you clicked on", self.relatorios_grid.item(item, "text")) def alterar_relatorio_click(self): item = self.relatorios_grid.selection()[0] print("you clicked on", self.relatorios_grid.item(item, "text")) def excluir_relatorio_ctrl(self, db): if deleteBox("Excluir", "Deseja realmente excluir o relatório selecionado?"): relatorio_id = self.relatorios_grid.selection() self.relatorios_grid.delete(relatorio_id) RelatoriosDb(self.db).excluirRelatorio(relatorio_id) print("Projeto excluído: ", relatorio_id) def move_up_ctrl(self): leaves = self.relatorios_grid.selection() print("item: ", leaves) for i in leaves: self.relatorios_grid.move(i, self.relatorios_grid.parent(i), self.relatorios_grid.index(i) - 1) def move_down_ctrl(self): leaves = self.relatorios_grid.selection() for i in leaves: self.relatorios_grid.move(i, self.relatorios_grid.parent(i), self.relatorios_grid.index(i) + 1) def sobre_ctrl(self): app = Sobre(self.parent)
class Relat: #Guarda o ID do projeto aberto projeto_aberto = 0 #Janela prncipal def __init__(self, parent, db): self.parent = parent self.db = db self.parent.title("Relat") self.parent.geometry("700x450") self.parent.protocol("WM_DELETE_WINDOW", self.fechar_janela_ctrl) main_frame = Frame(self.parent) main_frame.pack(fill=BOTH, expand=YES) # TOOLBAR toolbar = Frame(main_frame) toolbar.pack(side=TOP, fill=X) self.projeto_img = tk.PhotoImage(file="./imagens/projetos.png") self.lista_projetos_btn = ttk.Button(toolbar, image=self.projeto_img, command=self.lista_projetos) self.lista_projetos_btn.pack(side=LEFT, padx=2, pady=2) self.iniciar_img = tk.PhotoImage(file="./imagens/iniciar.png") self.iniciar_btn = ttk.Button(toolbar, image=self.iniciar_img, command=self.iniciar_ctrl) self.iniciar_btn.state(['disabled']) # set the disabled flag, disabling the button self.iniciar_btn.pack(side=LEFT, pady=1) self.cancelar_img = tk.PhotoImage(file="./imagens/stop.png") self.cancelar_btn = ttk.Button(toolbar, image=self.cancelar_img, command=self.cancelar_ctrl) self.cancelar_btn.state(['disabled']) # set the disabled flag, disabling the button # self.cancelar_btn.state(['!disabled']) self.cancelar_btn.pack(side=LEFT, pady=1) self.sair_img = tk.PhotoImage(file="./imagens/sair.png") self.sair_btn = ttk.Button(toolbar, image=self.sair_img, command=self.fechar_janela_ctrl) self.sair_btn.pack(side=LEFT, pady=1) status_bar = Frame(main_frame) status_bar.pack(side=BOTTOM, fill=X) self.text_status_bar = Label(status_bar, text="www.KlinikPython.Wordpress.Com", relief=SUNKEN, bd=1) self.text_status_bar.pack(side=LEFT, fill=X, expand=True) frame_central = ttk.Notebook(main_frame) grid_frame = Frame(frame_central, bd=10) grid_frame.pack(fill=BOTH, expand=YES, side=LEFT) self.dataCols = ('nome', 'ultima_atualizacao') self.relatorios_grid = ttk.Treeview(grid_frame, selectmode='browse', columns=self.dataCols) self.relatorios_grid.bind("<Double-1>", self.alterar_relatorio_click) #self.relatorios_grid.bind("<Button-1>", self.habilita_btn_relat) scroll_y = ttk.Scrollbar(grid_frame, orient=VERTICAL, command=self.relatorios_grid.yview) scroll_x = ttk.Scrollbar(grid_frame, orient=HORIZONTAL, command=self.relatorios_grid.xview) self.relatorios_grid['yscroll'] = scroll_y.set self.relatorios_grid['xscroll'] = scroll_x.set scroll_y.configure(command=self.relatorios_grid.yview) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.configure(command=self.relatorios_grid.xview) scroll_x.pack(side=BOTTOM, fill=X) # setup column headings self.relatorios_grid['show'] = 'headings' self.relatorios_grid.heading('nome', text='Nome', anchor=W) self.relatorios_grid.column('nome', stretch=0, width=200) self.relatorios_grid.heading('ultima_atualizacao', text='Última Atualização', anchor=W) # self.projetos_grid.column('ultima_atualizacao', stretch=0, width=100) self.relatorios_grid.pack(fill=BOTH, side=LEFT, expand=True) self.relatorios_grid.bind("<Double-1>", self.alterar_relatorio_click) frame_central.add(grid_frame, text="Relatórios") frame_central.add(Frame(), text="Configurações") frame_central.pack(side=LEFT, fill=BOTH, expand=1) frame_botoes = Frame(main_frame, width=200, padx=20, pady=30) frame_botoes.pack(side=RIGHT, fill=Y) self.novo_relatorio_img = tk.PhotoImage(file="./imagens/incluir.png") self.novo_relatorio_btn = ttk.Button(frame_botoes, width=20, text="Incluir", image=self.novo_relatorio_img, compound=LEFT, command=lambda: self.form_relatorio('novo')) self.novo_relatorio_btn.state(['disabled']) self.novo_relatorio_btn.pack(side=TOP, pady=2) self.alterar_relatorio_img = tk.PhotoImage(file="./imagens/alterar.png") self.alterar_relatorio_btn = ttk.Button(frame_botoes, width=20, text="Alterar", image=self.alterar_relatorio_img, compound=LEFT, command=lambda: self.form_relatorio('alterar')) self.alterar_relatorio_btn.state(['disabled']) self.alterar_relatorio_btn.pack(side=TOP, pady=2) self.excluir_relatorio_img = tk.PhotoImage(file="./imagens/excluir.png") self.excluir_relatorio_btn = ttk.Button(frame_botoes, width=20, text="Excluir", image=self.excluir_relatorio_img, compound=LEFT, command=self.excluir_relatorio_ctrl) self.excluir_relatorio_btn.state(['disabled']) self.excluir_relatorio_btn.pack(side=TOP, pady=2) self.move_up_img = tk.PhotoImage(file="./imagens/up.png") self.move_up_btn = ttk.Button(frame_botoes, width=20, text="Mover para cima", image=self.move_up_img, compound=LEFT, command=self.move_up_ctrl) self.move_up_btn.state(['disabled']) self.move_up_btn.pack(side=TOP, pady=2) self.move_down_img = tk.PhotoImage(file="./imagens/down.png") self.move_down_btn = ttk.Button(frame_botoes, width=20, text="Mover para baixo", image=self.move_down_img, compound=LEFT, command=self.move_down_ctrl) self.move_down_btn.state(['disabled']) self.move_down_btn.pack(side=TOP, pady=2) menu_bar = tk.Menu(main_frame) projeto_menu = tk.Menu(menu_bar, tearoff=0) projeto_menu.add_command(label="Projetos", command=self.lista_projetos) projeto_menu.add_command(label="Fechar Projeto", command=self.fechar_projeto_ctrl) projeto_menu.add_separator() projeto_menu.add_command(label="Sair", command=self.fechar_janela_ctrl) menu_bar.add_cascade(label="Projetos", menu=projeto_menu) ajuda_menu = tk.Menu(menu_bar, tearoff=0) ajuda_menu.add_command(label="Ajuda", command=self.sobre_ctrl) ajuda_menu.add_command(label="Licença", command=self.sobre_ctrl) ajuda_menu.add_separator() ajuda_menu.add_command(label="Sobre", command=self.sobre_ctrl) menu_bar.add_cascade(label="Sobre", menu=ajuda_menu) self.parent.config(menu=menu_bar) def lista_projetos(self): self.projeto_janela = Toplevel(self.parent) self.projeto_janela.title("Projetos") self.projeto_janela.geometry("400x400") self.projeto_janela.protocol("WM_DELETE_WINDOW", self.fechar_projeto_janela_ctrl) self.projeto_janela.withdraw() self.projeto_janela.grid() self.projeto_janela.transient(self.parent) self.projeto_janela.grab_set() projeto_frame = Frame(self.projeto_janela) projeto_frame.pack(fill=BOTH, expand=True) fechar_proj_btn = ttk.Button(self.projeto_janela, text="Fechar", width=10, command=self.fechar_projeto_janela_ctrl) fechar_proj_btn.pack(side=RIGHT, padx=5, pady=5) self.excluir_proj_btn = ttk.Button(self.projeto_janela, text="Excluir", width=10, command=self.excluir_projeto_ctrl) self.excluir_proj_btn.pack(side=RIGHT, padx=5, pady=5) self.excluir_proj_btn.state(["disabled"]) self.abrir_proj_btn = ttk.Button(self.projeto_janela, text="Abrir", width=10, command=self.abrir_projeto_ctrl) self.abrir_proj_btn.pack(side=RIGHT) self.abrir_proj_btn.state(["disabled"]) self.alterar_proj_btn = ttk.Button(self.projeto_janela, text="Alterar", width=10, command=lambda: self.form_projeto('alterar')) self.alterar_proj_btn.pack(side=RIGHT) self.alterar_proj_btn.state(["disabled"]) novo_proj_btn = ttk.Button(self.projeto_janela, text="Novo", width=10, command=lambda: self.form_projeto('novo')) novo_proj_btn.pack(side=RIGHT, padx=5, pady=5) grid_frame = Frame(projeto_frame, bd=10) grid_frame.pack(fill=BOTH, expand=YES, side=LEFT) self.dataCols = ('nome', 'ultima_atualizacao') self.projetos_grid = ttk.Treeview(grid_frame, selectmode='browse', columns=self.dataCols) self.projetos_grid.bind("<Double-1>", self.abrir_projeto_click) self.projetos_grid.bind("<Button-1>", self.habilita_btn_proj) scroll_y = ttk.Scrollbar(grid_frame, orient=VERTICAL, command=self.projetos_grid.yview) scroll_x = ttk.Scrollbar(grid_frame, orient=HORIZONTAL, command=self.projetos_grid.xview) self.projetos_grid['yscroll'] = scroll_y.set self.projetos_grid['xscroll'] = scroll_x.set scroll_y.configure(command=self.projetos_grid.yview) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.configure(command=self.projetos_grid.xview) scroll_x.pack(side=BOTTOM, fill=X) # setup column headings self.projetos_grid['show'] = 'headings' self.projetos_grid.heading('nome', text='Nome', anchor=W) self.projetos_grid.column('nome', stretch=0, width=200) self.projetos_grid.heading('ultima_atualizacao', text='Última Atualização', anchor=W) # self.projetos_grid.column('ultima_atualizacao', stretch=0, width=100) self.projetos_grid.pack(fill=BOTH, side=LEFT, expand=True) centro_(self.projeto_janela) self.lista_projetos_ctrl() self.projeto_janela.deiconify() self.parent.wait_window(self.projeto_janela) def lista_projetos_ctrl(self): self.projetos_grid.delete(*self.projetos_grid.get_children()) dados = ProjetosDb(self.db).listar_projetos() for row in dados: formato = '{%d/%m/%Y %H:%M:%S}' #datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") self.projetos_grid.insert('', END, row[0], values=(row[1], row[12])) def form_projeto(self, acao): self.form_projeto_janela = Toplevel(self.parent) self.form_projeto_janela.resizable(0, 0) if acao == 'novo': self.form_projeto_janela.title("Novo Projeto") else: self.form_projeto_janela.title("Alterar Projeto") self.form_projeto_janela.geometry("700x400") self.form_projeto_janela.protocol("WM_DELETE_WINDOW", self.fechar_form_projeto_ctrl) self.form_projeto_janela.withdraw() self.form_projeto_janela.grid() self.form_projeto_janela.transient(self.parent) self.form_projeto_janela.grab_set() projeto_frame = Frame(self.form_projeto_janela) projeto_frame.pack(fill=BOTH, expand=True) cancelar_btn = ttk.Button(self.form_projeto_janela, text="Cancelar", width=10, command=self.fechar_form_projeto_ctrl) cancelar_btn.pack(side=RIGHT, padx=5, pady=5) salvar_btn = ttk.Button(self.form_projeto_janela, text="Salvar", width=10, command=lambda: self.salvar_projeto_ctrl(acao)) salvar_btn.pack(side=RIGHT) info_frame = Frame(projeto_frame, bd=10) info_frame.pack(fill=BOTH, expand=YES, side=RIGHT) group_info = ttk.LabelFrame(info_frame, text="Informações", padding=(6, 6, 12, 12)) group_info.grid(row=0, column=0, sticky='nsew') ttk.Label(group_info, text='Nome', width=10).grid(row=0, column=0, sticky=W) self.nome = ttk.Entry(group_info, width=25) self.nome.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Descrição', width=10).grid(row=1, column=0, sticky=W) self.descricao = Text(group_info, height=4, width=25) self.descricao.configure(font=font.Font(font=self.nome['font'])) self.descricao.grid(row=1, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Autor', width=10).grid(row=2, column=0, sticky=W) self.autor = ttk.Entry(group_info, width=25) self.autor.grid(row=2, column=1, sticky=W, pady=2) group_db = ttk.LabelFrame(info_frame, text="Acesso ao banco", padding=(6, 6, 12, 12)) group_db.grid(row=1, column=0, sticky=NSEW) ttk.Label(group_db, text='Tipo', width=10).grid(row=0, column=0, sticky=W) self.bd_tipo_value = tk.StringVar() self.bd_tipo = ttk.Combobox(group_db, textvariable=self.bd_tipo_value, state="readonly", width=22) self.bd_tipo['values'] = ('', 'Oracle', 'Mysql', 'PostgreSql') self.bd_tipo.current(0) self.bd_tipo.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Servidor', width=10).grid(row=1, column=0, sticky=W) self.bd_servidor = ttk.Entry(group_db, width=25) self.bd_servidor.grid(row=1, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Porta', width=10).grid(row=2, column=0, sticky=W) self.bd_porta = ttk.Entry(group_db, width=15) self.bd_porta.grid(row=2, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Banco', width=10).grid(row=3, column=0, sticky=W) self.bd_banco = ttk.Entry(group_db, width=25) self.bd_banco.grid(row=3, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Usuário', width=10).grid(row=4, column=0, sticky=W) self.bd_usuario = ttk.Entry(group_db, width=25) self.bd_usuario.grid(row=4, column=1, sticky=W, pady=2) ttk.Label(group_db, text='Senha', width=10).grid(row=5, column=0, sticky=W) self.bd_senha = ttk.Entry(group_db, show="*", width=25) self.bd_senha.grid(row=5, column=1, sticky=W, pady=2) centro_(self.form_projeto_janela) if acao == 'alterar': self.alterar_projeto_ctrl() self.form_projeto_janela.deiconify() self.parent.wait_window(self.form_projeto_janela) def alterar_projeto_ctrl(self): projeto_id = self.projetos_grid.selection()[0] projeto = ProjetosDb(self.db).localizar_projeto(projeto_id) self.nome.insert(0, projeto[1]) self.descricao.insert(END, projeto[2]) self.autor.insert(0, projeto[3]) self.bd_tipo.current(projeto[4]) self.bd_servidor.insert(0, projeto[5]) self.bd_porta.insert(0, projeto[6]) self.bd_banco.insert(0, projeto[7]) self.bd_usuario.insert(0, projeto[9]) self.bd_senha.insert(0, projeto[10]) def salvar_projeto_ctrl(self, acao): arr = [] arr.append(self.nome.get()) arr.append(self.descricao.get("1.0", END)) arr.append(self.autor.get()) bd_tipo = self.bd_tipo.current() arr.append(bd_tipo) arr.append(self.bd_servidor.get()) arr.append(self.bd_porta.get()) arr.append(self.bd_banco.get()) # if (bd_tipo == 1) # conexao = oracle+cx_oracle://user:pass@host:port/dbname arr.append(self.bd_usuario.get()) arr.append(self.bd_senha.get()) arr.append("conexao") #Novo Projeto if acao == 'novo': #data de criação arr.append(datetime.now().isoformat(" ")) retorno = ProjetosDb(self.db).novo_projeto(arr) # if retorno.isnumeric: # self.projetos_grid.insert('', END, arr[0], values=(row[1], row[9])) self.fechar_form_projeto_ctrl() self.fechar_projeto_janela_ctrl() self.habilita_btn_abrir_proj() #Alterar projeto else: projeto_id = self.projetos_grid.selection()[0] # id do projeto arr.append(projeto_id) retorno = ProjetosDb(self.db).alterar_projeto(arr) # if retorno.isnumeric: # self.projetos_grid.insert('', END, arr[0], values=(row[1], row[9])) self.lista_projetos_ctrl() self.fechar_form_projeto_ctrl() def excluir_projeto_ctrl(self): if deleteBox("Excluir", "Deseja realmente excluir o projeto selecionado?"): item = self.projetos_grid.selection()[0] self.projetos_grid.delete(item) ProjetosDb(self.db).excluirProjeto(item) print("Projeto excluído: ", item) def indica_porta_bd(self, event): current = self.db_tipo.current() if current != -1: if current == 'Oracle': self.porta def fechar_janela_ctrl(self): self.parent.destroy() def fechar_projeto_ctrl(self): for child in self.relatorios_grid.get_children(): print(self.relatorios_grid.item(child)["values"]) #self.projetos_grid.delete(item) self.iniciar_btn.state(["disabled"]) self.cancelar_btn.state(["disabled"]) self.novo_relatorio_btn.state(["disabled"]) self.alterar_relatorio_btn.state(["disabled"]) self.excluir_relatorio_btn.state(["disabled"]) self.move_up_btn.state(["disabled"]) self.move_down_btn.state(["disabled"]) #Limpar a lista de relatórios self.relatorios_grid.delete(*self.relatorios_grid.get_children()) def fechar_projeto_janela_ctrl(self): self.projeto_janela.destroy() def fechar_form_projeto_ctrl(self): self.form_projeto_janela.destroy() def abrir_projeto_ctrl(self): projeto_id = self.projetos_grid.selection()[0] self.projeto_aberto = projeto_id relatorios_lista = RelatoriosDb(self.db).listar_relatorios(projeto_id) #print(relatorios_lista) self.lista_relatorios_ctrl(relatorios_lista) self.fechar_projeto_janela_ctrl() self.habilita_btn_abrir_proj() def abrir_projeto_click(self, event): projeto_id = self.projetos_grid.selection()[0] relatorios_lista = RelatoriosDb(self.db).listar_relatorios(projeto_id) #print(relatorios_lista) self.lista_relatorios_ctrl(relatorios_lista) self.fechar_projeto_janela_ctrl() self.habilita_btn_abrir_proj() def habilita_btn_proj(self, event): self.alterar_proj_btn.state(["!disabled"]) self.abrir_proj_btn.state(["!disabled"]) self.excluir_proj_btn.state(["!disabled"]) def habilita_btn_abrir_proj(self): self.novo_relatorio_btn.state(["!disabled"]) self.iniciar_btn.state(["!disabled"]) def iniciar_ctrl(self): self.lista_projetos_btn.state(["disabled"]) self.sair_btn.state(["disabled"]) self.novo_relatorio_btn.state(["disabled"]) self.alterar_relatorio_btn.state(["disabled"]) self.excluir_relatorio_btn.state(["disabled"]) self.move_up_btn.state(["disabled"]) self.move_down_btn.state(["disabled"]) self.iniciar_btn.state(["disabled"]) self.cancelar_btn.state(["!disabled"]) def cancelar_ctrl(self): self.lista_projetos_btn.state(["!disabled"]) self.sair_btn.state(["!disabled"]) self.novo_relatorio_btn.state(["!disabled"]) self.iniciar_btn.state(["!disabled"]) self.cancelar_btn.state(["disabled"]) def form_relatorio(self, acao): print('Projeto aberto:', self.projeto_aberto) self.form_relatorio_janela = Toplevel() self.form_relatorio_janela.resizable(0, 0) if acao == 'incluir': self.form_relatorio_janela.title("Novo Relatório") else: self.form_relatorio_janela.title("Alterar Relatório") self.form_relatorio_janela.geometry("500x300") self.form_relatorio_janela.protocol("WM_DELETE_WINDOW", self.fechar_form_relatorio_ctrl) self.form_relatorio_janela.withdraw() self.form_relatorio_janela.grid() self.form_relatorio_janela.transient(self.parent) self.form_relatorio_janela.grab_set() relatorio_frame = Frame(self.form_relatorio_janela, relief=RAISED, borderwidth=1) relatorio_frame.pack(fill=BOTH, expand=True) relatorio_tab = ttk.Notebook(relatorio_frame) relatorio_tab.pack(fill=BOTH, expand=True) cancelar_btn = ttk.Button(self.form_relatorio_janela, text="Cancelar", width=10, command=self.fechar_form_relatorio_ctrl) cancelar_btn.pack(side=RIGHT, padx=5, pady=5) ok_btn = ttk.Button(self.form_relatorio_janela, text="Incluir", width=10, command=self.alterar_relatorio_ctrl) ok_btn.pack(side=RIGHT) info_frame = Frame(relatorio_tab, bd=10) info_frame.pack(fill=BOTH, expand=YES, side=RIGHT) group_info = ttk.LabelFrame(info_frame, text="Informações", padding=(6, 6, 12, 12)) group_info.grid(row=0, column=0, sticky='nsew') ttk.Label(group_info, text='Nome', width=10).grid(row=0, column=0, sticky=W) self.nome_relatorio = ttk.Entry(group_info, width=25) self.nome_relatorio.grid(row=0, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Descrição', width=10).grid(row=1, column=0, sticky=W) self.descricao_relatorio = Text(group_info, height=4, width=25) self.descricao_relatorio.configure(font=font.Font(font=self.nome_relatorio['font'])) self.descricao_relatorio.grid(row=1, column=1, sticky=W, pady=2) ttk.Label(group_info, text='Autor', width=10).grid(row=2, column=0, sticky=W) self.autor_relatorio = ttk.Entry(group_info, width=25) self.autor_relatorio.grid(row=2, column=1, sticky=W, pady=2) consulta_frame = ttk.Frame(relatorio_tab) sql_frame = ttk.LabelFrame(consulta_frame, text="Sql", padding=(6, 6, 12, 12)) sql_frame.grid(row=0, column=0, sticky=NSEW) self.consulta = Text(sql_frame, height=4, width=25) self.consulta.configure(font=font.Font(font=self.nome_relatorio['font'])) self.consulta.grid(row=0, column=0, sticky=W, pady=2) colunas_frame = ttk.LabelFrame(consulta_frame, text="Colunas", padding=(6, 6, 12, 12)) colunas_frame.grid(row=0, column=0, sticky=NSEW) self.dataCols = ('nome', 'complemento') self.colunas_grid = ttk.Treeview(colunas_frame, selectmode='browse', columns=self.dataCols) self.colunas_grid.bind("<Double-1>", self.abrir_projeto_click) self.colunas_grid.bind("<Button-1>", self.habilita_btn_proj) scroll_y = ttk.Scrollbar(colunas_frame, orient=VERTICAL, command=self.colunas_grid.yview) scroll_x = ttk.Scrollbar(colunas_frame, orient=HORIZONTAL, command=self.colunas_grid.xview) self.colunas_grid['yscroll'] = scroll_y.set self.colunas_grid['xscroll'] = scroll_x.set scroll_y.configure(command=self.colunas_grid.yview) scroll_y.pack(side=RIGHT, fill=Y) scroll_x.configure(command=self.colunas_grid.xview) scroll_x.pack(side=BOTTOM, fill=X) # setup column headings self.colunas_grid['show'] = 'headings' self.colunas_grid.heading('nome', text='Nome', anchor=W) self.colunas_grid.column('nome', stretch=0, width=200) self.colunas_grid.heading('complemento', text='Última Atualização', anchor=W) self.colunas_grid.pack(fill=BOTH, side=LEFT, expand=True) frame_botoes = Frame(relatorio_tab, width=200, padx=20, pady=30) frame_botoes.pack(side=RIGHT, fill=Y) self.novo_relatorio_img = tk.PhotoImage(file="./imagens/incluir.png") self.novo_relatorio_btn = ttk.Button(frame_botoes, width=20, text="Incluir", image=self.novo_relatorio_img, compound=LEFT, command=lambda: self.form_relatorio('novo')) self.novo_relatorio_btn.state(['disabled']) self.novo_relatorio_btn.pack(side=TOP, pady=2) self.alterar_relatorio_img = tk.PhotoImage(file="./imagens/alterar.png") self.alterar_relatorio_btn = ttk.Button(frame_botoes, width=20, text="Alterar", image=self.alterar_relatorio_img, compound=LEFT, command=lambda: self.form_relatorio('alterar')) self.alterar_relatorio_btn.state(['disabled']) self.alterar_relatorio_btn.pack(side=TOP, pady=2) f3 = ttk.Frame(relatorio_tab) # second page relatorio_tab.add(info_frame, text='Informações') relatorio_tab.add(consulta_frame, text='Consulta') relatorio_tab.add(f3, text='Configuração') centro_(self.form_relatorio_janela) self.form_relatorio_janela.deiconify() self.parent.wait_window(self.form_relatorio_janela) def alterar_relatorio_ctrl(self): relatorio_id = self.relatorios_grid.selection()[0] relatorio = RelatoriosDb(self.db).localizar_relatorio(relatorio_id) self.nome.insert(0, projeto[1]) self.descricao.insert(END, projeto[2]) self.autor.insert(0, projeto[3]) self.bd_tipo.current(projeto[4]) self.bd_servidor.insert(0, projeto[5]) self.bd_porta.insert(0, projeto[6]) self.bd_banco.insert(0, projeto[7]) self.bd_usuario.insert(0, projeto[9]) self.bd_senha.insert(0, projeto[10]) def salvar_relatorio_ctrl(self, acao): arr = [] arr.append(self.nome.get()) arr.append(self.descricao.get("1.0", END)) arr.append(self.autor.get()) tipo_operacao = self.tipo_operacao.current() arr.append(bd_tipo) arr.append(self.bd_servidor.get()) arr.append(self.bd_porta.get()) arr.append(self.bd_banco.get()) arr.append(self.bd_usuario.get()) arr.append(self.bd_senha.get()) #Novo Relatorio if acao == 'novo': #data de criação arr.append(datetime.now().isoformat(" ")) retorno = RelatoriosDb(self.db).novo_relatorio(arr) # if retorno.isnumeric: # self.projetos_grid.insert('', END, arr[0], values=(row[1], row[9])) self.fechar_form_relatorio_ctrl() #Alterar relatorio else: relatorio_id = self.relatorios_grid.selection()[0] # id do projeto arr.append(relatorio_id) retorno = RelatoriosDb(self.db).alterar_relatorio(arr) # if retorno.isnumeric: # self.projetos_grid.insert('', END, arr[0], values=(row[1], row[9])) self.fechar_form_relatorio_ctrl() def lista_relatorios_ctrl(self, relatorios): self.relatorios = relatorios for row in self.relatorios: self.relatorios_grid.insert("", END, row[0], values=(row[2], row[8])) def fechar_form_relatorio_ctrl(self): self.form_relatorio_janela.destroy() def habilita_btn_relat(self, event): self.alterar_relatorio_btn.state(["!disabled"]) self.excluir_relatorio_btn.state(["!disabled"]) self.move_up_btn.state(["!disabled"]) self.move_down_btn.state(["!disabled"]) def alterar_relatorio_click(self, event): self.form_relatorio('alterar') def excluir_relatorio_ctrl(self, db): if deleteBox("Excluir", "Deseja realmente excluir o relatório selecionado?"): relatorio_id = self.relatorios_grid.selection() self.relatorios_grid.delete(relatorio_id) RelatoriosDb(self.db).excluir_relatorio(relatorio_id) print("Relatório excluído: ", relatorio_id) def move_up_ctrl(self): relatorio = self.relatorios_grid.selection() print("item: ", relatorio) for i in relatorio: self.relatorios_grid.move(i, self.relatorios_grid.parent(i), self.relatorios_grid.index(i) - 1) def move_down_ctrl(self): leaves = self.relatorios_grid.selection() for i in leaves: self.relatorios_grid.move(i, self.relatorios_grid.parent(i), self.relatorios_grid.index(i) + 1) def sobre_ctrl(self): app = Sobre(self.parent)
class Application(Frame): className = [] prob = [] #image_path_temporary = "D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images" def __init__(self, master=None): Frame.__init__(self, master) self.window_init() self.grid() def window_init(self): self.master.title('Eagle') screenwidth = self.winfo_screenwidth() screenheight = self.winfo_screenheight( ) # 设置界面宽度为530,高度为365像素,并且基于屏幕居中 width = 500 height = 400 size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) self.master.geometry(size) self.grid() self.create_widgets_initial() def create_widgets_initial(self): #self.frame = Frame(self) #self.frame.grid() self.tabControl = ttk.Notebook(self) self.tab1 = Frame(self.tabControl) self.tabControl.add(self.tab1, text='企业用户') self.tab2 = Frame(self.tabControl) self.tabControl.add(self.tab2, text='个人用户') self.tabControl.pack(expand=1, fill="both") self.create_widgets_user() self.create_widgets() def create_widgets(self): #self.frame.destroy() #self.frame1 = Frame(self) #self.frame1.grid() #self.frame2 = Frame(self) #self.frame2.grid() self.chooseLabel = Label(self.tab1, text='请选择进行所需图片的语义信息') self.chooseLabel.grid(column=1, row=1, sticky='W') #comvalue.append(print("comvalue" + str(i))) #comboxlist.append(print("comboxlist" + str(i))) #self.comvalue = StringVar() # 窗体自带的文本,新建一个值 self.comboxlist = ttk.Combobox(self.tab1, textvariable='', state="readonly") #初始化 self.comboxlist["values"] = ("房屋占地率(%)", "绿化率(%)", "车辆数目", "篮球场数目") #self.comboxlist["values"] = ("first", "second", "third", "fourth") self.comboxlist.current(0) self.comboxlist.bind( "<<ComboboxSelected>>", print(self.comboxlist.get())) #绑定事件,(下拉列表框被选中时,绑定go()函数) self.comboxlist.grid(row=2, column=0) self.spinBox1 = Spinbox(self.tab1, from_=0, to=100, increment=1) self.spinBox1.grid(row=2, column=1) self.spinBox2 = Spinbox(self.tab1, from_=0, to=100, increment=1) self.spinBox2.grid(row=2, column=2) self.addButton = Button(self.tab1, text='确定并增加条件', command=self.add_condition) self.addButton.grid(row=3, column=1) self.cancelButton = Button(self.tab1, text='条件输入有误,重新输入', command=self.delete_condition) self.cancelButton.grid(row=4, column=1) self.confirmButton = Button(self.tab1, text='完成所有条件', command=self.check) self.confirmButton.grid(row=5, column=1) #self.backButton = Button(self.tab1, text='返回初始界面', command=self.create_widgets_initial) #self.backButton.grid() self.quitButton = Button(self.tab1, text='Quit', command=self._quit) self.quitButton.grid(row=6, column=1) def add_condition(self): self.confirm_condition() self.addButton.destroy() self.cancelButton.destroy() self.confirmButton.destroy() self.quitButton.destroy() #self.comvalue = StringVar() # 窗体自带的文本,新建一个值 self.comboxlist = ttk.Combobox(self.tab1, textvariable='') # 初始化 self.comboxlist["values"] = ("房屋占地率(%)", "绿化率(%)", "车辆数目", "篮球场数目") #self.comboxlist["values"] = ("first", "second", "third", "fourth") self.comboxlist.current(0) self.comboxlist.bind( "<<ComboboxSelected>>", print(self.comboxlist.get())) # 绑定事件,(下拉列表框被选中时,绑定go()函数) self.comboxlist.grid(row=len(self.className) + 2, column=0) self.spinBox1 = Spinbox(self.tab1, from_=0, to=100, increment=1) self.spinBox1.grid(row=len(self.className) + 2, column=1) self.spinBox2 = Spinbox(self.tab1, from_=0, to=100, increment=1) self.spinBox2.grid(row=len(self.className) + 2, column=2) self.addButton = Button(self.tab1, text='确定并增加条件', command=self.add_condition) self.addButton.grid(row=len(self.className) + 3, column=1) self.cancelButton = Button(self.tab1, text='条件输入有误,重新输入', command=self.delete_condition) self.cancelButton.grid(row=len(self.className) + 4, column=1) self.confirmButton = Button(self.tab1, text='完成所有条件', command=self.check) self.confirmButton.grid(row=len(self.className) + 5, column=1) # self.backButton = Button(self.tab1, text='返回初始界面', command=self.create_widgets_initial) # self.backButton.grid() self.quitButton = Button(self.tab1, text='Quit', command=self._quit) self.quitButton.grid(row=len(self.className) + 6, column=1) #self.addButton.grid(row=len(self.className)+1, column=2) def confirm_condition(self): #print("confirm") if (self.comboxlist.get() in self.className): self._msgbox("条件已存在,请重新选择") return 0 else: self.className.append(self.comboxlist.get()) self.prob.append(self.spinBox1.get()) self.prob.append(self.spinBox2.get()) return 1 def delete_condition(self): if (messagebox.askyesno(message='确定清除所有条件吗')): for i in range(0, len(self.className)): self.className.clear() self.prob.clear() # self.comboxlist.destroy() # self.spinBox.destroy() # self.addButton.destroy() #self.lab1.destroy() self.tab1.destroy() self.tab2.destroy() #self.tab1 = Frame(self.tabControl) #self.tabControl.add(self.tab1, text='企业用户') self.create_widgets_initial() def check(self): if (self.confirm_condition() == 0): self.comboxlist = ttk.Combobox(self.tab1, textvariable='') # 初始化 self.comboxlist["values"] = ("房屋占地率(%)", "绿化率(%)", "车辆数目", "篮球场数目") #self.comboxlist["values"] = ("first", "second", "third", "fourth") self.comboxlist.current(0) self.comboxlist.bind( "<<ComboboxSelected>>", print(self.comboxlist.get())) # 绑定事件,(下拉列表框被选中时,绑定go()函数) self.comboxlist.grid(row=len(self.className) + 1, column=0) self.spinBox1 = Spinbox(self.tab1, from_=0, to=100, increment=1) self.spinBox1.grid(row=len(self.className) + 1, column=1) self.spinBox2 = Spinbox(self.tab1, from_=0, to=100, increment=1) self.spinBox2.grid(row=len(self.className) + 1, column=2) self.addButton = Button(self.tab1, text='确定并增加条件', command=self.add_condition) self.addButton.grid(row=len(self.className) + 2, column=1, columnspan=2) else: self.addButton.destroy() self.confirmButton.destroy() self.cancelButton.destroy() self.quitButton.destroy() self.cancelButton = Button(self.tab1, text='条件输入有误,重新输入', command=self.delete_condition) self.cancelButton.grid(row=len(self.className) + 2, column=1) self.runButton = Button(self.tab1, text='开始运行', command=self.run) self.runButton.grid(row=len(self.className) + 3, column=1) self.quitButton = Button(self.tab1, text='Quit', command=self._quit) self.quitButton.grid(row=len(self.className) + 4, column=1) def run(self): self.addButton.destroy() self.cancelButton["text"] = "清除所有条件" self.info = [] #合成命令 #激活环境并运行 self.info.append( "cd venv\Scripts\&activate.bat&cd ..&cd ..&python connection_local.py" ) #个人用户电脑信息 self.info.append(" --hostname " + myaddr + " --port " + myport + " --username " + myname + " --passcode " + mypasscode) #需要提取的信息条件 for i in range(0, len(self.className)): self.info.append(" --" + self.className[i] + " " + self.prob[2 * i] + "," + self.prob[2 * i + 1]) self.info_str = ''.join(self.info) #print(self.info) print(self.info_str) self.info_str = self.info_str.replace("房屋占地率(%)", "first") self.info_str = self.info_str.replace("绿化率(%)", "second") self.info_str = self.info_str.replace("车辆数目", "third") self.info_str = self.info_str.replace("篮球场数目", "fourth") print(self.info_str) path = 'D:\study\Eagle\DB\DB' for i in os.listdir(path): path_file1 = os.path.join(path, i) if os.path.isfile(path_file1): os.remove(path_file1) #清空路径下的文件 output = os.popen(self.info_str) op = output.read() print(op) img_path = [] for line in op.splitlines(): img_path.append(line) if img_path[len(img_path) - 1] == "finish": print(img_path) img_path1 = os.path.abspath(os.path.dirname(img_path[0])) img_path1 = img_path1.replace('\mnt\d', '') self.result(img_path1) self.pic_win.resultLabel[ "text"] = "满足条件图片已保存在本地文件夹:\n" + img_path1 self.pic_win.canvas = Canvas(self.pic_win) self.pic_win.canvas.pack() self.pic_win.checkButton = Button( self.pic_win, text="查看图片", command=lambda: self.pic_preview(img_path1)) self.pic_win.checkButton.pack() img_path = [ 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-021.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-035.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-038.png', 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images\SNAG-040.png' ] img_path1 = 'D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images' self.result(img_path1) def result(self, img_path1): self.pic_win = Toplevel() screenwidth = self.pic_win.winfo_screenwidth() screenheight = self.pic_win.winfo_screenheight( ) # 设置界面宽度为530,高度为365像素,并且基于屏幕居中 width = 1500 height = 800 size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) self.pic_win.geometry(size) self.pic_win.grid() self.pic_win.title("结果") self.pic_win.resultLabel = Label(self.pic_win, text="满足条件图片已保存在本地文件夹:\n" + img_path1) self.pic_win.resultLabel.pack() self.pic_win.checkButton = Button( self.pic_win, text="查看图片", command=lambda: self.pic_preview(img_path1)) self.pic_win.checkButton.pack() self.listBox = Listbox(self.pic_win) self.scrollbar = Scrollbar(self.listBox, orient=HORIZONTAL) self.scrollbar.pack(side=BOTTOM, fill="x") self.listBox.config(xscrollcommand=self.scrollbar.set) self.scrollbar.set(0.6, 0) self.scrollbar.config(command=self.listBox.xview()) gifsdict = {} self.listBox.pack(expand=YES) self.pic_win.infoLabel = Label(self.pic_win, text='info:', justify=LEFT) self.pic_win.infoLabel.pack() def pic_preview(self, img_path1): #父窗口可以在主窗口之前关的问题为解决 self.pic_win.wm_attributes('-topmost', 1) self.pic_win.wm_attributes('-topmost', 0) #print("sssss"+img_path1) self.filePath = filedialog.askopenfilename(parent=self, initialdir=img_path1, title='Choose an image.') odFilePath = str(self.filePath).replace('RGB', 'OD') ssFilePath = str(self.filePath).replace('RGB', 'SS') infoFilePath = str(self.filePath).replace('RGB.png', 'INFO.txt') img = Image.open(self.filePath) filename = ImageTk.PhotoImage(img) odImg = Image.open(odFilePath) odFilename = ImageTk.PhotoImage(odImg) ssImg = Image.open(ssFilePath) ssFilename = ImageTk.PhotoImage(ssImg) self.pic_win.wm_attributes('-topmost', 1) #Label_image = Image.open(self.filePath) #Label_image.show() #self.pic_win.canvas.image = filename # <--- keep reference of your image #self.pic_win.canvas.create_image(0, 0, anchor='nw', image=filename) self.imageLabel = Label(self.listBox, imag=filename) self.imageLabel.pack(side="left", fill="both", expand="yes") self.odLabel = Label(self.listBox, imag=odFilename) self.odLabel.pack(side="left", fill="both", expand="yes") self.ssLabel = Label(self.listBox, imag=ssFilename) self.ssLabel.pack(side="left", fill="both", expand="yes") infoFile = open(infoFilePath, encoding='UTF-8') infoList = [] for line in infoFile.readlines(): infoList.append(line) info = ''.join(infoList) print(info) self.pic_win.infoLabel = Label(self.pic_win, text=info, justify=LEFT) self.pic_win.infoLabel.pack() self.listBox.insert(ACTIVE, self.imageLabel) self.listBox.insert(ACTIVE, self.odLabel) self.listBox.insert(self.ssLabel) #self.listBox.insert(END, self.infoLabel) self.listBox.pack() self.pic_win.checkButton["text"] = "查看下一张图片" def _msgbox(self, msg): messagebox.showinfo('提示', msg) def create_widgets_user(self): #self.frame.destroy() #self.frame3 = Frame(self) #self.frame3.grid() self.chooseLabel = Label(self.tab2, text='请选择进行目标检测和语义分割的图片') self.chooseLabel.pack() self.canvas = Canvas(self.tab2, height=200, width=200) self.canvas.pack() self.pathLabel = Label(self.tab2, text='Image Path') self.pathLabel.pack() self.chooseButton = Button(self.tab2, text='Choose', command=self.pic_choose_user) self.chooseButton.pack() self.detectButton = Button(self.tab2, text='Detect', command=self.detect_user) self.detectButton.pack() self.quitButton = Button(self.tab2, text='Quit', command=self._quit) self.quitButton.pack() def pic_choose_user(self): self.filePath = filedialog.askopenfilename(parent=self, initialdir="C:/", title='Choose an image.') #self.filePath = filedialog.askopenfilename(parent=self, initialdir=self.image_path_temporary, title='Choose an image.') img = Image.open(self.filePath) img_width = img.size[0] img_height = img.size[1] rate = img_width / img_height if rate > 1: rate1 = img_width / 200 img_width = 200 img_height = img_height / rate1 else: rate1 = float(img_height) / 200.0 img_height = 200 img_width = img_width / rate1 img_new = img.resize((int(img_width), int(img_height))) filename = ImageTk.PhotoImage(img_new) self.canvas.image = filename # <--- keep reference of your image self.canvas.create_image(0, 0, anchor='nw', image=filename) def detect_user(self): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ServerHostname, port=ServerPort, username=ServerUsername, password=ServerPassword) folder = '/server_space/jiangyl/dlink_potsdam_normto1/remote' # folder has script file = 'predict_remote.py' sftp = ssh.open_sftp() sftp.put(self.filePath, folder + 'test.png') stdin, stdout, stderr = ssh.exec_command('cd %s; python %s ' % (folder, file)) for s in stdout: if s == "finish": self.pic_preview_user() ssh.close() self.pic_preview_user( "D:\study\Eagle\squeeze_yolo_gui\squeeze_yolo_gui\datasets\google_maps\images/001.png" ) def pic_preview_user(self, filePath): self.pic_win_user = Toplevel() self.pic_win_user.wm_attributes('-topmost', 1) self.pic_win_user.wm_attributes('-topmost', 0) self.listBox_user = Listbox(self.pic_win_user) self.scrollbar_user = Scrollbar(self.listBox_user, orient=HORIZONTAL) self.scrollbar_user.pack(side=BOTTOM, fill="x") self.listBox_user.config(xscrollcommand=self.scrollbar_user.set) self.scrollbar_user.set(0.6, 0) self.scrollbar_user.config(command=self.listBox_user.xview()) gifsdict = {} self.listBox_user.pack(expand=YES) odFilePath = filePath.replace('RGB', 'OD') ssFilePath = filePath.replace('RGB', 'SS') infoFilePath = filePath.replace('RGB.png', 'INFO.txt') print(filePath) img = Image.open(filePath) filename = ImageTk.PhotoImage(img) odImg = Image.open(odFilePath) odFilename = ImageTk.PhotoImage(odImg) ssImg = Image.open(ssFilePath) ssFilename = ImageTk.PhotoImage(ssImg) self.pic_win_user.wm_attributes('-topmost', 1) self.imageLabel_user = Label(self.listBox_user, imag=filename) self.imageLabel_user.pack(side="left", fill="both", expand="yes") self.odLabel_user = Label(self.listBox_user, imag=odFilename) self.odLabel_user.pack(side="left", fill="both", expand="yes") self.ssLabel_user = Label(self.listBox_user, imag=ssFilename) self.ssLabel_user.pack(side="left", fill="both", expand="yes") infoFile = open(infoFilePath) infoList = [] for line in infoFile.readlines(): infoList.append(line) info = ''.join(infoList) print(info) self.infoLabel_user = Label(self.pic_win_user, text=info, justify=LEFT) self.infoLabel_user.pack() self.listBox_user.insert(ACTIVE, self.imageLabel_user) self.listBox_user.insert(ACTIVE, self.odLabel_user) self.listBox_user.insert(self.ssLabel_user) # self.listBox_user.insert(END, self.infoLabel) self.listBox_user.pack() def _quit(self): self.quit() self.destroy() exit()