def create_widgets(self): url_frame = Frame(self) url_frame.pack(anchor='w', fill='x') url_label = Label(url_frame, text='Google Patent URL: ') url_label.pack(side='left') url_entry = Entry(url_frame, width=75) url_entry.pack(side='left', expand=True, fill='x') url_entry.bind('<Return>', self.analyze_patent) url_entry.bind('<2>', rClicker) claim_pane = PanedWindow(self, orient=HORIZONTAL) claim_pane.pack(anchor='n', fill='both', expand=True) claim_treeview = Treeview(claim_pane, columns=('Type', ), displaycolumns='#all', selectmode='browse') claim_treeview.column('Type', stretch=True) claim_treeview.heading('Type', text='Type') claim_treeview.heading('#0', text='#') claim_treeview.bind('<<TreeviewSelect>>', self.display_claim) claim_pane.add(claim_treeview) claim_text = ScrolledText(claim_pane, font=('Helvetica', 17), wrap='word') claim_text.bind('<2>', rClicker) claim_pane.add(claim_text) self.claim_treeview = claim_treeview self.claim_text = claim_text
class MyGUI: def __init__(self, reps=3): self.reps = reps self.text = ScrolledText() self.text.pack() threadChecker(self.text) self.text.bind('<Button-1>', lambda event: list(map(self.onEvent, range(6)))) def onEvent(self, i): myname = 'thread-%s' % i startThread(action=self.threadaction, args=(i, ), context=(myname,), onExit=self.threadexit, onFail=self.threadfail, onProgress=self.threadprogress) def threadaction(self, id, progress): for i in range(self.reps): time.sleep(1) if progress: progress(i) if id % 2 == 1: raise Exception def threadexit(self, myname): self.text.insert('end', '%s\texit\n' % myname) self.text.see('end') def threadfail(self, exc_info, myname): self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0])) self.text.see('end') def threadprogress(self, count, myname): self.text.insert('end', '%s\tprog\t%s\n' % (myname, count)) self.text.see('end') self.text.update()
def make_gui(cls, interactive=False): gui = cls() root = Tk() gui.root = root f = Frame(root) f.pack(side='top', expand=1, fill='both') gui.frame = f canvas = Canvas(f) canvas.bind("<Configure>", gui.configure_canvas) canvas.pack(side='top', expand=1, fill='both') gui.canvas = canvas screen = turtle.TurtleScreen(canvas) gui.screen = screen if interactive: output = ScrolledText(f, height=10, state='disabled') output.bind("<1>", lambda event: output.focus_set()) output.pack(side='top', expand=0, fill='x') gui.output = output text_input = Frame(f) prompt = Label(text_input, text="?") prompt.pack(side='left', expand=0) gui._prompt_label = prompt input_var = StringVar() gui.input_var = input_var entry = Entry(text_input, textvariable=input_var) entry.bind('<Return>', gui.handle_input) entry.bind('<Up>', gui.back_history) entry.bind('<Down>', gui.forward_history) entry.pack(side='left', expand=1, fill='x') text_input.pack(side='top', expand=0, fill='x') return gui
class mainWindow: def __init__(self, master=None): self.master = master self.set_app_title(None) self.font = Font(family="Verdana", size=10) self.text = ScrolledText(self.master, state='normal', height=400, width=400, wrap='word', font=self.font, pady=2, padx=3, undo=True, bg='white') self.text.pack(fill=tk.Y, expand=1) self.text.focus_set() self.menubar = tk.Menu(self.master, relief=tk.FLAT) self.selectedText = None '''configure events''' self.events() def build(self): self.fileMenu = file_menu.fileMenu(self.text, self.master, self) self.editMenu = edit_menu.editMenu(self.text, self.master, self) self.formatMenu = format_menu.formatMenu(self.text, self.master, self) self.helpMenu = help_menu.helpMenu(self.text, self.master, self) def events(self): self.text.bind("<<Selection>>", self.selected_text) self.master.bind("<Button-1>", self.mouse_click) self.menubar.bind("<Button-1>", self.mouse_click) def set_app_title(self, file_name): app_title = my_globals.BTTE_NAME() + '-' app_title += 'v' + my_globals.BTTE_VERSION() + '-' if not file_name: file_name = "Untitled" app_title += file_name self.master.title(app_title) '''EVENTS''' def selected_text(self, event): oldSelectedText = self.selectedText try: self.selectedText = self.text.get(tk.SEL_FIRST, tk.SEL_LAST) except: self.selectedText = None ''' update edit menu''' if oldSelectedText != self.selectedText: self.editMenu.update() def mouse_click(self, event): self.editMenu.rightClick.unpost()
class TextFrame(ttk.LabelFrame): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._init_ui() def _init_ui(self): self.textbox = ScrolledText(self, width=70, height=10) self.textbox.bind("<1>", lambda event: self.textbox.focus_set()) self.textbox.pack(expand=True, fill='both')
class ConsoleUi: """Poll messages from a logging queue and display them in a scrolled text widget""" def __init__(self, frame): self.frame = frame self.input_start_idx = tk.END # Create a ScrolledText wdiget self.scrolled_text = ScrolledText(frame, state='disabled', height=12) self.scrolled_text.pack(expand=True, fill=tk.BOTH) self.scrolled_text.configure(font='TkFixedFont') self.scrolled_text.tag_config('INFO', foreground='black') self.scrolled_text.tag_config('DEBUG', foreground='gray') self.scrolled_text.tag_config('WARNING', foreground='dark orange') self.scrolled_text.tag_config('ERROR', foreground='red') self.scrolled_text.tag_config('CRITICAL', foreground='red', underline=1) self.scrolled_text.bind('<Key>', self.key_press) # Create a logging handler using a queue self.log_queue = queue.Queue() self.queue_handler = QueueHandler(self.log_queue) formatter = logging.Formatter('%(asctime)s:\t%(message)s', datefmt='%H:%M:%S') self.queue_handler.setFormatter(formatter) logger.addHandler(self.queue_handler) # Start polling messages from the queue self.frame.after(100, self.poll_log_queue) def display(self, record): msg = record.getMessage() self.scrolled_text.configure(state='normal') self.scrolled_text.insert(tk.END, msg + '\n', record.levelname) # self.scrolled_text.configure(state='disabled') # Autoscroll to the bottom self.scrolled_text.yview(tk.END) self.scrolled_text.mark_set('input_start', 'end-1c') self.scrolled_text.mark_gravity('input_start', tk.LEFT) def poll_log_queue(self): while True: try: record = self.log_queue.get(block=False) except queue.Empty: break else: self.display(record) # Check every 100ms if there is a new message in the queue to display self.frame.after(100, self.poll_log_queue) def key_press(self, event): """Function used to send any inputs to the input_queue when the return key is pressed""" if event.char == '\r': user_input = self.scrolled_text.get('input_start', 'end-1c').strip() input_queue.put(user_input) self.scrolled_text.mark_set('input_start', 'end-1c')
def init_disp(self): """Output area""" disp_area = ScrolledText(master=self.frame, wrap=tk.WORD, width=60, height=10) disp_area.grid(padx=10, pady=10, row=3, column=0, columnspan=4, rowspan=4, sticky='nsew') disp_area.bind("<1>", lambda event: disp_area.focus_set()) disp_area.insert('end', '等待指示!') disp_area.configure(state='disabled') tk.Grid.rowconfigure(self.frame, 3, weight=1) tk.Grid.columnconfigure(self.frame, 0, weight=1) return disp_area
class Log(Base): def __init__(self, parent): Base.__init__(self, parent) self.parent = parent self.frame = ttk.Frame(self.parent) self.frame.pack() Base.set_position(self, 266, 270) bar = Scrollbar(self.frame, orient=tk.HORIZONTAL) self.log_box = ScrolledText(self.frame, width=35, height=15, wrap='none', font=("Calibri", 10)) self.log_box.bind("<Key>", lambda e: "break") bar.config(command=self.log_box.xview) self.log_box.config(xscrollcommand=bar.set) self.log_box.grid(row=0, columnspan=2) bar.grid(row=1, column=0, sticky='nsew', columnspan=2) if functions.light_mode_is_on(): self.log_box.config(background='gray88', foreground="gray8") else: self.log_box.config(background='gray15', foreground="gray95") ttk.Button(self.frame, text="Click here to copy", command=self.copy_log_clipboard).grid(row=2, column=0, columnspan=3, sticky="WE") self.read_log() def read_log(self): with open(Path(__file__).parent / "full.log") as file: self.text = file.readlines() self.log_box.insert(tk.INSERT, ''.join(self.text)) def copy_log_clipboard(self): pyperclip.copy(''.join(self.text))
class MyGui: def __init__(self, reps=3): self.reps = reps self.text = ScrolledText() self.text.pack() threadChecker(self.text) self.text.bind('<Button-1>', lambda event: list(map(self.onEvent, range(6)))) def onEvent(self, i): myname = 'thread-%s' % i startThread(action=self.threadaction, args=(i, 3), context=(myname, ), onExit=self.threadexit, onFail=self.threadfail, onProgress=self.threadprogress) # 线程主要操作 def threadaction(self, id, progress): # 线程的功能 for i in range(self.reps): time.sleep(1) if progress: progress(i) # 回调,加入队列 if id % 2 == 1: # 奇数表示失败 raise Exception # 线程exit/progress回调:离开主线程队列 def threadexit(self, myname): self.text.insert('end', '%s\text\n' % myname) self.text.see('end') def threadfail(self, exc_info, myname): self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0])) self.text.see('end') def threadprogress(self, count, myname): self.text.insert('end', '%s\tprogress\t%s\n' % (myname, count)) self.text.see('end') self.text.update() # 在这里生效,在主线程中运行
class MyGUI: def __init__(self, reps=3): self.reps = reps # uses default Tk root self.text = ScrolledText() # save widget as state self.text.pack() threadChecker(self.text) # start thread check loop self.text.bind('<Button-1>', # 3.x need list for map, range ok lambda event: list(map(self.onEvent, range(6))) ) def onEvent(self, i): # code that spawns thread myname = 'thread-%s' % i startThread( action = self.threadaction, args = (i, ), context = (myname,), onExit = self.threadexit, onFail = self.threadfail, onProgress = self.threadprogress) # thread's main action def threadaction(self, id, progress): # what the thread does for i in range(self.reps): # access to object state here time.sleep(1) if progress: progress(i) # progress callback: queued if id % 2 == 1: raise Exception # odd numbered: fail # thread callbacks: dispatched off queue in main thread def threadexit(self, myname): self.text.insert('end', '%s\texit\n' % myname) self.text.see('end') def threadfail(self, exc_info, myname): # have access to self state self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0])) self.text.see('end') def threadprogress(self, count, myname): self.text.insert('end', '%s\tprog\t%s\n' % (myname, count)) self.text.see('end') self.text.update() # works here: run in main thread
class MyGUI: def __init__(self, reps=3): self.reps = reps self.text = ScrolledText() self.text.pack() threadChecker(self.text) self.text.bind('<Button-1>', lambda event: list(map(self.onEvent, range(6)))) def onEvent(self, i): myname = 'thread-%s' % i startThread(action=self.threadaction, args=(i, ), context=(myname, ), onExit=self.threadexit, onFail=self.threadfail, onProgress=self.threadprogress) def threadaction(self, id_, progress): for i in range(self.reps): time.sleep(1) if progress: progress(i) if id_ % 2 == 1: raise Exception def threadexit(self, myname): self.text.insert('end', '%s\texit\n' % myname) self.text.see('end') def threadfail(self, exc_info, myname): self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0])) self.text.see('end') def threadprogress(self, count, myname): self.text.insert('end', '%s\tprog\t%s\n' % (myname, count)) self.text.see('end') self.text.update()
def create_widgets(self): url_frame = Frame(self) url_frame.pack(anchor='w', fill='x') url_label = Label(url_frame, text='Google Patent URL: ') url_label.pack(side='left') url_entry = Entry(url_frame, width=75) url_entry.pack(side='left', expand=True, fill='x') url_entry.bind('<Return>', self.analyze_patent) url_entry.bind('<2>', rClicker) claim_pane = PanedWindow(self, orient=HORIZONTAL) claim_pane.pack(anchor='n', fill='both', expand=True) claim_treeview = Treeview(claim_pane, columns=('Type',), displaycolumns='#all', selectmode='browse') claim_treeview.column('Type', stretch=True) claim_treeview.heading('Type', text='Type') claim_treeview.heading('#0', text='#') claim_treeview.bind('<<TreeviewSelect>>', self.display_claim) claim_pane.add(claim_treeview) claim_text = ScrolledText(claim_pane, font=('Helvetica', 17), wrap='word') claim_text.bind('<2>', rClicker) claim_pane.add(claim_text) self.claim_treeview = claim_treeview self.claim_text = claim_text
#canvas horizontal scrollbar canvas_hbar = Scrollbar(canvas_frame, orient=HORIZONTAL) canvas_hbar.pack(side=BOTTOM, fill=X) canvas_hbar.config(command=page.xview) #connect canvas to scrollbars page.config(xscrollcommand=canvas_hbar.set, yscrollcommand=canvas_vbar.set) page.pack(side=LEFT, fill=BOTH, expand=YES) #canvas takes up rest of space #Text box for translations translation_textbox = ScrolledText(frame, wrap='word', height=5, undo=True) translation_textbox.grid(row=2, column=1, columnspan=2, sticky=(W, E)) #Stretch configurations root.columnconfigure(0, weight=1) #main window root.rowconfigure(0, weight=1) #main window frame.columnconfigure(1, weight=1, minsize=300) #canvas frame x frame.rowconfigure(1, weight=1, minsize=745) #canvas frame y menu_frame.rowconfigure(4, weight=1) #listbox #Event bindings page_listbox.bind("<Double-Button-1>", listbox_change_page) #change active page by listbox page.bind("<MouseWheel>", zoom) #zoom using the mouse wheel page.bind("<Button-1>", canvas_click) #create a new object page.bind("<Motion>", mouseover) page.bind("<ButtonRelease-1>", on_release) translation_textbox.bind("<FocusOut>", textbox_out) #focus off of text box translation_textbox.bind("<Escape>", textbox_out) #press esc when editing root.mainloop()
time.sleep(1) # 模拟长时间工作 if progress: progress(i) # progress callback: queued if id % 2 == 1: raise Exception # odd numbered: fail #奇数则模拟异常,否则正常结束 # thread exit/progress callbacks: dispatched off queue in main thread def threadexit(myname): text.insert("end", "%s\texit\n" % myname) text.see("end") def threadfail(exc_info, myname): text.insert("end", "%s\tfail\t%s\n" % (myname, exc_info[0])) text.see("end") def threadprogress(count, myname): text.insert("end", "%s\tprog\t%s\n" % (myname, count)) text.see("end") text.update() # works here: run in main thread # make enclosing GUI and start timer loop in main thread # spawn batch of worker threads on each mouse click: may overlap text = ScrolledText() text.pack() threadChecker(text) # start thread loop in main thread #开始检查到来的生产品 text.bind( "<Button-1>", lambda event: list(map(onEvent, range(6))) # 3.x need list for map, range ok ) # 按下左键启动6个工作者线程 text.mainloop() # pop-up window, enter tk event loop
class Application(ttk.Frame): def __init__(self, master=None): # ttk.Frame is an old-style class on 2.7 ttk.Frame.__init__(self, master) self._init_ui() self.pack() env = os.environ.copy() env['RUST_LOG'] = 'info' self.wrapper = WrapperProcessMonitor(('bin/wrapper',), env=env) self.wrapper.on_event = self._handle_wrapper_event module = 'http.server' if py3 else 'SimpleHTTPServer' self.http = ProcessMonitor((sys.executable, '-u', '-m', module, '8889'), cwd=os.path.join(os.getcwd(), 'www')) self.http.on_event = self._handle_http_event self.repl = ReplConnection() self.repl.on_event = self._handle_repl_event self.stopping = 0 self.master.protocol('WM_DELETE_WINDOW', self._handle_close) self.after(100, self._check_queues) def _init_ui(self): frame_top = ttk.Frame(self) notebook = ttk.Notebook(self) self.btn_start = ttk.Button(frame_top, text='Start Server', command=self._start) self.btn_stop = ttk.Button(frame_top, text='Stop Server', command=self._stop) self.btn_stop.state(['disabled']) self.btn_start.pack(side='left') self.btn_stop.pack(side='right') notebook.add(self._init_status_frame(notebook), text='Status') notebook.add(self._init_repl_frame(notebook), text='REPL') self.wrapper_log = ScrolledText(notebook, height=20, width=80) notebook.add(self.wrapper_log, text='Main Log') self.http_log = ScrolledText(notebook, height=20, width=80) notebook.add(self.http_log, text='HTTP Log') frame_top.pack() notebook.pack() def _init_status_frame(self, notebook): wrapper = ttk.Frame(notebook) frame = ttk.Frame(wrapper) ttk.Label(frame, text='Main Server: ').grid(row=0, column=0, sticky='W') ttk.Label(frame, text='HTTP Server: ').grid(row=1, column=0, sticky='W') self.status_wrapper = ttk.Label(frame, text='Not running') self.status_wrapper.grid(row=0, column=1, sticky='W') self.status_http = ttk.Label(frame, text='Not running') self.status_http.grid(row=1, column=1, sticky='W') self.status_extra = ttk.Label(frame, text='') self.status_extra.grid(row=2, column=0, columnspan=2) frame.pack() return wrapper def _init_repl_frame(self, notebook): frame = ttk.Frame(notebook) self.repl_input = ScrolledText(frame, height=15, width=80) self.repl_input.insert(tk.END, '-- REPL command input\n' '-- Press Ctrl-Enter to run command\n' 'client_by_name(\'OP\'):extra().superuser = true') self.repl_input.bind('<Control-Return>', self._repl_send) self.repl_input.pack() self.repl_output = ScrolledText(frame, height=5, width=80) self.repl_output.pack() return frame def _handle_wrapper_event(self, kind, data): self._log_event(self.wrapper_log, kind, data) if kind in ('error', 'result'): if self.stopping > 0: self.stopping -= 1 stat = 'down' else: stat = 'err' self._update_status(wrapper=stat) def _handle_http_event(self, kind, data): self._log_event(self.http_log, kind, data) if kind in ('error', 'result'): if self.stopping > 0: self.stopping -= 1 stat = 'down' else: stat = 'err' self._update_status(http=stat) def _repl_send(self, evt): cmd = self.repl_input.get('1.0', tk.END) cmd = '{\n%s\n}\n' % cmd try: self.repl.send(cmd) except (IOError, OSError) as e: append_text(self.repl_output, '\n\nError sending command: %s' % e) return 'break' def _handle_repl_event(self, kind, data): if kind == 'recv': append_text(self.repl_output, data.decode('utf-8')) def _log_event(self, log, kind, data): if kind == 'error': append_text(log, '\n\nError reading output: %s' % data.decode()) elif kind == 'result': append_text(log, '\n\nProcess exited with code %d' % data) elif kind == 'output': append_text(log, data.decode()) def _check_queues(self): self.wrapper.poll() self.http.poll() self.repl.poll() self.after(100, self._check_queues) def _start(self): if os.name == 'posix': if os.path.exists('control'): os.remove('control') if os.path.exists('repl'): os.remove('repl') try: self.wrapper.start() wrapper_ok = 'up' except OSError as e: append_text(self.wrapper_log, '\n\nError starting main server: %s' % e) wrapper_ok = 'err' try: self.http.start() http_ok = 'up' except OSError as e: append_text(self.http_log, '\n\nError starting HTTP server: %s' % e) http_ok = 'err' self._update_status(wrapper=wrapper_ok, http=http_ok) self.btn_start.state(['disabled']) self.btn_stop.state(['!disabled']) def _stop(self): self.stopping = 2 self.wrapper.stop() self.http.stop() self.repl.close() self.btn_start.state(['!disabled']) self.btn_stop.state(['disabled']) def _update_status(self, wrapper=None, http=None): STATUS_TEXT = { 'up': 'Running', 'down': 'Not running', 'err': 'Error (see log)', } if wrapper is not None: self.status_wrapper.config(text=STATUS_TEXT[wrapper]) if http is not None: self.status_http.config(text=STATUS_TEXT[http]) if wrapper == 'up' and http == 'up': self.status_extra.config( text='Visit http://localhost:8889/client.html to play') else: self.status_extra.config(text='') def _handle_close(self): self._stop() self.quit()
class WbRunner(tk.Frame): def __init__(self, tool_name=None, master=None): # First, try to find the WhiteboxTools exe directory if _platform == 'win32': ext = '.exe' else: ext = '' exe_name = "whitebox_tools{}".format(ext) self.exe_path = path.dirname(path.abspath(__file__)) os.chdir(self.exe_path) for filename in glob.iglob('**/*', recursive=True): if filename.endswith(exe_name): self.exe_path = path.dirname(path.abspath(filename)) break wbt.set_whitebox_dir(self.exe_path) ttk.Frame.__init__(self, master) self.script_dir = os.path.dirname(os.path.realpath(__file__)) self.grid() self.tool_name = tool_name self.master.title("WhiteboxTools Runner") # widthpixels = 800 # heightpixels = 600 # self.master.geometry('{}x{}'.format(widthpixels, heightpixels)) # self.master.resizable(0, 0) # self.master.lift() if _platform == "darwin": os.system( '''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''' ) self.create_widgets() self.working_dir = str(Path.home()) def create_widgets(self): toplevel_frame = ttk.Frame(self, padding='0.1i') (self.toolslist, selected_item) = self.get_tools_list() self.tools_frame = ttk.LabelFrame(toplevel_frame, text="{} Available Tools".format( len(self.toolslist)), padding='0.1i') self.toolnames = tk.StringVar(value=self.toolslist) self.tools_listbox = tk.Listbox(self.tools_frame, height=22, listvariable=self.toolnames) self.tools_listbox.bind("<<ListboxSelect>>", self.update_tool_help) self.tools_listbox.grid(row=0, column=0, sticky=tk.NSEW) self.tools_listbox.columnconfigure(0, weight=10) self.tools_listbox.rowconfigure(0, weight=1) s = ttk.Scrollbar(self.tools_frame, orient=tk.VERTICAL, command=self.tools_listbox.yview) s.grid(row=0, column=1, sticky=(tk.N, tk.S)) self.tools_listbox['yscrollcommand'] = s.set self.tools_frame.grid(row=0, column=0, sticky=tk.NSEW) self.tools_frame.columnconfigure(0, weight=10) self.tools_frame.columnconfigure(1, weight=1) self.tools_frame.rowconfigure(0, weight=1) overall_frame = ttk.Frame(toplevel_frame, padding='0.1i') # json_str = '{"default_value": null, "description": "Directory containing data files.", "flags": ["--wd"], "name": "Working Directory", "optional": true, "parameter_type": "Directory"}' # self.wd = FileSelector(json_str, overall_frame) # self.wd.grid(row=0, column=0, sticky=tk.NSEW) current_tool_frame = ttk.Frame(overall_frame, padding='0.1i') self.current_tool_lbl = ttk.Label( current_tool_frame, text="Current Tool: {}".format(self.tool_name), justify=tk.LEFT) # , font=("Helvetica", 12, "bold") self.current_tool_lbl.grid(row=0, column=0, sticky=tk.W) self.view_code_button = ttk.Button(current_tool_frame, text="View Code", width=12, command=self.view_code) self.view_code_button.grid(row=0, column=1, sticky=tk.E) current_tool_frame.grid(row=1, column=0, sticky=tk.NSEW) current_tool_frame.columnconfigure(0, weight=1) current_tool_frame.columnconfigure(1, weight=1) tool_args_frame = ttk.Frame(overall_frame, padding='0.0i') self.tool_args_frame = ttk.Frame(overall_frame, padding='0.0i') self.tool_args_frame.grid(row=2, column=0, sticky=tk.NSEW) self.tool_args_frame.columnconfigure(0, weight=1) # args_frame = ttk.Frame(overall_frame, padding='0.1i') # self.args_label = ttk.Label(args_frame, text="Tool Arguments:", justify=tk.LEFT) # self.args_label.grid(row=0, column=0, sticky=tk.W) # args_frame2 = ttk.Frame(args_frame, padding='0.0i') # self.args_value = tk.StringVar() # self.args_text = ttk.Entry(args_frame2, width=45, justify=tk.LEFT, textvariable=self.args_value) # self.args_text.grid(row=0, column=0, sticky=tk.NSEW) # self.args_text.columnconfigure(0, weight=1) # self.clearButton = ttk.Button(args_frame2, text="Clear", width=4, command=self.clear_args_box) # self.clearButton.pack(pady=10, padx=10) # self.clearButton.grid(row=0, column=1, sticky=tk.E) # self.clearButton.columnconfigure(0, weight=1) # args_frame2.grid(row=1, column=0, sticky=tk.NSEW) # args_frame2.columnconfigure(0, weight=10) # args_frame2.columnconfigure(1, weight=1) # args_frame.grid(row=2, column=0, sticky=tk.NSEW) # args_frame.columnconfigure(0, weight=1) # # Add the bindings # if _platform == "darwin": # self.args_text.bind("<Command-Key-a>", self.args_select_all) # else: # self.args_text.bind("<Control-Key-a>", self.args_select_all) buttonsFrame = ttk.Frame(overall_frame, padding='0.1i') self.run_button = ttk.Button(buttonsFrame, text="Run", width=8, command=self.run_tool) # self.run_button.pack(pady=10, padx=10) self.run_button.grid(row=0, column=0) self.quitButton = ttk.Button(buttonsFrame, text="Cancel", width=8, command=self.cancel_operation) self.quitButton.grid(row=0, column=1) buttonsFrame.grid(row=3, column=0, sticky=tk.E) output_frame = ttk.Frame(overall_frame, padding='0.1i') outlabel = ttk.Label(output_frame, text="Output:", justify=tk.LEFT) outlabel.grid(row=0, column=0, sticky=tk.NW) k = wbt.tool_help(self.tool_name) self.out_text = ScrolledText(output_frame, width=63, height=10, wrap=tk.NONE, padx=7, pady=7) self.out_text.insert(tk.END, k) self.out_text.grid(row=1, column=0, sticky=tk.NSEW) self.out_text.columnconfigure(0, weight=1) output_frame.grid(row=4, column=0, sticky=tk.NSEW) output_frame.columnconfigure(0, weight=1) # Add the binding if _platform == "darwin": self.out_text.bind("<Command-Key-a>", self.select_all) # self.out_text.bind("<Command-Key-A>", self.select_all) else: self.out_text.bind("<Control-Key-a>", self.select_all) progress_frame = ttk.Frame(overall_frame, padding='0.1i') self.progress_label = ttk.Label(progress_frame, text="Progress:", justify=tk.LEFT) self.progress_label.grid(row=0, column=0, sticky=tk.E, padx=5) self.progress_var = tk.DoubleVar() self.progress = ttk.Progressbar(progress_frame, orient="horizontal", variable=self.progress_var, length=200, maximum=100) self.progress.grid(row=0, column=1, sticky=tk.E) progress_frame.grid(row=5, column=0, sticky=tk.E) overall_frame.grid(row=0, column=1, sticky=tk.NSEW) overall_frame.columnconfigure(0, weight=1) toplevel_frame.columnconfigure(0, weight=1) toplevel_frame.columnconfigure(1, weight=4) # self.pack(fill=tk.BOTH, expand=1) # toplevel_frame.columnconfigure(0, weight=1) # toplevel_frame.rowconfigure(0, weight=1) toplevel_frame.grid(row=0, column=0, sticky=tk.NSEW) # Select the appropriate tool, if specified, otherwise the first tool self.tools_listbox.select_set(selected_item) self.tools_listbox.event_generate("<<ListboxSelect>>") self.tools_listbox.see(selected_item) menubar = tk.Menu(self) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="Set Working Directory", command=self.set_directory) filemenu.add_command(label="Locate WhiteboxTools exe", command=self.select_exe) filemenu.add_command(label="Refresh Tools", command=self.refresh_tools) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.quit) menubar.add_cascade(label="File", menu=filemenu) editmenu = tk.Menu(menubar, tearoff=0) editmenu.add_command( label="Cut", command=lambda: self.focus_get().event_generate("<<Cut>>")) editmenu.add_command( label="Copy", command=lambda: self.focus_get().event_generate("<<Copy>>")) editmenu.add_command( label="Paste", command=lambda: self.focus_get().event_generate("<<Paste>>")) menubar.add_cascade(label="Edit ", menu=editmenu) helpmenu = tk.Menu(menubar, tearoff=0) helpmenu.add_command(label="About", command=self.help) helpmenu.add_command(label="License", command=self.license) menubar.add_cascade(label="Help ", menu=helpmenu) self.master.config(menu=menubar) # self.get_toolboxes() def help(self): self.print_to_output(wbt.version()) def license(self): self.print_to_output(wbt.license()) def set_directory(self): try: self.working_dir = filedialog.askdirectory( initialdir=self.exe_path) wbt.set_working_dir(self.working_dir) except: messagebox.showinfo( "Warning", "Could not find WhiteboxTools executable file.") def select_exe(self): try: filename = filedialog.askopenfilename(initialdir=self.exe_path) self.exe_path = path.dirname(path.abspath(filename)) wbt.set_whitebox_dir(self.exe_path) self.refresh_tools() except: messagebox.showinfo( "Warning", "Could not find WhiteboxTools executable file.") def run_tool(self): # wd_str = self.wd.get_value() wbt.set_working_dir(self.working_dir) # args = shlex.split(self.args_value.get()) args = [] for widget in self.tool_args_frame.winfo_children(): v = widget.get_value() if v: args.append(v) elif not widget.optional: messagebox.showinfo( "Error", "Non-optional tool parameter not specified.") return self.print_line_to_output("") # self.print_line_to_output("Tool arguments:{}".format(args)) # self.print_line_to_output("") # Run the tool and check the return value for an error if wbt.run_tool(self.tool_name, args, self.custom_callback) == 1: print("Error running {}".format(self.tool_name)) else: self.run_button["text"] = "Run" self.progress_var.set(0) self.progress_label['text'] = "Progress:" self.progress.update_idletasks() def print_to_output(self, value): self.out_text.insert(tk.END, value) self.out_text.see(tk.END) def print_line_to_output(self, value): self.out_text.insert(tk.END, value + "\n") self.out_text.see(tk.END) def cancel_operation(self): wbt.cancel_op = True self.print_line_to_output("Cancelling operation...") self.progress.update_idletasks() def view_code(self): webbrowser.open_new_tab(wbt.view_code(self.tool_name).strip()) def update_tool_help(self, event): selection = self.tools_listbox.curselection() self.tool_name = self.tools_listbox.get(selection[0]) self.out_text.delete('1.0', tk.END) for widget in self.tool_args_frame.winfo_children(): widget.destroy() k = wbt.tool_help(self.tool_name) self.print_to_output(k) j = json.loads(wbt.tool_parameters(self.tool_name)) param_num = 0 for p in j['parameters']: json_str = json.dumps(p, sort_keys=True, indent=2, separators=(',', ': ')) pt = p['parameter_type'] if 'ExistingFileOrFloat' in pt: ff = FileOrFloat(json_str, self, self.tool_args_frame) ff.grid(row=param_num, column=0, sticky=tk.NSEW) param_num = param_num + 1 elif ('ExistingFile' in pt or 'NewFile' in pt or 'Directory' in pt): fs = FileSelector(json_str, self, self.tool_args_frame) fs.grid(row=param_num, column=0, sticky=tk.NSEW) param_num = param_num + 1 elif 'FileList' in pt: b = MultifileSelector(json_str, self, self.tool_args_frame) b.grid(row=param_num, column=0, sticky=tk.W) param_num = param_num + 1 elif 'Boolean' in pt: b = BooleanInput(json_str, self.tool_args_frame) b.grid(row=param_num, column=0, sticky=tk.W) param_num = param_num + 1 elif 'OptionList' in pt: b = OptionsInput(json_str, self.tool_args_frame) b.grid(row=param_num, column=0, sticky=tk.W) param_num = param_num + 1 elif ('Float' in pt or 'Integer' in pt or 'String' in pt or 'StringOrNumber' in pt or 'StringList' in pt): b = DataInput(json_str, self.tool_args_frame) b.grid(row=param_num, column=0, sticky=tk.NSEW) param_num = param_num + 1 else: messagebox.showinfo( "Error", "Unsupported parameter type: {}.".format(pt)) self.update_args_box() self.out_text.see("%d.%d" % (1, 0)) def update_args_box(self): s = "" self.current_tool_lbl['text'] = "Current Tool: {}".format( self.tool_name) # self.spacer['width'] = width=(35-len(self.tool_name)) for item in wbt.tool_help(self.tool_name).splitlines(): if item.startswith("-"): k = item.split(" ") if "--" in k[1]: value = k[1].replace(",", "") else: value = k[0].replace(",", "") if "flag" in item.lower(): s = s + value + " " else: if "file" in item.lower(): s = s + value + "='{}' " else: s = s + value + "={} " # self.args_value.set(s.strip()) def clear_args_box(self): self.args_value.set("") def args_select_all(self, event): self.args_text.select_range(0, tk.END) return 'break' def custom_callback(self, value): ''' A custom callback for dealing with tool output. ''' if "%" in value: try: str_array = value.split(" ") label = value.replace(str_array[len(str_array) - 1], "").strip() progress = float(str_array[len(str_array) - 1].replace( "%", "").strip()) self.progress_var.set(int(progress)) self.progress_label['text'] = label except ValueError as e: print("Problem converting parsed data into number: ", e) except Exception as e: print(e) else: self.print_line_to_output(value) self.update( ) # this is needed for cancelling and updating the progress bar def select_all(self, event): self.out_text.tag_add(tk.SEL, "1.0", tk.END) self.out_text.mark_set(tk.INSERT, "1.0") self.out_text.see(tk.INSERT) return 'break' def get_tools_list(self): list = [] selected_item = -1 for item in wbt.list_tools().splitlines(): if item: if "available tools" not in item.lower(): value = item.split(":")[0] list.append(value) if value == self.tool_name: selected_item = len(list) - 1 if selected_item == -1: selected_item = 0 self.tool_name = list[0] return (list, selected_item) def get_toolboxes(self): toolboxes = set() for item in wbt.toolbox().splitlines( ): # run wbt.toolbox with no tool specified--returns all if item: tb = item.split(":")[1].strip() toolboxes.add(tb) for v in sorted(toolboxes): # print(v) self.print_line_to_output(v) def refresh_tools(self): (self.toolslist, selected_item) = self.get_tools_list() self.tools_listbox.delete(0, len(self.toolslist)) for item in self.toolslist: self.tools_listbox.insert(len(self.toolslist), item) self.tools_frame["text"] = "{} Available Tools".format( len(self.toolslist))
class OptimizerMainWindow: """ classdocs """ # TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W + E + N + S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) # generate color tags for textboxes for i in range(101): # green for normal codons (r, g, b) = colorsys.hsv_to_rgb(210 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("normal" + str(i), background=colorHex) self.textResultSequence.tag_config("normal" + str(i), background=colorHex) # red for codons with restriction sites (r, g, b) = colorsys.hsv_to_rgb(5 / 360, i / 100, 1.0) colorHex = "#%02x%02x%02x" % (int(r * 255), int(g * 255), int(b * 255)) self.textSourceSeq.tag_config("restrict" + str(i), background=colorHex) self.textResultSequence.tag_config("restrict" + str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError: # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ["A", "C", "G", "T"]) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal" + str(int(sc * 100))) # print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict" + str(int(sc * 100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode="w") as fd: fd.write(self.optimizer.optimizedSequence)
class NamedWindow(object): """ This creates a window for the Tkui which you can then write to programmatically. This allows modules to spin off new named windows and write to them. """ def __init__(self, windowname, master, partk): """ Initializes the window @param windowname: the name of the new window @type windowname: string @param master: the main tk window @type master: toplevel """ self._parent = master self._tk = Toplevel(partk) self._windowname = windowname # map of session -> (bold, foreground, background) self._currcolors = {} # ses -> string self._unfinishedcolor = {} self._do_i_echo = 1 self._tk.geometry("500x300") self._tk.title("Lyntin -- " + self._windowname) self._tk.protocol("WM_DELETE_WINDOW", self.close) if os.name == "posix": fontname = "Courier" else: fontname = "Fixedsys" fnt = tkinter.font.Font(family=fontname, size=12) self._txt = ScrolledText(self._tk, fg="white", bg="black", font=fnt, height=20) self._txt.pack(side=TOP, fill=BOTH, expand=1) # handles improper keypresses self._txt.bind("<KeyPress>", self._ignoreThis) # initialize color tags self._initColorTags() def convertColor(self, name): """ Tk has this really weird color palatte. So I switched to using color names in most cases and rgb values in cases where I couldn't find a good color name. This method allows me to specify either an rgb or a color name and it converts the color names to rgb. @param name: either an rgb value or a name @type name: string @returns: the rgb color value @rtype: string """ if name[0] == "#": return name rgb = self._tk._getints( self._tk.tk.call('winfo', 'rgb', self._txt, name)) rgb = "#%02x%02x%02x" % (old_div(rgb[0], 256), old_div( rgb[1], 256), old_div(rgb[2], 256)) print(name, "converted to: ", rgb) return rgb def _initColorTags(self): """ Sets up Tk tags for the text widget (fg/bg).""" for ck in list(fg_color_codes.keys()): color = self.convertColor(fg_color_codes[ck]) self._txt.tag_config(ck, foreground=color) for ck in list(bg_color_codes.keys()): self._txt.tag_config(ck, background=bg_color_codes[ck]) self._txt.tag_config("u", underline=1) def _ignoreThis(self, tkevent): """ This catches keypresses to this window. """ return "break" def close(self): """ Closes and destroys references to this window. """ self._parent.removeWindow(self._windowname) self._tk.destroy() def _yadjust(self): """Handles y scrolling after text insertion.""" self._txt.yview('moveto', '1') # if os.name != 'posix': self._txt.yview('scroll', '20', 'units') def _clipText(self): """ Scrolls the text buffer up so that the new text written at the bottom of the text buffer can be seen. """ temp = self._txt.index("end") ind = temp.find(".") temp = temp[:ind] if (temp.isdigit() and int(temp) > 800): self._txt.delete("1.0", "100.end") def write(self, msg): """ This writes text to the text buffer for viewing by the user. This is overridden from the 'base.BaseUI'. """ if type(msg) == tuple: msg = msg[0] if type(msg) == bytes: msg = message.Message(msg, message.LTDATA) line = msg.data ses = msg.session if line == '': return color, leftover = buffer_write(msg, self._txt, self._currcolors, self._unfinishedcolor) if msg.type == message.MUDDATA: self._unfinishedcolor[ses] = leftover self._currcolors[ses] = color self._clipText() self._yadjust()
class MarkovDemo(Frame): "MarkovDemo(master=None, **kw) -> MarkovDemo instance" TEXT = dict(height=2, width=46, wrap=WORD) # Text Options GRID = dict(padx=5, pady=5) # Grid Options # Initialize a MarkovDemo instance with a GUI for interaction. def __init__(self, master=None, **kw): "Initialize the MarkovDemo instance's widgets and settings." super().__init__(master, **kw) self.build_widgets() self.place_widgets() self.setup_widgets() self.grid_rowconfigure(2, weight=1) self.grid_rowconfigure(3, weight=1) self.grid_columnconfigure(0, weight=1) self.key = self.primer = None def build_widgets(self): "Build the various widgets that will be used in the program." # Create processing frame widgets. self.processing_frame = LabelFrame(self, text='Processing Mode:') self.mode_var = StringVar(self, 'encode') self.decode_button = Radiobutton(self.processing_frame, text='Decode Cipher-Text', command=self.handle_radiobuttons, value='decode', variable=self.mode_var) self.encode_button = Radiobutton(self.processing_frame, text='Encode Plain-Text', command=self.handle_radiobuttons, value='encode', variable=self.mode_var) self.freeze_var = BooleanVar(self, False) self.freeze_button = Checkbutton(self.processing_frame, text='Freeze Key & Primer', command=self.handle_checkbutton, offvalue=False, onvalue=True, variable=self.freeze_var) # Create encoding frame widgets. self.encoding_frame = LabelFrame(self, text='Encoding Options:') self.chain_size_label = Label(self.encoding_frame, text='Chain Size:') self.chain_size_entry = Entry(self.encoding_frame) self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:') self.plain_text_entry = Entry(self.encoding_frame) # Create input frame widgets. self.input_frame = LabelFrame(self, text='Input Area:') self.input_text = ScrolledText(self.input_frame, **self.TEXT) # Create output frame widgets. self.output_frame = LabelFrame(self, text='Output Area:') self.output_text = ScrolledText(self.output_frame, **self.TEXT) def place_widgets(self): "Place the widgets where they belong in the MarkovDemo frame." # Locate processing frame widgets. self.processing_frame.grid(sticky=EW, **self.GRID) self.decode_button.grid(row=0, column=0, **self.GRID) self.encode_button.grid(row=0, column=1, **self.GRID) self.freeze_button.grid(row=0, column=2, **self.GRID) # Locate encoding frame widgets. self.encoding_frame.grid(sticky=EW, **self.GRID) self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID) self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID) self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID) self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID) self.encoding_frame.grid_columnconfigure(1, weight=1) # Locate input frame widgets. self.input_frame.grid(sticky=NSEW, **self.GRID) self.input_text.grid(sticky=NSEW, **self.GRID) self.input_frame.grid_rowconfigure(0, weight=1) self.input_frame.grid_columnconfigure(0, weight=1) # Locate output frame widgets. self.output_frame.grid(sticky=NSEW, **self.GRID) self.output_text.grid(sticky=NSEW, **self.GRID) self.output_frame.grid_rowconfigure(0, weight=1) self.output_frame.grid_columnconfigure(0, weight=1) def setup_widgets(self): "Setup each widget's configuration for the events they handle." self.input_text.bind('<Key>', self.handle_key_events) self.input_text.bind('<Control-Key-a>', self.handle_control_a) self.input_text.bind('<Control-Key-/>', lambda event: 'break') self.output_text['state'] = DISABLED self.output_text.bind('<Control-Key-a>', self.handle_control_a) self.output_text.bind('<Control-Key-/>', lambda event: 'break') ######################################################################## # Take care of any special event needing dedicated processing. def handle_radiobuttons(self): "Change the interface based on the encoding / decoding setting." if self.encrypting: self.freeze_button.grid() if not self.freeze_var.get(): self.encoding_frame.grid() else: self.freeze_button.grid_remove() if not self.freeze_var.get(): self.encoding_frame.grid_remove() self.handle_key_events(None) def handle_checkbutton(self): "Change the interface based on the key / primer freeze setting." if self.freeze_var.get(): self.encoding_frame.grid_remove() else: self.encoding_frame.grid() def handle_key_events(self, event): "Schedule refreshing the output area after an input area event." if event is None or event.char and event.state | 0o11 == 0o11: self.after_idle(self.refresh) @staticmethod def handle_control_a(event): "Select all text in the widget associated with the given event." event.widget.tag_add(SEL, 1.0, END + '-1c') return 'break' ######################################################################## # Handle interface's updates when either encoding or decoding. def refresh(self): "Refresh the output based on the value of the input." text = self.input_text.get(1.0, END + '-1c') if not text: self.output = text elif self.encrypting: self.encode(text) else: self.decode(text) def output(self, value): "Set the text in the output area to the string value." self.output_text['state'] = NORMAL self.output_text.delete(1.0, END) self.output_text.insert(END, value) if self.encrypting and self.freeze_var.get(): self.output_text.see(END) self.output_text['state'] = DISABLED output = property(fset=output, doc='Output area property.') @property def chain_size(self): "Chain size for the Markov chains used when encrypting." try: value = ast.literal_eval(self.chain_size_entry.get()) assert isinstance(value, int) and 2 <= value <= 256 return value except: self.chain_size_entry.delete(0, END) self.chain_size_entry.insert(0, '2') return 2 @property def plain_text(self): "Plain text or ignored characters in encryption process." try: value = self.repr_to_obj(self.plain_text_entry.get(), '') assert isinstance(value, str) return value except: self.plain_text_entry.delete(0, END) return '' ######################################################################## # Encrypt a string for display in the interface's output area. def encode(self, string): "Encode the string and show the cipher-text in the output." try: cipher = self.build_cipher(string) except ValueError: self.output = '' except: self.output = traceback.format_exc() else: self.output = self.build_header() + '\n\n' + cipher def build_cipher(self, string): "Build cipher-text based on plain-text and return answer." if self.key and self.freeze_var.get(): cipher, primer = me.encrypt_str(string, self.key, self.primer) else: args = string, self.chain_size, self.plain_text cipher, self.key, self.primer = me.auto_encrypt_str(*args) return cipher def build_header(self): "Build header from key and primer values in current use." header = '\n'.join(map(self.bytes_to_repr, self.key.data)) header += '\n' + self.bytes_to_repr(self.primer.data) return header ######################################################################## # Decrypt a string for display in the interface's output area. def decode(self, string): "Decode encrypted message and display plain-text in output." try: cipher = self.extract_keys(string) text = self.extract_text(cipher) except ValueError: self.output = '' except: self.output = traceback.format_exc() else: self.output = text def extract_keys(self, string): "Extract keys to decryption and return the cipher-text area." header, cipher = string.split('\n\n', 1) *key, primer = map(self.repr_to_obj, header.split('\n')) self.key, self.primer = me.Key(tuple(key)), me.Primer(primer) return cipher def extract_text(self, string): "Extract text message from string using built key and primer." text, primer = me.decrypt_str(string, self.key, self.primer) return text ######################################################################## # Provide some special methods to simplify the program's code. @property def encrypting(self): "Encrypting boolean stating current operations mode." return {'encode': True, 'decode': False}[self.mode_var.get()] @staticmethod def bytes_to_repr(obj): "Convert bytes object into suitable representation." if not isinstance(obj, bytes): raise TypeError('Object must be a bytes instance!') return repr(obj)[2:-1] @staticmethod def repr_to_obj(string, prefix='b'): "Convert representation into an equivalent object." for template in '{}"{}"', "{}'{}'": try: return ast.literal_eval(template.format(prefix, string)) except: pass raise ValueError('Cannot convert {!r} to object!'.format(string)) @classmethod def main(cls): "Create context for demo and run a test instance." NoDefaultRoot() root = Tk() root.minsize(420, 330) root.title('Markov Demo 2') test = cls(root) test.grid(sticky=NSEW) root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) root.mainloop()
class MarkovDemo: def __init__(self, master): self.prompt_size = Label(master, anchor=W, text='Encode Word Size') self.prompt_size.pack(side=TOP, fill=X) self.size_entry = Entry(master) self.size_entry.insert(0, '8') self.size_entry.pack(fill=X) self.prompt_plain = Label(master, anchor=W, text='Plaintext Characters') self.prompt_plain.pack(side=TOP, fill=X) self.plain_entry = Entry(master) self.plain_entry.insert(0, '""') self.plain_entry.pack(fill=X) self.showframe = Frame(master) self.showframe.pack(fill=X, anchor=W) self.showvar = StringVar(master) self.showvar.set("encode") self.showfirstradio = Radiobutton(self.showframe, text="Encode Plaintext", variable=self.showvar, value="encode", command=self.reevaluate) self.showfirstradio.pack(side=LEFT) self.showallradio = Radiobutton(self.showframe, text="Decode Cyphertext", variable=self.showvar, value="decode", command=self.reevaluate) self.showallradio.pack(side=LEFT) self.inputbox = ScrolledText(master, width=60, height=10, wrap=WORD) self.inputbox.pack(fill=BOTH, expand=1) self.dynamic_var = IntVar() self.dynamic_box = Checkbutton(master, variable=self.dynamic_var, text='Dynamic Evaluation', offvalue=False, onvalue=True, command=self.reevaluate) self.dynamic_box.pack() self.output = Label(master, anchor=W, text="This is your output:") self.output.pack(fill=X) self.outbox = ScrolledText(master, width=60, height=10, wrap=WORD) self.outbox.pack(fill=BOTH, expand=1) self.inputbox.bind('<Key>', self.reevaluate) def select_all(event=None): event.widget.tag_add(SEL, 1.0, 'end-1c') event.widget.mark_set(INSERT, 1.0) event.widget.see(INSERT) return 'break' self.inputbox.bind('<Control-Key-a>', select_all) self.outbox.bind('<Control-Key-a>', select_all) self.inputbox.bind('<Control-Key-/>', lambda event: 'break') self.outbox.bind('<Control-Key-/>', lambda event: 'break') self.outbox.config(state=DISABLED) def reevaluate(self, event=None): if event is not None: if event.char == '': return if self.dynamic_var.get(): text = self.inputbox.get(1.0, END)[:-1] if len(text) < 10: return text = text.replace('\n \n', '\n\n') mode = self.showvar.get() assert mode in ('decode', 'encode'), 'Bad mode!' if mode == 'encode': # Encode Plaintext try: # Evaluate the plaintext characters plain = self.plain_entry.get() if plain: PC = eval(self.plain_entry.get()) else: PC = '' self.plain_entry.delete(0, END) self.plain_entry.insert(0, '""') # Evaluate the word size size = self.size_entry.get() if size: XD = int(size) while grid_size(text, XD, PC) > 1 << 20: XD -= 1 else: XD = 0 grid = 0 while grid <= 1 << 20: grid = grid_size(text, XD, PC) XD += 1 XD -= 1 # Correct the size and encode self.size_entry.delete(0, END) self.size_entry.insert(0, str(XD)) cyphertext, key, prime = encrypt_str(text, XD, PC) except: traceback.print_exc() else: buffer = '' for block in key: buffer += repr(block)[2:-1] + '\n' buffer += repr(prime)[2:-1] + '\n\n' + cyphertext self.outbox.config(state=NORMAL) self.outbox.delete(1.0, END) self.outbox.insert(END, buffer) self.outbox.config(state=DISABLED) else: # Decode Cyphertext try: header, cypher = text.split('\n\n', 1) lines = header.split('\n') for index, item in enumerate(lines): try: lines[index] = eval('b"' + item + '"') except: lines[index] = eval("b'" + item + "'") plain = decrypt_str(cypher, tuple(lines[:-1]), lines[-1]) except: traceback.print_exc() else: self.outbox.config(state=NORMAL) self.outbox.delete(1.0, END) self.outbox.insert(END, plain) self.outbox.config(state=DISABLED) else: text = self.inputbox.get(1.0, END)[:-1] text = text.replace('\n \n', '\n\n') mode = self.showvar.get() assert mode in ('decode', 'encode'), 'Bad mode!' if mode == 'encode': try: XD = int(self.size_entry.get()) PC = eval(self.plain_entry.get()) size = grid_size(text, XD, PC) assert size except: pass else: buffer = 'Grid size will be:\n' + convert(size) self.outbox.config(state=NORMAL) self.outbox.delete(1.0, END) self.outbox.insert(END, buffer) self.outbox.config(state=DISABLED)
def onEvent(i): myname = 'thread-%s' % i startThread(action=threadaction, args=(i, 3), context=(myname, ), onExit=threadexit, onFail=threadfail, onProgress=threadprogress) def threadaction(id, reps, progress): for i in range(reps): time.sleep(1) if progress: progress(i) if id % 2 == 1: raise Exception def threadexit(myname): text.insert('end', '%s\texit\n' % myname) text.see('end') def threadfail(exc_info, myname): text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0])) text.see('end') def threadprogress(count, myname): text.insert('end', '%s\tprog\t%s\n' % (myname, count)) text.see('end') text.update() text=ScrolledText() text.pack() threadChecker(text) text.bind('<Button-1>', lambda event: list(map(onEvent, range(6)))) text.mainloop()
class SpinDelight(Frame): def __init__(self): Frame.__init__(self) self.master.geometry("1020x600+150+50") self.master.title("Spin Delight 1.0 - Copyright (c) Robin Thomas") self.master.resizable(0,0) self.grid() self.brwe = Button(self, text = "Browse", command = self.open_file, width = 10, relief = "groove") self.rtxt = Label(self, text="Input Text:") self.txt1 = ScrolledText(self, width = 50, height = 25) self.txt1.bind("<Control-Key-a>", self.select_all_txt1) self.txt1.bind("<Control-Key-A>", self.select_all_txt1) self.spin = Button(self, text = "Spin", command = self.spin_file, width = 10, relief = "groove") self.stxt = Label(self, text="Spun Text:") self.txt2 = ScrolledText(self, width = 50, height = 25) self.txt2.bind("<Control-Key-a>", self.select_all_txt2) self.txt2.bind("<Control-Key-A>", self.select_all_txt2) self.brwe.grid(row = 2, column = 2, pady = 15) self.rtxt.grid(row = 2, column = 0, padx = 25) self.txt1.grid(row = 3, column = 0, columnspan = 10, padx = 25) self.spin.grid(row = 3, column = 12) self.stxt.grid(row = 2, column = 13, padx = 25, pady = 5) self.txt2.grid(row = 3, column = 13, columnspan = 10, padx = 25) def select_all_txt1(self,event): self.txt1.tag_add(SEL, "1.0", END) self.txt1.mark_set(INSERT, "1.0") self.txt1.see(INSERT) return 'break' def select_all_txt2(self,event): self.txt2.tag_add(SEL, "1.0", END) self.txt2.mark_set(INSERT, "1.0") self.txt2.see(INSERT) return 'break' def open_file(self): fname = askopenfilename(filetypes=(("Text files", "*.txt"), ("All files", "*.*") )) if fname: try: self.txt1.delete(0.0, END) f = open(fname,'r') self.txt1.insert(INSERT,f.read()) except: showerror("Open Source File", "Failed to read file\n'%s'" % fname) def spin_file(self): txt = self.txt1.get("1.0", END) self.txt2.delete(0.0, END) if len(txt): try: words = sub(r'([.,?])+', r' \1 ', sub(r'[^a-zA-Z0-9 .,?]+', ' ', txt)).split() w1 = words[0] z = [(words[j - 1], words[j]) for j in range(1, len(words))] values = self.generate_dict(z, w1) string = self.generate_sent(values) if len(string): self.txt2.insert(INSERT, string) else: showerror("Error", "Insufficient data to spin !!") except: showerror("Error", "Nothing to spin !!") def generate_dict(self, x, w1): values = {'.': [w1]} for (wa, wb) in x: if wa in values: values[wa].append(wb) else: values[wa] = [wb] return values def generate_sent(self, values): w1 = '.' w2 = choice(values[w1]) string = w2 values[w1].remove(w2) while values: w1 = w2 if len(values[w1]): w2 = choice(values[w1]) else: del values[w1] w1 = '.' break if w2 in ('.', ',', '?'): string += w2 else: string += " " + w2 values[w1].remove(w2) return string
class MoMakeApp(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() cfg_file = '%s/momake.cfg.json' % (tempfile.gettempdir()) self.cfg = Config(cfg_file) self.master.title('MoMake v0.3') self.master.geometry('740x480') self.master.resizable(0, 0) self.src_path = StringVar() self.src_path.set(self.cfg.get('src')) self.dst_path = StringVar() self.dst_path.set(self.cfg.get('dst')) self.env = StringVar() self.env.set(self.cfg.get('env') or 'test') ft = tkFont.Font(family='微软雅黑', size=12) row_span = 20 Label(self, text="代码路径: ", font=ft).grid(row=0, sticky=E, pady=row_span) e = Entry(self, font=ft, width=60, textvariable=self.src_path) e.grid(row=0, column=1, sticky=W, columnspan=4) e.bind('<KeyPress>', lambda e: 'break') # 禁止输入 self.chooseSrcPath = Button(self, text="选择...", font=ft, command=self.__chooseSrcPath) self.chooseSrcPath.grid(row=0, column=5, sticky=E, padx=15) Label(self, text="输出路径: ", font=ft).grid(row=1, sticky=E) e = Entry(self, font=ft, width=60, textvariable=self.dst_path) e.grid(row=1, column=1, sticky=W, columnspan=4) e.bind('<KeyPress>', lambda e: 'break') # 禁止输入 self.chooseDistPath = Button(self, text="选择...", height=1, font=ft, command=self.__chooseDstPath) self.chooseDistPath.grid(row=1, column=5, sticky=E, padx=15) Label(self, text="环境: ", font=ft).grid(row=2, sticky=E) #Radiobutton(self, text='开发环境', value='dev', variable=self.env, font=ft).grid(row=2, sticky=W, column=1) self.radioEnvTest = Radiobutton(self, text='测试环境', value='test', variable=self.env, font=ft) self.radioEnvTest.grid(row=2, sticky=W, column=1) self.radioEnvRelease = Radiobutton(self, text='正式环境', value='release', variable=self.env, font=ft) self.radioEnvRelease.grid(row=2, sticky=W, column=2) self.create = Button(self, text="生成小程序", font=ft, width=20, height=1, command=self.__create) self.create.grid(row=3, column=0, columnspan=6, pady=row_span) self.create['state'] = DISABLED self.output = ScrolledText(self, borderwidth=1, width=98, height=19) self.output.bind('<KeyPress>', lambda e: 'break') # 禁止输入 self.output.grid(row=4, column=0, columnspan=6) self.__refreshState() def __chooseSrcPath(self): path = askdirectory(initialdir=self.src_path.get(), title='请选择python代码文件夹') if path: self.src_path.set(path) self.__output('choose src path:%s' % path) self.__refreshState() def __chooseDstPath(self): path = askdirectory(initialdir=self.dst_path.get(), title='请选择小程序输出文件夹') if path: self.dst_path.set(path) self.__output('choose dst path:%s' % path) self.__refreshState() def __refreshState(self): if os.path.isdir(self.src_path.get()) and os.path.isdir( self.dst_path.get()): self.create['state'] = NORMAL else: self.create['state'] = DISABLED def __output(self, text): if text[0:1] != '\t': if text != '': text = '%s %s' % (time.strftime("%H:%M:%S", time.localtime()), text) else: text = text.replace('\t', ' ') self.output.insert(END, text) self.output.insert(END, '\n') self.output.see(END) def onFinish(self): self.__output('') self.create['state'] = NORMAL self.create['text'] = '生成小程序' self.chooseSrcPath['state'] = NORMAL self.chooseDistPath['state'] = NORMAL self.radioEnvTest['state'] = NORMAL self.radioEnvRelease['state'] = NORMAL def __create(self): self.output.delete(1.0, END) self.cfg.set('src', self.src_path.get()) self.cfg.set('dst', self.dst_path.get()) self.cfg.set('env', self.env.get()) self.create['state'] = DISABLED self.chooseSrcPath['state'] = DISABLED self.chooseDistPath['state'] = DISABLED self.radioEnvTest['state'] = DISABLED self.radioEnvRelease['state'] = DISABLED self.create['text'] = '制作中,请稍后...' t = TaskThread(self.src_path.get(), self.dst_path.get(), self.env.get(), self.__output, self.onFinish) t.start()
class VentanaContador: def __init__(self): self.html_table = "" self.cabecera = ('N', 'Verso', 'Etiquetado', "Sílabas", "Acentos", 'Sin extrarrítmicos', 'Tipo', 'Coincidencia') self.dibujar() def dibujar(self): self.root = Tk() self.root.title("Jumper: Contador de sílabas y acentos en tiempo real") # Group0 Frame ---------------------------------------------------- group0 = LabelFrame(self.root, text="Tendencia versal", padx=2, pady=2) group0.grid(row=0, column=0, columnspan=2, padx=5, pady=5, sticky=N + E + W + S) group0.rowconfigure(0, weight=1) group0.columnconfigure(0, weight=1) # Create the textbox self.trend = Entry(group0, width=50, font=("Verdana", 11)) self.trend.grid(row=0, column=0, sticky=E + W + N + S) # Group1 Frame ---------------------------------------------------- group1 = LabelFrame(self.root, text="Poema", padx=2, pady=2) group1.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky=N + E + W + S) group1.rowconfigure(0, weight=1) group1.columnconfigure(0, weight=1) # Create the textbox self.txt_origen = ScrolledText(group1, width=80, height=10, font=("Times New Roman", 12)) self.txt_origen.grid(row=0, column=0, sticky=E + W + N + S) # Group2 Frame ---------------------------------------------------- group2 = LabelFrame(self.root, text="Análisis", padx=2, pady=2) group2.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky=N + E + W + S) group2.rowconfigure(1, weight=1) group2.columnconfigure(0, weight=1) # Create the textbox self.txt_destino = ttk.Treeview(group2, height=25, columns=self.cabecera, show='headings') vsb = ttk.Scrollbar(group2, orient="vertical", command=self.txt_destino.yview) vsb.configure(command=self.txt_destino.yview) self.txt_destino.configure(yscrollcommand=vsb.set) # set column headings tamanios = (50, 400, 400, 80, 180, 180, 350, 100) for i, col in enumerate(self.cabecera): self.txt_destino.heading(col, text=col) self.txt_destino.column(col, minwidth=0, width=tamanios[i], stretch=NO) self.txt_destino.tag_configure('green', foreground='green') self.txt_destino.tag_configure('red', foreground='red') self.txt_destino.tag_configure('black', foreground='black') vsb.grid(row=1, column=3, sticky=N + S) self.txt_destino.grid(row=1, column=0, sticky=E + W + N + S) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(1, weight=1) # Menu menubar = Menu(self.root) self.root.config(menu=menubar) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Guardar análisis", command=self.onSave) filemenu.add_command(label="Limpiar texto", command=self.clearText) filemenu.add_separator() filemenu.add_command(label="Salir", command=self.root.quit) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Cómo se usa", command=self.popupmsgHelp) helpmenu.add_separator() helpmenu.add_command(label="Acerca de...", command=self.popupmsgAbout) analisismenu = Menu(menubar, tearoff=0) analisismenu.add_command(label="Analizar poema", command=self.put_text_in_txt_destino_menu) menubar.add_cascade(label="Archivo", menu=filemenu) menubar.add_cascade(label="Análisis", menu=analisismenu) menubar.add_cascade(label="Ayuda", menu=helpmenu) self.txt_origen.bind('<Button-3>', self.rClicker, add='') self.txt_origen.bind('<KeyPress>', self.put_text_in_txt_destino_on_key) self.txt_origen.focus() self.statusbar = Label(self.root, text="", bd=1, relief=SUNKEN, anchor='e', justify=LEFT) self.statusbar.grid(row=3, column=0, columnspan=2) # https://stackoverflow.com/questions/4266566/stardand-context-menu-in-python-tkinter-text-widget-when-mouse-right-button-is-p def rClicker(self, e): try: def rClick_Copy(e, apnd=0): e.widget.event_generate('<Control-c>') def rClick_Cut(e): e.widget.event_generate('<Control-x>') def rClick_Paste(e): e.widget.event_generate('<Control-v>') e.widget.focus() nclst = [ (' Cortar', lambda e=e: rClick_Cut(e)), (' Copiar', lambda e=e: rClick_Copy(e)), (' Pegar', lambda e=e: rClick_Paste(e)), ] rmenu = Menu(None, tearoff=0, takefocus=0) for (txt, cmd) in nclst: rmenu.add_command(label=txt, command=cmd) rmenu.tk_popup(e.x_root + 40, e.y_root + 10, entry="0") except TclError: print(' - rClick menu, something wrong') pass return "break" def show(self, x, colores): self.txt_destino.delete(*self.txt_destino.get_children()) for i, (v, v_etiquetado, v_silabas, v_acentos, v_extra, v_tipo, v_coin) in enumerate(x): self.txt_destino.insert("", "end", values=(i + 1, v, v_etiquetado, v_silabas, str(v_acentos), str(v_extra), v_tipo, v_coin), tags=(colores[i], )) def put_text_in_txt_destino_on_key(self, event): t = threading.Thread(target=self.put_text_in_txt_destino(), args=(self, )) del (t) def put_text_in_txt_destino_menu(self): t = threading.Thread(target=self.put_text_in_txt_destino(), args=(self, )) del (t) def put_text_in_txt_destino(self): fetched_content = self.txt_origen.get('1.0', 'end-1c') try: x = jumper.escandir_texto(fetched_content) columna_silabas_v = list(map(list, zip(*x)))[2] versos_frecuentes = jumper.most_frequent(columna_silabas_v) except: return None tendencia_versal = self.trend.get().strip().strip(',').split(',') # si hay tendencia versal operamos con ella if tendencia_versal[0] != '' and tendencia_versal[0].find( 'Auto') == -1: tendencia_versal = [ int(i) for i in tendencia_versal ] if len(tendencia_versal) > 0 and self.RepresentsInt( tendencia_versal[0]) else [] else: tendencia_versal = list(versos_frecuentes.keys()) self.trend.delete(0, END) self.trend.insert( 0, 'Auto: ' + str(tendencia_versal).replace(']', '').replace('[', '')) precision = 0 colores = [] self.html_table = '<table width="100%" style="margin: 0px;font-size: 11pt;font-family: Courier;">' self.html_table += '<tr>' for item in self.cabecera: self.html_table += '<th style="text-align: left;">' + item + '</th>' self.html_table += '</tr>' for i, v in enumerate(x): silabas_v = v[2] # se convierte a porcetaje v[-1] = int(v[-1] * 100) if len(tendencia_versal) > 0: if silabas_v in tendencia_versal and v[-1] == 100: precision += 1 color = 'green' elif silabas_v in tendencia_versal: precision += 1 color = 'black' else: color = 'red' colores.append(color) self.html_table += '<tr style="color:' + color + '">' self.html_table += '<td>' + str(i) + '</td>' for item in v: self.html_table += '<td>' + str(item) + '</td>' self.html_table += '</tr>' self.html_table += '</table><br>' self.html_table += 'Tendencia versal: ' + str( tendencia_versal) + '<br>' calidad, regularidad = self.calcular_calidad_precision( x, versos_frecuentes) #imprimimos regularidad y precision resumen_precision = f"Precisión de los acentos: {calidad:.1f}% Regularidad con los versos más frecuentes: {regularidad:.1f}%" self.statusbar['text'] = resumen_precision self.html_table += resumen_precision self.show(x, colores) #self.txt_destino.set_content(self.html_table) def calcular_calidad_precision(self, analisis, versos_frecuentes): calidad = 0 regularidad = 0 for verso_analizado in analisis: ratio = verso_analizado[-1] silabas = verso_analizado[2] if ratio == 100: calidad += 1 if silabas in versos_frecuentes: regularidad += 1 return (calidad / len(analisis)) * 100, (regularidad / len(analisis)) * 100 def popupgen(self, title, msg): popup = Tk() popup.wm_title(title) label = Label(popup, text=msg) label.pack(side="top", fill="x", pady=15) B1 = Button(popup, text="Ok", command=popup.destroy) B1.pack() popup.mainloop() def popupmsgAbout(self): msg = 'Analizador automático de métrica por Guillermo Marco Remón.\n nlp.uned.es, Research Group in NLP & IR, UNED, Madrid, Spain.\n Las tipologías de verso empleadas se han extraído de Pou, P. J. (2020). Métrica española. Ediciones Cátedra. \n Si detecta cualquier error escriba a [email protected]' title = "Acerca de... Versión 21122020" self.popupgen(title, msg) def popupmsgHelp(self): msg = 'Pegue o escriba el poema en la sección "Poema",\nel análisis métrico se hará automáticamente. \nLa tendencia versal se calculará también automáticamente.\n Si lo desea, puede establecerla manualmente separada por comas en la caja de texto: ej.: 14, 11, 7' title = 'Modo de empleo' self.popupgen(title, msg) def clearText(self): self.txt_origen.delete('1.0', END) def onSave(self): home = os.path.expanduser('~') path = filedialog.asksaveasfilename(initialdir=home, title="Guardar como", filetypes=(("html", "*.html"), ("All files", "*.*"))) textFile = open(path + '.html', 'w') textFile.write(self.html_table) textFile.close() def RepresentsInt(self, s): try: int(s) return True except ValueError: return False def lanzar(self): self.root.mainloop()
try: import tkinter from tkinter.scrolledtext import ScrolledText top = tkinter.Tk() try: s = top.clipboard_get() except: s = '' ent = ScrolledText(top) ent.pack(fill='both', expand=True) ent.insert(1.0, s) ent.bind('<KeyRelease>', refresh) top.protocol("WM_DELETE_WINDOW", close) refresh() top.mainloop() except Exception as e: print('import tkinter failure.') s = '' while s.lower() != 'q': s = input("input line(s): (press 'q' exit) ") data = store.add(s) if not file_decode(data, log): with open(log, 'a') as f:
class Client_mainUI(object): global clientSock global nick def __init__(self, master=None): self.root = master self.root.iconbitmap('weixin.ico') self.frame = [Tkinter.Frame(),Tkinter.Frame(),Tkinter.Frame(),Tkinter.Frame()] self.nick = nick self.sock = clientSock self.outString = '' self.inString = '' self.root.title('Enjoy chatting, ' + self.nick) #显示消息Text右边的滚动条 # self.chatTextScrollBar = Tkinter.Scrollbar(self.frame[0]) # self.chatTextScrollBar.pack(side=Tkinter.RIGHT,fill=Tkinter.Y) #显示消息Text,并绑定上面的滚动条 ft = tkFont.Font(family='微软雅黑',size=11) self.chatText = ScrolledText(self.frame[0],width=70,height=18,font=ft) self.chatText.pack(expand=1,fill=Tkinter.BOTH) self.frame[0].pack(expand=1,fill=Tkinter.BOTH) #标签,分开消息显示Text和消息输入Text label = Tkinter.Label(self.frame[1],height=1) label.pack(fill=Tkinter.BOTH) self.frame[1].pack(expand=1,fill=Tkinter.BOTH) #输入消息Text的滚动条 # self.inputTextScrollBar = Tkinter.Scrollbar(self.frame[2]) # self.inputTextScrollBar.pack(side=Tkinter.RIGHT,fill=Tkinter.Y) #输入消息Text,并与滚动条绑定 ft = tkFont.Font(family='微软雅黑',size=11) self.inputText = ScrolledText(self.frame[2],width=70,height=8,font=ft) self.inputText.pack(expand=1,fill=Tkinter.BOTH) self.inputText.bind("<Control-Return>", self.dataout) self.frame[2].pack(expand=1,fill=Tkinter.BOTH) #发送消息按钮 ft = tkFont.Font(family='微软雅黑', size=8) self.sendButton=Tkinter.Button(self.frame[3],text='Send (Ctrl+Enter)',width=15,height=2,font=ft, background='white', activebackground='black', activeforeground='white', command=self.dataout) self.sendButton.pack(expand=1, padx=15,pady=8, anchor=Tkinter.E) # 发送图片按钮 # self.img_button = Tkinter.Button(self.frame[3], text='发送图片', width=10, command=self.send_image) # self.img_button.pack(expand=1, side=Tkinter.BOTTOM and Tkinter.LEFT, padx=15, pady=8) self.frame[3].pack(expand=1, fill=Tkinter.BOTH) def modified(self): self.chatText.yview_moveto(1) # 发送信息的函数 def DealOut(self): temp = self.inputText.get('1.0',Tkinter.END) if re.sub('\s+', '', temp) == '': # 整个输入都是空白字符 showinfo(title='error', message='empty message!') else: self.outString = re.sub('\n+$', '', temp) self.outString = nick + ':' + self.outString # 拼接cd try: self.sock.sendall(bytes(self.outString, encoding='utf-8')) # 发送 except: print("server error") showinfo(title='error', message='server error') os._exit(1) self.inputText.delete(0.0, self.outString.__len__() - 1.0) # 发送完后清空输入框 # 接收信息 def DealIn(self): while True: try: self.inString = str(self.sock.recv(1024), encoding='utf-8') if not self.inString: break """ if "send an image" in self.inString: while True: temp = str(self.sock.recv(1024), encoding='utf-8') if not temp: break self.inString += temp self.inString = re.sub(r'^.*send an image', '', self.inString) self.chatText.image_create(Tkinter.END, image=ImageTk.PhotoImage(data=self.inString)) else: """ if self.inString == self.outString: self.inString = self.inString.replace(nick, "me", 1) theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) try: user, mess = self.inString.split(':', 1) if user == 'robot': self.chatText.tag_config("tag_1", foreground="blue") self.chatText.insert(Tkinter.END, user + ':' + theTime + '\n', 'tag_1') self.chatText.insert(Tkinter.END, mess + '\n\n', 'tag_1') else: self.chatText.insert(Tkinter.END, user + ':' + theTime + '\n') self.chatText.insert(Tkinter.END, mess + '\n\n') self.modified() except: self.chatText.insert(Tkinter.END, theTime + ' \n') self.chatText.insert(Tkinter.END, self.inString + '\n\n') self.modified() print(self.inString) except: break def datain(self): thin = threading.Thread(target=self.DealIn) # 调用threading 创建一个接收信息的线程' thin.start() def dataout(self, _=None): thout = threading.Thread(target=self.DealOut) # 创建一个发送信息的线程,声明是一个元组 thout.start()
m = Menu(window, tearoff=0) m.add_command(label="Copy", command=copy) m.add_command(label="Reload", command=get_website) m.add_separator() m.add_command(label="Pass") def do_popup(event): try: m.tk_popup(event.x_root, event.y_root) finally: m.grab_release() website_body_text.bind("<Button-3>", do_popup) def paste(): try: print(window.clipboard_get()) search.insert(tk.END, str(window.clipboard_get())) except: window.clipboard_append("") n = Menu(window, tearoff=0) n.add_command(label="Paste", command=paste) n.add_separator() n.add_command(label="Pass")
fontMenu = Menu(menubar, tearoff=0, bg="#b0b0b0", fg="black") # Menu Bar File Option Attribs. menubar.add_cascade(label='File', menu=fileMenu) fileMenu.add_command(label='Save Ctrl+S', command=saveFile) fileMenu.add_command(label='Save As Ctrl+Shift+S', command=saveasFile) fileMenu.add_command(label='Open Ctrl+O', command=openFile) fileMenu.add_separator() fileMenu.add_command(label='Exit Ctrl+Q', command=onClose) # Menu Bar Theme Option Attribs. menubar.add_command(label="Theme", command=dark) fontMenu.add_command(label="Font", command=font) menubar.add_cascade(label='Format', menu=fontMenu) menubar.add_cascade(label='About', command=about) base.config(menu=menubar) # Binding Keyboard combos base.bind('<Control-s>', saveFile) base.bind('<Control-S>', saveasFile) base.bind('<Control-o>', openFile) base.bind('<Control-q>', onClose) base.bind('<Control-T>', dark) # base.bind('<Key>', auto) textField.bind('<Control-BackSpace>', lastwrdDel) base.protocol("WM_DELETE_WINDOW", onClose) # Running the main tkinter window base.mainloop()
class Tkui(base.BaseUI): """ This is a ui class which handles the complete Tk user interface. """ def __init__(self): """ Initializes.""" base.BaseUI.__init__(self) # internal ui queue self._event_queue = queue.Queue() # map of session -> (bold, foreground, background) self._currcolors = {} # ses -> string self._unfinishedcolor = {} self._viewhistory = 0 self._do_i_echo = 1 # holds a map of window names -> window references self._windows = {} # instantiate all the widgets self._tk = Tk() self._tk.geometry("800x600") self.settitle() fnt = tkinter.font.Font(family="FixedSys", size=10) self._entry = CommandEntry(self._tk, self, fg='white', bg='black', insertbackground='yellow', font=fnt, insertwidth='2') self._entry.pack(side='bottom', fill='both') self._topframe = Frame(self._tk) self._topframe.pack(side='top', fill='both', expand=1) self._txt = ScrolledText(self._topframe, fg='white', bg='black', font=fnt, height=20) self._txt.pack(side='bottom', fill='both', expand=1) self._txt.bind("<KeyPress>", self._ignoreThis) self._txtbuffer = ScrolledText(self._topframe, fg='white', bg='black', font=fnt, height=20) self._txtbuffer.bind("<KeyPress-Escape>", self.escape) self._txtbuffer.bind("<KeyPress>", self._ignoreThis) self._entry.focus_set() self._initColorTags() self.dequeue() exported.hook_register("config_change_hook", self.configChangeHandler) exported.hook_register("to_user_hook", self.write) # FIXME - fix this explanation. this is just terrible. tc = config.BoolConfig( "saveinputhighlight", 0, 1, "Allows you to change the behavior of the command entry. When " "saveinputhighlight is off, we discard whatever is on the entry " "line. When it is on, we will retain the contents allowing you " "to press the enter key to do whatever you typed again.") exported.add_config("saveinputhighlight", tc) self._quit = 0 def runui(self): global HELP_TEXT exported.add_help("tkui", HELP_TEXT) exported.write_message("For tk help type \"#help tkui\".") exported.add_command("colorcheck", colorcheck_cmd) # run the tk mainloop here self._tk.mainloop() def wantMainThread(self): # The tkui needs the main thread of execution so we return # a 1 here. return 1 def quit(self): if not self._quit: self._quit = 1 self._topframe.quit() def dequeue(self): qsize = self._event_queue.qsize() if qsize > 10: qsize = 10 for i in range(qsize): ev = self._event_queue.get_nowait() ev.execute(self) self._tk.after(25, self.dequeue) def settitle(self, title=""): """ Sets the title bar to the Lyntin title plus the given string. @param title: the title to set @type title: string """ if title: title = constants.LYNTINTITLE + title else: title = constants.LYNTINTITLE self._event_queue.put(_TitleEvent(self._tk, title)) def removeWindow(self, windowname): """ This removes a NamedWindow from our list of NamedWindows. @param windowname: the name of the window to write to @type windowname: string """ if windowname in self._windows: del self._windows[windowname] def writeWindow(self, windowname, message): """ This writes to the window named "windowname". If the window does not exist, we spin one off. It handles ansi text and messages just like writing to the main window. @param windowname: the name of the window to write to @type windowname: string @param message: the message to write to the window @type message: string or Message instance """ self._event_queue.put(_WriteWindowEvent(windowname, message)) def writeWindow_internal(self, windowname, message): if windowname not in self._windows: self._windows[windowname] = NamedWindow(windowname, self, self._tk) self._windows[windowname].write(message) def _ignoreThis(self, tkevent): """ This catches keypresses from the history buffer.""" # kludge so that ctrl-c doesn't get caught allowing windows # users to copy the buffer.... if tkevent.keycode == 17 or tkevent.keycode == 67: return self._entry.focus() if tkevent.char: # we do this little song and dance so as to pass events # we don't want to deal with to the entry widget essentially # by creating a new event and tossing it in the event list. # it only sort of works--but it's the best code we've got # so far. args = ('event', 'generate', self._entry, "<KeyPress>") args = args + ('-rootx', tkevent.x_root) args = args + ('-rooty', tkevent.y_root) args = args + ('-keycode', tkevent.keycode) args = args + ('-keysym', tkevent.keysym) self._tk.tk.call(args) return "break" def pageUp(self): """ Handles prior (Page-Up) events.""" if self._viewhistory == 0: self._txtbuffer.pack(side='top', fill='both', expand=1) self._viewhistory = 1 self._txtbuffer.delete("1.0", "end") lotofstuff = self._txt.get('1.0', 'end') self._txtbuffer.insert('end', lotofstuff) for t in self._txt.tag_names(): taux = None tst = 0 for e in self._txt.tag_ranges(t): if tst == 0: taux = e tst = 1 else: tst = 0 self._txtbuffer.tag_add(t, str(taux), str(e)) self._txtbuffer.yview('moveto', '1') if os.name != 'posix': self._txtbuffer.yview('scroll', '20', 'units') self._tk.update_idletasks() self._txt.yview('moveto', '1.0') if os.name != 'posix': self._txt.yview('scroll', '220', 'units') else: # yscroll up stuff self._txtbuffer.yview('scroll', '-15', 'units') def pageDown(self): """ Handles next (Page-Down) events.""" if self._viewhistory == 1: # yscroll down stuff self._txtbuffer.yview('scroll', '15', 'units') def escape(self, tkevent): """ Handles escape (Escape) events.""" if self._viewhistory == 1: self._txtbuffer.forget() self._viewhistory = 0 else: self._entry.clearInput() def configChangeHandler(self, args): """ This handles config changes including mudecho. """ name = args["name"] newvalue = args["newvalue"] if name == "mudecho": if newvalue == 1: # echo on self._do_i_echo = 1 self._entry.configure(show='') else: # echo off self._do_i_echo = 0 self._entry.configure(show='*') def _yadjust(self): """Handles y scrolling after text insertion.""" self._txt.yview('moveto', '1') # if os.name != 'posix': self._txt.yview('scroll', '20', 'units') def _clipText(self): """ Scrolls the text buffer up so that the new text written at the bottom of the text buffer can be seen. """ temp = self._txt.index("end") ind = temp.find(".") temp = temp[:ind] if (temp.isdigit() and int(temp) > 800): self._txt.delete("1.0", "100.end") def write(self, args): """ This writes text to the text buffer for viewing by the user. This is overridden from the 'base.BaseUI'. """ self._event_queue.put(_OutputEvent(args)) def write_internal(self, args): mess = args["message"] if type(mess) == bytes: mess = message.Message(mess, message.LTDATA) elif "window" in mess.hints: self.writeWindow_internal(mess.hints["window"], mess) return line = mess.data ses = mess.session if line == '' or self.showTextForSession(ses) == 0: return color, leftover = buffer_write(mess, self._txt, self._currcolors, self._unfinishedcolor) if mess.type == message.MUDDATA: self._unfinishedcolor[ses] = leftover self._currcolors[ses] = color self._clipText() self._yadjust() def convertColor(self, name): """ Tk has this really weird color palatte. So I switched to using color names in most cases and rgb values in cases where I couldn't find a good color name. This method allows me to specify either an rgb or a color name and it converts the color names to rgb. @param name: either an rgb value or a name @type name: string @returns: the rgb color value @rtype: string """ if name.startswith("#"): return name rgb = self._tk._getints( self._tk.tk.call('winfo', 'rgb', self._txt, name)) rgb = "#%02x%02x%02x" % (old_div(rgb[0], 256), old_div( rgb[1], 256), old_div(rgb[2], 256)) print(name, "converted to: ", rgb) return rgb def _initColorTags(self): """ Sets up Tk tags for the text widget (fg/bg/u).""" for ck in list(fg_color_codes.keys()): color = self.convertColor(fg_color_codes[ck]) self._txt.tag_config(ck, foreground=color) self._txtbuffer.tag_config(ck, foreground=color) for ck in list(bg_color_codes.keys()): self._txt.tag_config(ck, background=bg_color_codes[ck]) self._txtbuffer.tag_config(ck, background=bg_color_codes[ck]) self._txt.tag_config("u", underline=1) self._txtbuffer.tag_config("u", underline=1) def colorCheck(self): """ Goes through and displays all the combinations of fg and bg with the text string involved. Purely for debugging purposes. """ fgkeys = ['30', '31', '32', '33', '34', '35', '36', '37'] bgkeys = ['40', '41', '42', '43', '44', '45', '46', '47'] self._txt.insert('end', 'color check:\n') for bg in bgkeys: for fg in fgkeys: self._txt.insert('end', str(fg), (fg, bg)) self._txt.insert('end', str("b" + fg), ("b" + fg, bg)) self._txt.insert('end', '\n') for fg in fgkeys: self._txt.insert('end', str(fg), (fg, "b" + bg)) self._txt.insert('end', str("b" + fg), ("b" + fg, "b" + bg)) self._txt.insert('end', '\n') self._txt.insert('end', '\n') self._txt.insert('end', '\n')
class Window(tk.Tk): """Show a Tk window with scrollable text from stdin. Checks stdin for a new line every one millisecond. If the line starts with a \`#', the rest of the line is used as a new title for the window. Otherwise, the line is appended to the textfield, including the newline character. """ def __init__(self): """Initialize the window. Creates a frame, holding a srollable textfield. Finally reading from stdin is initiated. """ super().__init__() self.font = Font(size=20) self.title('State Machine') self.frame = tk.Frame(self) self.frame.pack(fill='both', expand=True) self.text = ScrolledText(self.frame, wrap='word', font=self.font) self.text.configure(state='disabled') self.text.pack(side='top', fill='both', expand=True) self.text.bind('<1>', lambda ev: self.text.focus_set()) self.geometry('500x400') self.after(1, self.do_read) def do_read(self): """Try to read a line from stdin.""" line = sys.stdin.readline() if line is not None and line != '': self.process_line(line) self.after(1, self.do_read) def process_line(self, line): """Process a line for debug display. If a line starts with \`#', change the window's title. Otherwise, write the line to the textbox. Arguments: line: the line to be processed, including newline character """ if line[0] == '#': self.title(line[1:].rstrip('\n')) else: self.write_text(line) def write_text(self, text): """Write text to the end of the textfield. Arguments: text: the text to be added to the textfield. """ self.text.configure(state='normal') self.text.insert('end', text) # Only autoscroll when at end. if self.text.vbar.get()[1] == 1.0: self.text.pos = self.text.index('end - 1 char') self.text.yview_pickplace('end') self.text.configure(state='disabled')
class OptimizerMainWindow(): ''' classdocs ''' #TODO: change that name def reactToClick(self, event): a = AddRestrictionDialog(self) def __init__(self, optimizer): # always have a reference to model/controller self.optimizer = optimizer # setup main GUI and make stretchable self.guiRoot = Tk() self.guiRoot.title("OPTIMIZR") self.guiRoot.columnconfigure(1, weight=1) self.guiRoot.rowconfigure(0, weight=1) # left (settings) and right (sequences) part self.frameLeft = Frame(self.guiRoot) self.frameLeft.grid(row=0, column=0, sticky=W+E+N+S) self.frameLeft.columnconfigure(0, weight=1) self.frameRight = Frame(self.guiRoot) self.frameRight.grid(row=0, column=1, sticky=W+E+N+S) self.frameRight.columnconfigure(0, weight=1) self.frameRight.rowconfigure(0, weight=1) self.frameRight.rowconfigure(1, weight=1) self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10) self.frameSpeciesControll.columnconfigure(1, weight=1) self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10) self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10) self.frameSpeciesControll.grid(row=0, column=0, sticky=W+E, padx=10, pady=10) self.frameOptimizationControll.grid(row=1, column=0, sticky=W+E, padx=10, pady=10) self.frameRestrictionControll.grid(row=2, column=0, sticky=W+E, padx=10, pady=10) # Species Controll Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0) Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0) self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew") self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly") self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we") self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List") self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e") self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Optimization Controll Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0) self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly") self.comboOptimizationStrategy.grid(row=0, column=1) self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged) # Restriction Enzymes self.listRestriction = Listbox(self.frameRestrictionControll) self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W+E) self.frameRestrictionControll.columnconfigure(0, weight=1) self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ") self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ") self.buttonRestricionAdd.grid(row=1, column=1, padx=5) self.buttonRestricionDel.grid(row=1, column=2, padx=5) # Source Sequence Frame self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10) self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10) self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10) self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10) self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ") self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10) self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5) self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens") self.frameSourceSequence.columnconfigure(0, weight=1) self.frameSourceSequence.rowconfigure(1, weight=1) self.textSourceSeq.frame.columnconfigure(1, weight=1) self.textSourceSeq.frame.rowconfigure(0, weight=1) self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ") self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize) self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ") self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion) self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ") self.textResultSequence = ScrolledText(self.frameResultSequence, height=10) self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w") self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w") self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens") self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e") self.frameResultSequence.columnconfigure(2, weight=1) self.frameResultSequence.rowconfigure(1, weight=1) self.textResultSequence.frame.columnconfigure(1, weight=1) self.textResultSequence.frame.rowconfigure(0, weight=1) self.textSourceSeq.bind("<<Modified>>", self.actionSequenceModified) self.textResultSequence.bind("<<Modified>>", self.actionSequenceModified) #generate color tags for textboxes for i in range(101): #green for normal codons (r,g,b) = colorsys.hsv_to_rgb(210/360, i/100, 1.0) colorHex = "#%02x%02x%02x" % (int(r*255), int(g*255), int(b*255)) self.textSourceSeq.tag_config("normal"+str(i), background=colorHex) self.textResultSequence.tag_config("normal"+str(i), background=colorHex) #red for codons with restriction sites (r,g,b) = colorsys.hsv_to_rgb(5/360, i/100, 1.0) colorHex = "#%02x%02x%02x" % (int(r*255), int(g*255), int(b*255)) self.textSourceSeq.tag_config("restrict"+str(i), background=colorHex) self.textResultSequence.tag_config("restrict"+str(i), background=colorHex) # Set (minimum + max) Window size self.guiRoot.update() self.guiRoot.minsize(self.guiRoot.winfo_width(), self.guiRoot.winfo_height()) self.buttonRestricionAdd.bind("<ButtonRelease>", self.reactToClick) self.buttonRestricionDel.bind("<ButtonRelease>", self.actionRestrictionEnzymeDelete) self.buttonSpeciesList.bind("<ButtonRelease>", self.actionEditSpeciesButton) self.buttonSourceLoad.bind("<ButtonRelease>", self.actionLoadSequence) self.buttonSaveResult.bind("<ButtonRelease>", self.actionSaveSequence) # TEST # self.listRestriction.insert("end", "EcoRI") # self.listRestriction.insert("end", "BamHI") # # dummy event to manually trigger update self.guiRoot.bind("<<Update>>", self.actionUpdate) self.actionUpdate(None) self.guiRoot.mainloop() def actionRestrictionEnzymeDelete(self, event): try: selectedEnzyme = self.listRestriction.selection_get() self.optimizer.restrictionEnzymeList.remove(selectedEnzyme) self.guiRoot.event_generate("<<Update>>") except tkinter.TclError : # no selection pass def actionUpdate(self, event): # print("update called") # clear list of restriction enzymes self.listRestriction.delete(0, "end") for r in self.optimizer.restrictionEnzymeList: self.listRestriction.insert("end", r) self.comboSourceSpecies.delete(0, "end") self.comboTargetSpecies.delete(0, "end") speciesValues = list() for (taxid, name) in self.optimizer.speciesList: speciesValues.append(taxid + ": " + name) self.comboSourceSpecies["values"] = speciesValues self.comboTargetSpecies["values"] = speciesValues if self.comboSourceSpecies.get() not in speciesValues: self.comboSourceSpecies.set("") if self.comboTargetSpecies.get() not in speciesValues: self.comboTargetSpecies.set("") self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) self.optimizer.saveConfig("config.ini") def actionEditSpeciesButton(self, event): speciesListDialog = SpeciesListDialog(self) def actionOptimizerSettingsChanged(self, event=None): # print("Something happened") strategy = self.comboOptimizationStrategy.get() sourceString = self.comboSourceSpecies.get() targetString = self.comboTargetSpecies.get() if not (strategy and sourceString and targetString): return sourceTaxid = sourceString.split(":")[0] targetTaxid = targetString.split(":")[0] self.optimizer.setOptimizer(sourceTaxid, targetTaxid, strategy) self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) # self.optimizer.testPrint() def actionOptimize(self, event=None): self.optimizer.runOptimization() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionRemoveRestricion(self, event=None): self.optimizer.runRestricionRemoval() self.textSourceSeq.edit_modified(True) self.textResultSequence.edit_modified(True) def actionSequenceModified(self, event=None): # necessary if, otherwise -> infinite loop if self.textSourceSeq.edit_modified(): seq = self.textSourceSeq.get("1.0", "end").strip() seq = stripCharsNotInList(seq.upper(), ['A', 'C', 'G', 'T']) self.optimizer.setSourceSeq(seq) oldInsert = self.textSourceSeq.index("insert") self.textSourceSeq.delete("1.0", "end") sourceCodons = self.optimizer.getCodonsForPrint(True) if not sourceCodons: self.textSourceSeq.insert("end", self.optimizer.sourceSequence) else: for (co, sc, r) in sourceCodons: if sc: if not r: self.textSourceSeq.insert("end", co, "normal"+str(int(sc*100))) #print("normal"+str(int(sc*100))) else: self.textSourceSeq.insert("end", co, "restrict"+str(int(sc*100))) else: # remainder without color self.textSourceSeq.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) # reset the modified status at the very end self.textSourceSeq.edit_modified(False) if self.textResultSequence.edit_modified(): seq = self.textResultSequence.get("1.0", "end").strip() # self.optimizer.setOptimizedSeq(seq) oldInsert = self.textResultSequence.index("insert") self.textResultSequence.delete("1.0", "end") targetCodons = self.optimizer.getCodonsForPrint(False) if not targetCodons: self.textSourceSeq.insert("end", self.optimizer.optimizedSequence) else: for (co, sc, r) in targetCodons: if sc: if not r: self.textResultSequence.insert("end", co, "normal"+str(int(sc*100))) #print("normal"+str(int(sc*100))) else: self.textResultSequence.insert("end", co, "restrict"+str(int(sc*100))) else: # remainder without color self.textResultSequence.insert("end", co) self.textSourceSeq.mark_set("insert", oldInsert) self.textResultSequence.edit_modified(False) def actionLoadSequence(self, event=None): filename = tkinter.filedialog.askopenfilename() if filename: seq = sequenceIO.readFile(filename) self.textSourceSeq.delete("1.0", "end") self.textSourceSeq.insert("end", seq) self.textSourceSeq.edit_modified(True) def actionSaveSequence(self, event=None): filename = tkinter.filedialog.asksaveasfilename() if filename: # print("file is " + filename) with open(filename, mode='w') as fd: fd.write(self.optimizer.optimizedSequence)
class myPanel(tkinter.Tk): def __init__(self): tkinter.Tk.__init__(self, 'lsx') self.withdraw() # 先withdraw隐藏再deiconify显示可使setCenter不会导致页面闪烁 self.title('电话簿v1.05 (联系作者:QQ11313213)') # TODO 是否有用 self.keys_var = tkinter.StringVar() self.tex1 = ScrolledText(self) ent1 = tkinter.Entry(self, textvariable=self.keys_var, width=125) ent1.pack(padx=2, pady=2, fill=tkinter.constants.BOTH, side=tkinter.constants.TOP) self.tex1.pack(padx=2, pady=2, fill=tkinter.constants.BOTH, expand=True) self.menu = tkinter.Menu(self, tearoff=0) self.menu.add_command(label='复制', command=self.copyItem) self.menu.add_separator() self.menu.add_command(label='来源') self.menu.add_separator() self.menu.add_command(label='刷新', command=readContacts2) self.menu.add_command(label='前后文', command=self.location) self.menu.add_separator() self.menu.add_command(label='导入文件', command=ImportFiles) self.menu.add_command(label='新增和更改', command=UpdateFile) self.menu0 = tkinter.Menu(self, tearoff=0) self.menu0.add_command(label='刷新', command=readContacts2) self.menu0.add_separator() self.menu0.add_command(label='导入文件', command=ImportFiles) self.menu0.add_command(label='新增和更改', command=UpdateFile) self.menu0.add_separator() submenu = [tkinter.Menu(self, tearoff=0)] self.menu0.add_cascade(label='Designed by Lsx. ', menu=submenu[0]) for key, value in [['Name', 'Li Shixian'], ['Mail', '*****@*****.**'], ['Website', 'github.com/znsoooo/contacts'], ['Wechat', 'Xian_2'], ['Donate', 'xxxx']]: submenu.append(tkinter.Menu(self, tearoff=0)) submenu.append(tkinter.Menu(self, tearoff=0)) submenu[-1].add_command(label=value) submenu[0].add_cascade(label=key, menu=submenu[-1]) self.img_wechat = tkinter.PhotoImage( data=Image.img1) # 没有self会导致显示图片为空白 self.img_donate = tkinter.PhotoImage(data=Image.img2) submenu[8].entryconfig(0, image=self.img_wechat) submenu[10].entryconfig(0, image=self.img_donate) submenu[0].add_separator() submenu[0].add_command(label='All Rights Reserved.', command=bonus) setCenter(self) self.deiconify() ent1.focus() ent1.bind('<KeyRelease>', self.onKeyRelease) self.tex1.bind('<ButtonRelease-3>', self.onRightClick) def select(self, row): self.tex1.mark_set('insert', '%d.0' % row) self.tex1.tag_remove('sel', '0.0', 'end') self.tex1.tag_add('sel', '%d.0' % row, '%d.0' % (row + 1)) def location(self, row=0): if not row: row = self.current_index + 1 self.onKeyRelease(keys='') self.select(row) self.tex1.see('%d.0' % row) def copyItem(self): text = self.tex1.selection_get() self.clipboard_clear() self.clipboard_append(text[:-1]) # 去掉文末换行符 def onRightClick(self, evt=0): self.tex1.focus() # 当焦点在ent1中时 self.current = int(self.tex1.index('current').split('.')[0]) if len(self.index): self.current_index = self.index[self.current - 1] line_last = 0 for line, file in file_list: if line > self.current_index: break else: line_last = line self.menu.entryconfig(2, label='来源: %s (line:%s)' % (file, self.current_index - line_last + 1)) self.menu.entryconfig( 2, command=lambda: os.popen('explorer /select, %s\\%s\\%s' % (os.getcwd(), DATA_FOLDER, file))) self.select(self.current) self.menu.post(evt.x_root, evt.y_root) else: self.menu0.post(evt.x_root, evt.y_root) return self.current def onKeyRelease(self, evt=0, keys=None): if keys is None: keys = self.keys_var.get() keys = keys.lower().split(' ') ss_new = [] self.index = [] for n, s in enumerate(ss): ok = True for key in keys: if key not in s[1]: ok = False if ok: ss_new.append(s[0]) self.index.append(n) # TODO 提出搜索部分到独立的函数 self.tex1.config(state='normal') self.tex1.delete('1.0', 'end') self.tex1.insert('1.0', '\n'.join(ss_new)) self.tex1.config(state='disabled') # 禁止编辑 self.title('电话簿v1.05 (联系作者:QQ11313213) - %s结果' % len(ss_new)) # title更改耗时短可以做到'同时'更改的效果 return ss_new
def ReverseGeolocate(latitude, longitude): apiKey = 'AIzaSyCwugFdGLz6QUtcYqD1z0PKKsYJhay3vIg' apiUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + str(latitude) + ',' + str(longitude) + '&key=' + apiKey apiCall = requests.get(apiUrl) status = apiCall.json()['status'] if status == 'OK': results = apiCall.json()['results'] addressComponents = results[0]['address_components'] return (status, addressComponents) else: return (status, 'No Data') def ProcessCoordinates(): with open('gps_sample_short.csv', newline='') as csvfile: csvReader = csv.reader(csvfile, delimiter=',') for row in csvReader: result = ReverseGeolocate(row[0], row[1]) if (result[0] != 'INVALID_REQUEST'): resultQueue.put(result) def StartAPICalls(): thread.start_new_thread(ProcessCoordinates, ()) if __name__ == '__main__': # main GUI thread, start thread on button click root = ScrolledText() root.pack() root.bind('<Button-1>', lambda event: StartAPICalls()) TkConsumer(root) root.mainloop()
class GetResourceApp(BaseWin): def __init__(self, tk_win): BaseWin.__init__(self, tk_win) self.input_url = StringVar() self.input_url.set('https://www.meijubie.com/movie/index44655.html') self.processing = False self.selectProcessor = StringVar() # 处理请求的个数 self.current_name = '' def set_init_window(self): self.tk_win.grid_rowconfigure(1, weight=1) self.tk_win.grid_columnconfigure(0, weight=1) labelframe = LabelFrame(text="输入") labelframe.grid_columnconfigure(1, weight=1) labelframe.grid(column=0, row=0, padx=10, pady=10, sticky=EW) Label(labelframe, text="目标网址", justify=LEFT, width=10).grid(row=0, column=0) entry = Entry(labelframe, textvariable=self.input_url) entry.grid(row=0, column=1, sticky=EW, padx=5) entry.bind('<Key-Return>', self.getResourceLink) self.button = Button(labelframe, text="获取", command=self.getResourceLink, width=10) self.button.grid(row=0, column=2, sticky=E, padx=5) Label(labelframe, text="处理器", justify=LEFT, width=10).grid(row=1, column=0) select_process = ttk.Combobox(labelframe, textvariable=self.selectProcessor, state="readonly", values=PROCESS_FUN_NAME_LIST, width=90) select_process.set("请选择网址处理器") select_process.grid(row=1, column=1, sticky=EW, columnspan=2, padx=5, pady=5) if len(PROCESS_FUN_NAME_LIST) > 0: select_process.set(PROCESS_FUN_NAME_LIST[0]) output_frame = LabelFrame(text="链接结果") output_frame.grid(column=0, row=1, sticky=NSEW, padx=10) self.copy_btn = Button(output_frame, text="复制到剪贴板", command=lambda: self.copy(self.output_txt)) self.copy_btn.config(state=DISABLED) self.copy_btn.pack() self.output_txt = ScrolledText(output_frame) self.output_txt.pack(side=TOP, expand=TRUE, fill=BOTH, padx=10, pady=10) self.output_txt.bind( "<Button-3>", lambda x: self.rightKey(x, self.output_txt)) # 绑定右键鼠标事件 self.output_txt.bind("<<Selection>>", self.on_text_selection) # 绑定选择事件 # self.output_txt.grid(column=0, columnspan=4) # self.vbar = ttk.Scrollbar(output_frame, orient=VERTICAL, command=self.output_txt.yview) # self.output_txt.configure(yscrollcommand=self.vbar.set) def on_text_selection(self, event=NONE): # try: # selection = self.output_txt.get(SEL_FIRST, SEL_LAST) # except Exception: # selection = NONE # if selection is not NONE and len(selection) > 0: if self.output_txt.tag_ranges("sel"): self.copy_btn.config(state=NORMAL) else: self.copy_btn.config(state=DISABLED) def getResourceLink(self, event=NONE): if self.processing: return self.processing = True # 创建进度条 self.gress_bar = GressBar() # 禁用按钮 self.button.state = DISABLED th = threading.Thread(target=self.doGetResourceLink) th.setDaemon(True) th.start() # 启动进度条 self.gress_bar.start() pass def doGetResourceLink(self): self.current_name = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) self.output_txt.insert( END, '#########################Begin:%s##########################\n' % self.current_name) request_url = self.input_url.get() if not request_url: self.output_txt.insert(END, '请求的网址为空\n') self.end_process() return self.output_txt.insert(END, request_url + '\n') self.output_txt.insert(END, '\n') processor = PROCESS_FUN_DICT[self.selectProcessor.get()] if processor is None: self.output_txt.insert(END, '未找到对应的网站处理器\n') self.end_process() return last_time = time.time_ns() try: results = processor.getDownloadLink(request_url) except Exception as e: self.output_txt.insert(END, '%s\n' % e.args) self.end_process() return index_start = self.output_txt.index("end-1c linestart") for item in results: self.output_txt.insert(END, item + '\n') index_end = self.output_txt.index("end-1c linestart") self.output_txt.insert( END, '\n耗时=%d毫秒\n' % ((time.time_ns() - last_time) / 1E6)) self.end_process(index_end, index_start) def end_process(self, index_end=END, index_start=END): self.output_txt.insert( END, '###########################End:%s##########################\n' % self.current_name) self.gress_bar.quit() self.button.state = NORMAL self.processing = False # 移除之前的选择 self.output_txt.tag_remove(SEL, '1.0', END) # 设置选中状态 print("\nstart=%s,end=%s\n" % (index_start, index_end)) self.output_txt.tag_add(SEL, index_start, index_end) self.output_txt.focus_set()
dataQueue = queue.Queue() def producer(id): for i in range(5): time.sleep(0.1) print('put') dataQueue.put('[producer id=%d, count=%d]' %(id, i)) def consumer(root): try: print('get') data = dataQueue.get(block=False) except queue.Empty: pass else: root.insert('end', 'consumer got => %s\n' % str(data)) root.see('end') root.after(250, lambda: consumer(root)) def makethreads(): for i in range(4): _thread.start_new_thread(producer, (i,)) if __name__ == '__main__': from tkinter.scrolledtext import ScrolledText root = ScrolledText() root.pack() root.bind('<Button-1>', lambda event: makethreads()) consumer(root) root.mainloop()
#主函数 if __name__ == "__main__": #初始化GUI root = tkinter.Tk() root.title("聊天小程序客户端 ") #顶部显示部分 frame1 = Frame(root) frame1.pack() IP_Show_Label = Label(frame1, text="本程序默认IP:127.0.0.1\n默认端口为6000\n无法更改!!!") IP_Show_Label.pack(side='left') #中部聊天框显示部分 frame2 = Frame(root) frame2.pack() Text_Show = ScrolledText(frame2, width=70, height=15) Text_Show.bind("<KeyPress>", lambda e: "break") Text_Show.pack(side="bottom", fill='both', expand=True) #底部消息发送部分 frame3 = Frame(root) frame3.pack() e3 = StringVar() Send_Show = Entry(frame3, textvariable=e3, width=60) buttontext2 = tkinter.StringVar() buttontext2.set('发送') button_Send = tkinter.Button(frame3, width=10, textvariable=buttontext2, command=Click_Send) Send_Show.pack(side="left") button_Send.pack(side="left") frame3.pack()
class VennGUI(object): def __init__(self, argv): """ :param argv: arguments for running the program Usage: venn_gui.py <-f filename> """ # Arguments parser = argparse.ArgumentParser() parser.add_argument("-f", "--filename", help="Read premises from local file", type=str) parser.add_argument("-e", "--eval", help="The argument being validated", type=str) parser.add_argument("--no_window", help="Get the result immediately without" " showing the interactive window " "(Need -f argument)", action="store_true") parser.add_argument("--export", help="Export the result to an image file " "(Need -f and --no_window argument)", type=str) self.args = parser.parse_args(argv[1:]) # Basic components self.filename = "" self.filepath = "" self.collect = None self.root = None self.fig = None self.msg_text = None self.msg_label = None self.premises_box = None self.show_btn = None self.is_possible_highlight = None self.show_exp_in_diagram = None self.eval_box = None if not self.args.no_window: self.set_up() # =============================================================================== # Basic GUI related operations # =============================================================================== def run(self): """ Start the GUI window """ if self.args.no_window: s = ExpressionSet() if self.args.filename: with open(self.args.filename, 'r', encoding='utf8') as f: premises = f.read() s.add_premises(premises) s.parse_premises() s.display_diagram() if self.args.eval: ret = s.evaluate(Expression(self.args.eval), show=True) if self.args.export: plt.savefig(self.args.export) else: plt.show(block=True) else: print("ERROR: No premises found.", file=sys.stderr) else: if self.args.filename: self.filepath = self.args.filename self.load(new_file=False) if self.args.eval: self.eval_box.delete(0, tk.END) self.eval_box.insert(0, self.args.eval) self.evaluate_exp() self.root.update() self.root.deiconify() self.root.mainloop() def clear(self): """ Empty the diagram, premises box and evaluation box """ self.premises_box.delete('1.0', tk.END) self.msg_text.set("") self.eval_box.delete(0, tk.END) plt.clf() def quit(self): """ Quit the program """ if self.premises_box.edit_modified(): save_before_exit = tk.messagebox.askyesnocancel( "Venn Diagram Interpreter", "Do you want to save the changes?") if save_before_exit is None: return if save_before_exit: self.save() self.root.quit() # =============================================================================== # GUI preparation # =============================================================================== def set_up(self): """ Set up all GUI components """ # Set up the venn self.collect = ExpressionSet() # Set up GUI self.root = tk.Tk() self.root.title("Venn Diagram Interpreter") self.root.withdraw() tk.Grid.rowconfigure(self.root, 0, weight=1) tk.Grid.columnconfigure(self.root, 0, weight=1) self.fig = plt.figure(1) canvas = FigureCanvasTkAgg(self.fig, master=self.root) plot_widget = canvas.get_tk_widget() # The main panel plot_widget.grid(row=0, column=0, columnspan=2, sticky=tk.N + tk.S + tk.E + tk.W) # ---------------------------- Premises -------------------------------- # Message self.msg_text = tk.StringVar() self.msg_label = tk.Label(self.root, textvariable=self.msg_text) self.msg_label.grid(row=1, sticky="w", columnspan=2) # Premises input box tk.Label(self.root, text="Sytnax: (Use quote or a newline to separate)").grid( row=2, sticky="w", columnspan=2) tk.Label(self.root, text="\tSet (total 3 at most): The name of the set, " "use a quote(\"\") if it contains multiple words").grid( row=3, sticky="w", columnspan=2) tk.Label(self.root, text="\tExpression: <All/Some> A's are <(not)> B's").grid( row=4, sticky="w", columnspan=2) tk.Label(self.root, text="Enter the premises:").grid(row=6, sticky="w", columnspan=2) PREMISE_BOX_HEIGHT = 4 FIRST_ROW_OF_PREMISE_BOX = 3 + PREMISE_BOX_HEIGHT self.premises_box = ScrolledText(self.root, height=PREMISE_BOX_HEIGHT) self.premises_box.grid(row=FIRST_ROW_OF_PREMISE_BOX, column=0, sticky="nsew", rowspan=PREMISE_BOX_HEIGHT) def premises_modified(event): curr_title = self.root.title() if self.premises_box.edit_modified(): if not curr_title.startswith("*"): self.root.title("*" + curr_title) else: curr_title = curr_title[1:] if curr_title[ 0] == '*' else curr_title self.root.title(curr_title) self.premises_box.bind("<<Modified>>", premises_modified) def focus_next_widget(event): event.widget.tk_focusNext().focus() return "break" self.premises_box.bind("<Tab>", focus_next_widget) self.show_btn = tk.Button(self.root, text="Show diagram", command=self.show_diagram) self.show_btn.grid(row=FIRST_ROW_OF_PREMISE_BOX + 1, column=1, sticky=tk.W + tk.E, rowspan=1) self.show_btn.bind("<Return>", lambda e: self.show_btn.invoke()) self.premises_box.bind("<Control-Return>", lambda e: self.show_btn.invoke()) clear_btn = tk.Button(self.root, text="Clear", command=self.clear) clear_btn.grid(row=FIRST_ROW_OF_PREMISE_BOX + 2, column=1, sticky=tk.W + tk.E, rowspan=1) clear_btn.bind("<Return>", lambda e: clear_btn.invoke()) self.is_possible_highlight = tk.IntVar() poss_check = tk.Checkbutton( self.root, text="Use color shadow to highlight \"Some\" statements.", variable=self.is_possible_highlight) poss_check.grid(row=FIRST_ROW_OF_PREMISE_BOX + PREMISE_BOX_HEIGHT, column=0) poss_check.toggle() self.show_exp_in_diagram = tk.IntVar() show_exp_check = tk.Checkbutton( self.root, text="Display the argument in the diagram", variable=self.show_exp_in_diagram) show_exp_check.grid(row=FIRST_ROW_OF_PREMISE_BOX + PREMISE_BOX_HEIGHT + 1, column=0) show_exp_check.toggle() # Input box tk.Label(self.root, text="Enter the expression you want to evaluate:").grid( row=FIRST_ROW_OF_PREMISE_BOX + PREMISE_BOX_HEIGHT + 2, sticky="w", columnspan=2) self.eval_box = tk.Entry(self.root) self.eval_box.grid(row=FIRST_ROW_OF_PREMISE_BOX + PREMISE_BOX_HEIGHT + 3, column=0, sticky="ew") self.eval_box.bind("<Return>", lambda e: self.evaluate_exp()) eval_btn = tk.Button(self.root, text="Evaluate", command=self.evaluate_exp) eval_btn.grid(row=FIRST_ROW_OF_PREMISE_BOX + PREMISE_BOX_HEIGHT + 3, column=1) eval_btn.bind("<Return>", lambda e: eval_btn.invoke()) # Menu bar menubar = tk.Menu(self.root) filemenu = tk.Menu(menubar, tearoff=0) filemenu.add_command(label="\tNew ", accelerator=" Ctrl+N", command=self.new_file) self.root.bind('<Control-n>', lambda e: self.new_file()) filemenu.add_command(label="\tOpen... ", accelerator=" Ctrl+O", command=self.load) self.root.bind('<Control-o>', lambda e: self.load()) filemenu.add_command(label="\tSave ", accelerator=" Ctrl+S", command=self.save) self.root.bind('<Control-s>', lambda e: self.save()) filemenu.add_command(label="\tSave As... ", accelerator="Ctrl+Shift+S", command=self.save_as) self.root.bind('<Control-Shift-s>', lambda e: self.save_as()) filemenu.add_separator() filemenu.add_command(label="\tExit", command=quit) menubar.add_cascade(label="File", menu=filemenu) editmenu = tk.Menu(menubar, tearoff=0) editmenu.add_command( label="\tUndo", accelerator="Ctrl+Z", command=lambda: self.root.focus_get().event_generate('<<Undo>>')) editmenu.add_separator() editmenu.add_command( label="\tCut", accelerator="Ctrl+X", command=lambda: self.root.focus_get().event_generate('<<Cut>>')) editmenu.add_command( label="\tCopy", accelerator="Ctrl+C", command=lambda: self.root.focus_get().event_generate('<<Copy>>')) editmenu.add_command( label="\tPaste", accelerator="Ctrl+V", command=lambda: self.root.focus_get().event_generate('<<Paste>>')) editmenu.add_separator() editmenu.add_command(label="\tSelect All", accelerator="Ctrl+A", command=lambda: self.root.focus_get(). event_generate('<<SelectAll>>')) menubar.add_cascade(label="Edit", menu=editmenu) helpmenu = tk.Menu(menubar, tearoff=0) helpmenu.add_command(label="Help Index") helpmenu.add_command(label="About...") menubar.add_cascade(label="Help", menu=helpmenu) self.root.config(menu=menubar) self.root.protocol("WM_DELETE_WINDOW", quit) # =============================================================================== # Diagram display operations # =============================================================================== # "Show" button def show_diagram(self): """ Displays the diagram with existing premises """ plt.clf() self.msg_text.set("") # Create the ExpressionSet object self.collect = ExpressionSet() if self.premises_box.get("1.0", tk.END) == "": return # Add all premises try: self.collect.add_premises( self.premises_box.get("1.0", tk.END).replace(';', '\n')) except NameError as e: self.msg_text.set(str(e)) self.msg_label.configure(foreground="red") except TypeError as e: print(e, file=sys.stderr) pass except ValueError as e: self.msg_text.set(str(e)) self.msg_label.configure(foreground="red") return except SyntaxError as e: self.msg_text.set(str(e)) self.msg_label.configure(foreground="red") return if self.collect.empty() or len(self.collect) == 1: return # Parse premises try: self.collect.parse_premises() except ValueError as e: self.msg_text.set(str(e)) self.msg_label.configure(foreground="red") return self.collect.display_diagram( highlight_some=bool(self.is_possible_highlight.get())) if not self.args.no_window: self.fig.canvas.flush_events() self.fig.canvas.draw() # "Update" button def evaluate_exp(self): """ Evaluate an argument and displays the result """ self.show_diagram() if self.collect.empty(): self.msg_text.set("The diagram is empty!") self.msg_label.configure(foreground="red") return if self.eval_box.get() == "": return try: ret, must, reason = self.collect.evaluate( Expression(self.eval_box.get()), show=True, show_exp=self.show_exp_in_diagram.get()) self.msg_text.set(reason) if ret: if must: self.msg_label.configure(foreground="green") else: self.msg_label.configure(foreground="yellowgreen") else: if must: self.msg_label.configure(foreground="red") else: self.msg_label.configure(foreground="darkorange") if self.args.no_window: plt.show(block=True) else: self.fig.canvas.flush_events() self.fig.canvas.draw() except SyntaxError as e: self.msg_text.set(str(e)) self.msg_label.configure(foreground="red") # =============================================================================== # Local file operations # =============================================================================== filetypes = (("Venn Diagram file (*.venn)", "*.venn"), ("Normal text file (*.txt)", "*.txt"), ("All types (*.*)", "*.*")) def load(self, new_file=True): """ Load premises from local file """ if new_file: self.filepath = tk.filedialog.askopenfilename( defaultextension=".venn", filetypes=VennGUI.filetypes) if self.filepath == "": return if not os.path.exists(self.filepath): print("ERROR File \"{}\" does not exist.".format(self.filepath), file=sys.stderr) return self.filename = os.path.basename(self.filepath) with open(self.filepath, 'r', encoding='utf8') as f: text = f.read() self.premises_box.delete('1.0', tk.END) self.premises_box.insert(tk.INSERT, text) self.premises_box.edit_modified(False) self.show_btn.invoke() self.msg_text.set("Successfully load from file \"{}\"".format( self.filename)) self.msg_label.configure(foreground="green") self.root.title(self.filename + " - Venn Diagram Interpreter") def save_as(self, new_file=True): """ Save premises to local file """ if new_file or self.filepath == "" or self.filename == "": self.filepath = tk.filedialog.asksaveasfilename( defaultextension=".venn", filetypes=VennGUI.filetypes) if self.filepath == "": return self.filename = os.path.basename(self.filepath) with open(self.filepath, "w", encoding='utf8') as text_file: text_file.write(self.premises_box.get("1.0", tk.END)) self.msg_text.set("Successfully saved file \"{}\"".format( self.filename)) self.msg_label.configure(foreground="green") self.root.title(self.filename + " - Venn Diagram Interpreter") def save(self): """ Save premises to current file """ if self.filename == "": self.save_as() self.save_as(new_file=False) def new_file(self): """ Create a new file """ if self.premises_box.edit_modified(): save_before_new = tk.messagebox.askyesnocancel( "Venn Diagram Interpreter", "Do you want to save the changes?") if save_before_new is None: return if save_before_new: self.save() self.clear() self.premises_box.edit_modified(False) self.filename = "" self.filepath = "" self.root.title("Venn Diagram Interpreter")
class user_add_kc(): def __init__(self, window): screen_width = window.winfo_screenwidth() screen_height = window.winfo_screenheight() shop_floor_canvax = tk.Canvas(window, width=400, height=501, background='white') shop_floor_canvax.grid(row=0, column=0) shop_floor_canvax.create_line(-10, 200, 400, 200, fill='grey', width=3) shop_floor_canvax.create_line(-10, 274, 400, 274, fill='grey', width=3) def command(tkvar0): print(tkvar0.widget.get('1.0', 'end-1c')) suggestion(x=tkvar0.widget.get('1.0', 'end-1c')) def suggestion(x): value = Output.predict_and_return(x) print(value) try: one = value[0] except: one = "i" try: two = value[1] except: two = "love" try: three = value[2] except: three = "my" try: four = value[3] except: four = "capatalist" try: five = value[4] except: five = "mentality" self.btn_one = ttk.Button(user_add, text=one, width=20) self.btn_one.place(x=0, y=230, width=80, height=45) self.btn_two = ttk.Button(user_add, text=two, width=20) self.btn_two.place(x=80, y=230, width=80, height=45) self.btn_three = ttk.Button(user_add, text=three, width=20) self.btn_three.place(x=160, y=230, width=80, height=45) self.btn_four = ttk.Button(user_add, text=four, width=20) self.btn_four.place(x=240, y=230, width=80, height=45) self.btn_five = ttk.Button(user_add, text=five, width=20) self.btn_five.place(x=320, y=230, width=80, height=45) self.tkvar0 = ScrolledText(window, font=("Ariel", 20), width=20) self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.bind("<Key>", command) def write_command_1(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(1)) def write_command_2(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(2)) def write_command_3(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(3)) def write_command_4(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(4)) def write_command_5(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(5)) def write_command_6(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(6)) def write_command_7(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(7)) def write_command_8(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(8)) def write_command_9(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(9)) def write_command_0(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(0)) def write_command_a(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("a")) def write_command_b(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("b")) def write_command_c(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("c")) def write_command_d(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("d")) def write_command_e(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("e")) def write_command_f(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("f")) def write_command_g(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("g")) def write_command_h(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("h")) def write_command_i(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("i")) def write_command_j(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("j")) def write_command_k(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("k")) def write_command_l(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("l")) def write_command_m(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("m")) def write_command_n(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("n")) def write_command_o(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("o")) def write_command_p(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("p")) def write_command_q(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("q")) def write_command_r(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("r")) def write_command_s(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("s")) def write_command_t(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("t")) def write_command_u(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("u")) def write_command_v(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("v")) def write_command_w(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("w")) def write_command_x(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("x")) def write_command_y(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("y")) def write_command_z(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str("z")) def write_command_space(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(" ")) def write_command_bsk(): temp = str(self.tkvar0.get('1.0', 'end-1c')) # self.tkvar0.destroy() # self.tkvar0 = ScrolledText(window,font=("Ariel", 20), width=20) # self.tkvar0.place(x=0, y=0, width=400, height=200) self.tkvar0.insert("end-1c", str(" ")) s = ttk.Style() s.configure('my.TButton', font=('Aerial', 12, 'bold')) # b = ttk.Button(mainframe, text='Press me', style='my.TButton', # self.btn0 = ttk.Button(user_add, text="DASHBOARD", style='my.TButton', width=20) # self.btn0.place(x=0, y=70, width=230, height=70) # # self.btn1 = ttk.Button(user_add, text="MASTER", style='my.TButton', width=20) # self.btn1.place(x=230, y=70, width=230, height=70) self.btn_submit = ttk.Button(user_add, text="SUBMIT", width=20) self.btn_submit.place(x=0, y=200, width=400, height=30) # The zero row of keyboard Layout self.btn_uk = ttk.Button(user_add, text="", width=20) self.btn_uk.place(x=0, y=275, width=400, height=226) self.btn_1 = ttk.Button(user_add, text="1", width=20, command=write_command_1) self.btn_1.place(x=0, y=275, width=40, height=45) self.btn_2 = ttk.Button(user_add, text="2", width=20, command=write_command_2) self.btn_2.place(x=40, y=275, width=40, height=45) self.btn_3 = ttk.Button(user_add, text="3", width=20, command=write_command_3) self.btn_3.place(x=80, y=275, width=40, height=45) self.btn_4 = ttk.Button(user_add, text="4", width=20, command=write_command_4) self.btn_4.place(x=120, y=275, width=40, height=45) self.btn_5 = ttk.Button(user_add, text="5", width=20, command=write_command_5) self.btn_5.place(x=160, y=275, width=40, height=45) self.btn_6 = ttk.Button(user_add, text="6", width=20, command=write_command_6) self.btn_6.place(x=200, y=275, width=40, height=45) self.btn_7 = ttk.Button(user_add, text="7", width=20, command=write_command_7) self.btn_7.place(x=240, y=275, width=40, height=45) self.btn_8 = ttk.Button(user_add, text="8", width=20, command=write_command_8) self.btn_8.place(x=280, y=275, width=40, height=45) self.btn_9 = ttk.Button(user_add, text="9", width=20, command=write_command_9) self.btn_9.place(x=320, y=275, width=40, height=45) self.btn_0 = ttk.Button(user_add, text="0", width=20, command=write_command_0) self.btn_0.place(x=360, y=275, width=40, height=45) #The first row of keyboard Layout self.btn_q = ttk.Button(user_add, text="q", width=20, command=write_command_q) self.btn_q.place(x=0, y=320, width=40, height=45) self.btn_w = ttk.Button(user_add, text="w", width=20, command=write_command_w) self.btn_w.place(x=40, y=320, width=40, height=45) self.btn_e = ttk.Button(user_add, text="e", width=20, command=write_command_e) self.btn_e.place(x=80, y=320, width=40, height=45) self.btn_r = ttk.Button(user_add, text="r", width=20, command=write_command_r) self.btn_r.place(x=120, y=320, width=40, height=45) self.btn_t = ttk.Button(user_add, text="t", width=20, command=write_command_t) self.btn_t.place(x=160, y=320, width=40, height=45) self.btn_y = ttk.Button(user_add, text="y", width=20, command=write_command_y) self.btn_y.place(x=200, y=320, width=40, height=45) self.btn_u = ttk.Button(user_add, text="u", width=20, command=write_command_u) self.btn_u.place(x=240, y=320, width=40, height=45) self.btn_i = ttk.Button(user_add, text="i", width=20, command=write_command_i) self.btn_i.place(x=280, y=320, width=40, height=45) self.btn_o = ttk.Button(user_add, text="o", width=20, command=write_command_o) self.btn_o.place(x=320, y=320, width=40, height=45) self.btn_p = ttk.Button(user_add, text="p", width=20, command=write_command_p) self.btn_p.place(x=360, y=320, width=40, height=45) #The Second row of Keyboard Layout self.btn_a = ttk.Button(user_add, text="a", width=20, command=write_command_a) self.btn_a.place(x=20, y=365, width=40, height=45) self.btn_s = ttk.Button(user_add, text="s", width=20, command=write_command_s) self.btn_s.place(x=60, y=365, width=40, height=45) self.btn_d = ttk.Button(user_add, text="d", width=20, command=write_command_d) self.btn_d.place(x=100, y=365, width=40, height=45) self.btn_f = ttk.Button(user_add, text="f", width=20, command=write_command_f) self.btn_f.place(x=140, y=365, width=40, height=45) self.btn_g = ttk.Button(user_add, text="g", width=20, command=write_command_g) self.btn_g.place(x=180, y=365, width=40, height=45) self.btn_h = ttk.Button(user_add, text="h", width=20, command=write_command_h) self.btn_h.place(x=220, y=365, width=40, height=45) self.btn_j = ttk.Button(user_add, text="j", width=20, command=write_command_j) self.btn_j.place(x=260, y=365, width=40, height=45) self.btn_k = ttk.Button(user_add, text="k", width=20, command=write_command_k) self.btn_k.place(x=300, y=365, width=40, height=45) self.btn_l = ttk.Button(user_add, text="l", width=20, command=write_command_l) self.btn_l.place(x=340, y=365, width=40, height=45) #The third row of keyboard Layout self.btn_z = ttk.Button(user_add, text="z", width=20, command=write_command_z) self.btn_z.place(x=60, y=410, width=40, height=45) self.btn_x = ttk.Button(user_add, text="x", width=20, command=write_command_x) self.btn_x.place(x=100, y=410, width=40, height=45) self.btn_c = ttk.Button(user_add, text="c", width=20, command=write_command_c) self.btn_c.place(x=140, y=410, width=40, height=45) self.btn_v = ttk.Button(user_add, text="v", width=20, command=write_command_v) self.btn_v.place(x=180, y=410, width=40, height=45) self.btn_b = ttk.Button(user_add, text="b", width=20, command=write_command_b) self.btn_b.place(x=220, y=410, width=40, height=45) self.btn_n = ttk.Button(user_add, text="n", width=20, command=write_command_n) self.btn_n.place(x=260, y=410, width=40, height=45) self.btn_m = ttk.Button(user_add, text="m", width=20, command=write_command_m) self.btn_m.place(x=300, y=410, width=40, height=45) self.btn_bsk = ttk.Button(user_add, text="bsk", width=20, command=write_command_bsk) self.btn_bsk.place(x=340, y=410, width=60, height=45) self.btn_space = ttk.Button(user_add, text="", width=20, command=write_command_space) self.btn_space.place(x=60, y=455, width=280, height=45) def quit(self): user_add.destroy()
class Gui(): def __init__(self): self.file_path = None self.simulation_data = None # A ScriptOutput object self.root = tk.Tk() self.root.protocol("WM_DELETE_WINDOW", self.file_quit) self.set_title() self.scriptLabel = None self.scriptField = None self._create_widgets() self._assign_accelerators() self.root.mainloop() def _create_widgets(self): # The frame containing the widgets frame = tk.Frame(self.root) # The menu bar menu_bar = tk.Menu(self.root, tearoff=0) # The File menu file_menu = tk.Menu( menu_bar, tearoff=0) # tearoff = 0: can't be seperated from window file_menu.add_command(label="New", underline=0, command=self.file_new) # , accelerator="Ctrl+N") file_menu.add_command( label="Open...", underline=0, command=self.file_open) # , accelerator="Ctrl+O") file_menu.add_command( label="Save", underline=0, command=self.file_save) # , accelerator="Ctrl+S") file_menu.add_command(label="Save As...", underline=1, command=self.file_save_as) file_menu.add_separator() file_menu.add_command(label="Exit", underline=1, command=self.file_quit) menu_bar.add_cascade(label="File", underline=0, menu=file_menu) # The Run menu run_menu = tk.Menu( menu_bar, tearoff=0) # tearoff = 0: can't be seperated from window run_menu.add_command(label="Simulate and Plot", underline=0, command=self.simulate, accelerator="F5") run_menu.add_command(label="Plot", underline=0, command=self.plot) menu_bar.add_cascade(label="Run", underline=0, menu=run_menu) # The Edit menu edit_menu = tk.Menu( menu_bar, tearoff=0) # tearoff = 0: can't be seperated from window edit_menu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl+Z") edit_menu.add_command(label="Redo", underline=0, command=self.redo, accelerator="Ctrl+Y") menu_bar.add_cascade(label="Edit", underline=0, menu=edit_menu) self.root.config(menu=menu_bar) # The label lbltxt = "Place your script in the box below or open a text file" # lbltxt = "Simulate: F5, Open: Ctrl+O, Save: Ctrl+S, New: Ctrl+N" scriptLabel = tk.Label(frame, text=lbltxt) scriptLabel.pack(side="top", anchor="w") # The Text widget self.scriptField = ScrolledText(frame) self.scriptField.pack(side="top", fill=BOTH, expand=YES) self.scriptField.config(undo=True) self.scriptField.focus_set() # self.scriptField.config( # borderwidth=0, # font="{Lucida Sans Typewriter} 12", # foreground="green", # background="black", # insertbackground="white", # cursor # selectforeground="green", # selection # selectbackground="#008000", # wrap=tk.WORD, # use word wrapping # width=64, # undo=True, # Tk 8.4 # ) # The Quit button # quitButton = tk.Button(frame, text="Quit", command=self.quit) # quitButton.pack(side="right") # The Close All button closefigButton = tk.Button(frame, text="Close All Figures", command=self.close_figs) closefigButton.pack(side="right") # The Simulate button simButton = tk.Button(frame, text="Simulate and Plot", command=self.simulate) simButton.pack(side="left") # The Plot button plotButton = tk.Button(frame, text="Plot", command=self.plot) plotButton.pack(side="left") frame.pack(fill=BOTH, expand=YES) def simulate(self, event=None): try: script = self.scriptField.get("1.0", "end-1c") script_obj = LsScript.LsScript(script) self.simulation_data = script_obj.run() script_obj.postproc(self.simulation_data) except Exception as ex: self.handle_exception(ex) def plot(self): try: if self.simulation_data is None: raise LsGuiException("No simulation data to plot.") script = self.scriptField.get("1.0", "end-1c") script_obj = LsScript.LsScript(script) script_obj.postproc(self.simulation_data) except Exception as ex: self.handle_exception(ex) def close_figs(self): plt.close("all") def handle_exception(self, ex): # err_msg = ex.args[0] err_msg = str(ex) # if len(ex.args) == 2: # err_msg = "{0} {1}".format(err_msg, ex.args[1]) # # err_msg = err_msg + ex.args[1] messagebox.showerror("Error", err_msg) print(traceback.format_exc()) # def file_open(self): # filename = filedialog.askopenfilename() # # filename = "C:/Python/Python36-32/_Markus/scriptexempel2.txt" # XXX # file = open(filename, "r") # self.scriptField.delete("1.0", "end-1c") # self.scriptField.insert("1.0", file.read()) # self.scriptField.mark_set("insert", "1.0") # file.close() # Make sure you close the file when done def save_changes(self): if self.scriptField.edit_modified(): msg = "This document has been modified. Do you want to save changes?" save_changes = messagebox.askyesnocancel("Save?", msg) if save_changes is None: # Cancel return False elif save_changes is True: # Yes self.file_save() return True def file_new(self, event=None): save_changes = self.save_changes() if not save_changes: return self.scriptField.delete(1.0, "end") self.scriptField.edit_modified(False) self.scriptField.edit_reset() self.file_path = None self.set_title() def file_open(self, event=None): # , filepath=None): save_changes = self.save_changes() if not save_changes: return # XXX initialdir = '.' if os.path.isdir('/home/markus/Dropbox/'): initialdir = '/home/markus/Dropbox/LearningSimulator/Scripts' filepath = filedialog.askopenfilename(filetypes=FILETYPES, initialdir=initialdir) if filepath is not None and len(filepath) != 0: with open(filepath, encoding="utf-8") as f: file_contents = f.read() # Set current text to file contents self.scriptField.delete(1.0, "end") self.scriptField.insert(1.0, file_contents) self.scriptField.edit_modified(False) self.scriptField.mark_set("insert", "1.0") self.file_path = filepath self.set_title() def file_save(self, event=None): self.file_save_as(filepath=self.file_path) def file_save_as(self, filepath=None, event=None): if filepath is None: filepath = filedialog.asksaveasfilename(filetypes=FILETYPES) if len( filepath ) == 0: # Empty tuple or empty string is returned if cancelled return # "cancelled" try: with open(filepath, 'wb') as f: text = self.scriptField.get(1.0, "end-1c") f.write(bytes(text, 'UTF-8')) self.scriptField.edit_modified(False) self.file_path = filepath self.set_title() return # "saved" except IOError as e: self.handle_exception(e) return # "cancelled" def file_quit(self, event=None): save_changes = self.save_changes() if not save_changes: return self.close_figs() self.root.destroy() # sys.exit(0) def set_title(self, event=None): if self.file_path is not None: # title = os.path.basename(self.file_path) title = os.path.abspath(self.file_path) else: title = "Untitled" self.root.title(title + " - " + TITLE) def undo(self, event=None): try: self.scriptField.edit_undo() except Exception as e: self.handle_exception(e) return "break" def redo(self, event=None): self.scriptField.edit_redo() return "break" def _assign_accelerators(self): # self.scriptField.bind("<Control-n>", self.file_new) # self.scriptField.bind("<Control-N>", self.file_new) # self.scriptField.bind("<Control-o>", self.file_open) # self.scriptField.bind("<Control-O>", self.file_open) # self.scriptField.bind("<Control-S>", self.file_save) # self.scriptField.bind("<Control-s>", self.file_save) self.scriptField.bind("<Control-y>", self.redo) self.scriptField.bind("<Control-Y>", self.redo) self.scriptField.bind("<Control-z>", self.undo) self.scriptField.bind("<Control-Z>", self.undo) # self.root.bind_class("Text", ",<Control-z>", self.undo) # self.root.bind_class("Text", ",<Control-Z>", self.undo) # self.root.bind_class("Text", ",<Control-y>", self.redo) # self.root.bind_class("Text", ",<Control-Y>", self.redo) self.scriptField.bind("<F5>", self.simulate)
import _thread, queue, time dataQueue = queue.Queue() def producer(id): for i in range(5): time.sleep(0.1) print('put') dataQueue.put('[producer id=%d, count=%d]' % (id, i)) def consumer(root): try: print('get') data = dataQueue.get(block=False) except queue.Empty: pass else: root.insert('end', 'consumer got => %s\n' % str(data)) root.see('end') root.after(250, lambda: consumer(root)) def makethreads(): for i in range(4): _thread.start_new_thread(producer, (i,)) if __name__ == '__main__': from tkinter.scrolledtext import ScrolledText root = ScrolledText() root.pack() root.bind('<Button-1>', lambda event: makethreads()) consumer(root) root.mainloop()
class GUI: def __init__(self): self.root = tk.Tk() self.root.minsize(300, 300) self.root.geometry('1000x700') #Initialize variables self.frame_index = 0 self.frame_count = float('NaN') self.text_available = True self.data = [] #Set up view window self.tabbed_views = ttk.Notebook(master=self.root) self.hex_frame = tk.Frame(master=self.tabbed_views) self.hex_window = ScrolledText(master=self.hex_frame, wrap=tk.WORD)#tk.Text(master=self.hex_frame, wrap=tk.WORD) #self.hex_scroll = tk.Scrollbar(master=self.hex_frame, command=self.hex_window.yview()) self.text_frame = tk.Frame(master=self.tabbed_views) self.text_window = ScrolledText(master=self.text_frame) #self.text_scroll = tk.Scrollbar(master=self.text_frame, command=self.text_window.yview()) self.tabbed_views.add(self.hex_frame, text='Hex') self.tabbed_views.add(self.text_frame, text='Text') self.tab_id = self.tabbed_views.select() self.current_tab = self.hex_window # Should point to a selected tab in ttk. #Set up menus self.main_menu = tk.Menu(master=self.root) self.file_menu = tk.Menu(master=self.main_menu) self.file_menu.add_command(label='Load File', command=self.load_file) self.file_menu.add_command(label="Save file", command=self.save_file) self.main_menu.add_cascade(label='File', menu=self.file_menu) #Bind events self.hex_window.bind('<Visibility>', self._switch_tab) self.text_window.bind('<Visibility>', self._switch_tab) #Set up labels self.byte_number_label = tk.Label(self.root) self.error_label = tk.Label(master=self.root, foreground=config.get('PALETTE', 'error_foreground')) self.frame_count_label = tk.Label(text="{} of {}".format(self.frame_index, self.frame_count)) #Set up buttons self.nav_button_frame = tk.Frame() self.previous_frame_btn = tk.Button(master=self.nav_button_frame, text="Previous frame", command=self._print_previous_frame) self.next_frame_btn = tk.Button(master=self.nav_button_frame, text='next frame', command=self._print_next_frame) #Pack and position self.root.config(menu=self.main_menu) self.next_frame_btn.grid(row=0, column=1) self.previous_frame_btn.grid(row=0, column=0) self.frame_count_label.pack() self.nav_button_frame.pack() self.error_label.pack() self.tabbed_views.pack(fill=tk.BOTH, expand=1) self.text_window.pack(fill=tk.BOTH, expand=1) self.hex_window.pack(fill=tk.BOTH, expand=1) self.byte_number_label.pack() def _switch_tab(self, event): try: self._update_data() self.tab_id = self.tabbed_views.select() self.current_tab = event.widget self._update_view() except ValueError: self.tabbed_views.select(self.tab_id) self.report_input_error() return def _update_view(self): if not self.data: "Early exit if no data is present" return #Clear editor window self.frame_count_label.configure(text="{} of {}".format(self.frame_index+1, self.frame_count)) self.current_tab.delete('0.0', tk.END) #Insert new content output = None if self.current_tab is self.hex_window: output = self._hexify_output(self.data[self.frame_index]) elif self.current_tab is self.text_window: output = self._textify_output(self.data[self.frame_index]) if not self.text_available: self.text_window.configure(foreground=config.get("PALETTE", "error_foreground"), wrap=tk.WORD) self.error_label.configure(text="Warning, no text representation available. Hex displayed instead.") else: self.text_window.configure(foreground=config.get('PALETTE', 'standard_foreground'), wrap=tk.CHAR) self.error_label.configure(text="") else: raise RuntimeError self.current_tab.insert(tk.END, output) def _update_data(self): try: self.data[self.frame_index] = self._validate_and_retrieve_data() except IndexError: # No data is previously loaded, assume new data is entered self.data.append(self._validate_and_retrieve_data()) def _validate_and_retrieve_data(self): if self.current_tab is self.hex_window or not self.text_available: return self._validate_hex_data() else: return self._validate_string_data() def report_input_error(self): """Raises an alert window to inform the user that there is erroneous input""" showwarning('Warning', "Invalid input detected. Please check that everything is correct before proceeding") def _print_next_frame(self): #Check so data is loaded, Do nothing if theres no data if not self.data: return #Save changes made in editor to data. try: self.data[self.frame_index] = self._validate_and_retrieve_data() except ValueError as error: self.report_input_error() return #Increment the frame 'pointer' self.frame_index += 1 #Check if the pointer is past the end and if so reset to begining if self.frame_index > len(self.data)-1: self.frame_index -= len(self.data) self._update_view() def _print_previous_frame(self): # Check so data is loaded, Do nothing if theres no data if not self.data: return #Save changes made in editor. try: self.data[self.frame_index] = self._validate_and_retrieve_data() except ValueError as error: self.report_input_error() return self.frame_index -= 1 if self.frame_index < 0: #If we move past the first frame, load the last instead self.frame_index = len(self.data)-1 self._update_view() def load_file(self): filename = filedialog.askopenfilename(initialdir=os.curdir, filetypes=(("All files", "*.*"),("Executable","*.exe"),)) if filename: self.file_cursor_pos = 0 self.current_tab.delete('0.0', tk.END) self.load_file_data(filename) self.frame_count_label.config(text='{} of {}'.format(self.frame_index,self.frame_count)) self._update_view() def load_file_data(self, filename: str): buffer_size = int(config.get(option='buffer_size', section='FILES', fallback=8192)) print(buffer_size) self.data = [] self.frame_index = 0 with open(filename, mode='rb') as file: while True: chunk = file.read(buffer_size) if chunk: self.data.append(chunk) else: break self.frame_count = len(self.data) self.text_available = True if self.frame_count == 0: #Emty file was read. Append empty bytes object to data self.data.append(bytes('')) #for index in range(0, self.frame_count): # self.data[index] = ' '.join([hexify(char) for char in self.data[index]]) return self.data def _hexify_output(self, data): return ' '.join([hexify(char) for char in data]) def _textify_output(self, data): """Returns the string representation of input data if it can be decoded. Falls back to hexify_output if an error occurs. """ try: self.text_available = True return data.decode(STRING_ENCODING) except Exception: self.text_available = False return self._hexify_output(data) def save_file(self): try: self.data[self.frame_index] = self._validate_and_retrieve_data() except ValueError as error: self.report_input_error() return except IndexError: #No data exists in current frame. Append to data self.data.append(self._validate_and_retrieve_data()) filename = filedialog.asksaveasfilename(initialdir=os.curdir) if filename: self._write_file(filename) def _validate_hex_data(self): """Validates that data retrieved from window is valid hex-data by converting it to bytes. Returns the data if it is valid""" data = self.current_tab.get('0.0', tk.END)[:-1] #This returns a newline character at the end, slice to remove return bytes.fromhex(data) def _validate_string_data(self): data = self.current_tab.get('0.0', tk.END)[:-1] return bytes(data, STRING_ENCODING) def _write_file(self, filename): with open(filename, mode='wb') as file: file.write(b''.join(self.data)) def run(self): self.root.mainloop()
# thread's main action def threadaction(id, reps, progress): # what the thread does for i in range(reps): time.sleep(1) if progress: progress(i) # progress callback: queued if id % 2 == 1: raise Exception # odd numbered: fail # thread exit/progress callbacks: dispatched off queue in main thread def threadexit(myname): text.insert('end', '%s\texit\n' % myname) text.see('end') def threadfail(exc_info, myname): text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0])) text.see('end') def threadprogress(count, myname): text.insert('end', '%s\tprog\t%s\n' % (myname, count)) text.see('end') text.update() # works here: run in main thread # make enclosing GUI and start timer loop in main thread # spawn batch of worker threads on each mouse click: may overlap text = ScrolledText() text.pack() threadChecker(text) # start thread loop in main thread text.bind('<Button-1>', # 3.x need list for map, range ok lambda event: list(map(onEvent, range(6))) ) text.mainloop() # pop-up window, enter tk event loop