def graph_report(window, data): """ графическое представление результатов """ global df, cmb df = data graph = Toplevel(window) graph.title('Графическое представление') graph.minsize(width=400, height=200) choose_box = Frame(graph) lbl = Label(choose_box, text='Выбор параметра') lbl.pack(side=LEFT, anchor=W, padx=10, pady=10) cmb = Combobox(choose_box, values=list(df.index), width=35) cmb.current(0) cmb.pack(side=LEFT, anchor=W, padx=10, pady=10) choose_box.pack(anchor=S, padx=10, pady=10) fig = Figure(figsize=(5, 4), dpi=100) make_fig(fig, cmb.current()) canvas = FigureCanvasTkAgg(fig, master=graph) canvas.draw() canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1) cmb.bind('<<ComboboxSelected>>', lambda event, canvas=canvas, ax=fig: change_canvas(event, canvas, ax)) toolbar = NavigationToolbar2Tk(canvas, graph) toolbar.update() canvas.get_tk_widget().pack(fill=BOTH, expand=1)
def choose_port_setup(): global app, combox Ports = [] ports = serial.tools.list_ports.comports() for port in ports: Ports.append(port.device) print(Ports) lbl_select = Label(app, text="Please select COM port!", bg="white", fg="black", font=("Times", 16, 'bold')) lbl_select.pack() lbl_select = Label(app, fg="black", font=("Times", 16, 'bold')) lbl_select.pack() combox = Combobox(app, values=Ports, width=36) combox.set("please select COM port here") combox.pack() combox.bind("<<ComboboxSelected>>", callback_port) lbl_select = Label(app, fg="black", font=("Times", 16, 'bold')) lbl_select.pack() btn_select = Button(app, text="Choose", bg="white", fg="green", font=("Times", 16, 'bold'), command=start) btn_select.pack()
def graph_reports(window, data): """ функция формирования окна интерфейса формирования диаграмм согласно требований задания """ global main, cinemas, films main, cinemas, films = data[0], data[1], data[2] graph = Toplevel(window) graph.title('Графические отчеты системы') graph.minsize(width=400, height=200) choose_box = Frame(graph) lbl = Label(choose_box, text='Выбор типа отчета') lbl.pack(side=LEFT, anchor=W, padx=10, pady=10) cmb = Combobox(choose_box, values=diagrams, width=35) cmb.set('Жанры') cmb.pack(side=LEFT, anchor=W, padx=10, pady=10) choose_box.pack(anchor=S, padx=10, pady=10) fig = Figure(figsize=(5, 4), dpi=100) make_fig([main, cinemas, films], fig, 0) canvas = FigureCanvasTkAgg(fig, master=graph) canvas.draw() canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1) cmb.bind( '<<ComboboxSelected>>', lambda event, canvas=canvas, ax=fig: change_canvas(event, canvas, ax)) toolbar = NavigationToolbar2Tk(canvas, graph) toolbar.update() canvas.get_tk_widget().pack(fill=BOTH, expand=1)
def getsheetnames(srcpath): global excelLabel global sheetNamesDropDown global fileSource global sheetNameList global sheetNameValues fileSource = dw.ExcelFile(srcpath) sheetNameList = fileSource.sheet_names Label(sourceFileFrame, text='Select Sheet').grid(row=1, column=0, padx=20, pady=20, sticky='') sheetNamesDropDown = Combobox(sourceFileFrame, width=27) sheetNamesDropDown.grid(row=1, column=1, padx=5, pady=5) sheetNamesDropDown['values'] = sheetNameList sheetNamesDropDown.current() def sheetNameEnter(event): global sheetNameValues sheetNameValues = event.widget.get() sheetNamesDropDown.bind('<<ComboboxSelected>>', sheetNameEnter) Button(sourceFileFrame, text='Initiate', command=lambda: initiate(srcFile.get())).grid(row=1, column=2, padx=20, pady=20, sticky='') excelLabel = Label(sourceFileFrame, text="Imported", bg='green', fg='white') excelLabel.grid(row=0, column=3, padx=5, pady=5, sticky='')
def _create_bcm_entry(self, r, col, str_var, parent, entry_width=12, product_values=None, product_txt=None, change_function=None): container = tk.Frame(parent, background='#ffffcc') entry = Entry(container, font=('Arial', 12), width=entry_width, textvariable=str_var) entry.grid(row=0, column=0, pady=2) if product_values is not None: select_product = Combobox(container, values=product_values, width=entry_width - 2, font=('Arial', 12), state='readonly', textvariable=product_txt) select_product.grid(row=1, column=0, pady=2) select_product.bind("<<ComboboxSelected>>", change_function) container.grid(row=r, column=col, pady=5, padx=2) return container
def modify_link(self, link, *, source=None, label=None, sink=None, new=False): old_source, old_label, old_sink = link assert old_source is not None if new: assert old_label is None assert old_sink is None assert source is None assert sink is None assert label is None assert 0 <= old_source < len(self.new_link_selectors) label_drop_down, sink_drop_down = self.new_link_selectors[old_source] label = label_drop_down.get() or None sink_index = sink_drop_down.current() if sink_index > 0: sink = sink_index - 1 else: sink = None if label is not None and sink is not None: label_drop_down.current(0) sink_drop_down.current(0) label_drop_down.selection_clear() sink_drop_down.selection_clear() else: assert old_sink is not None assert old_label is not None self.graph.remove_link(old_source, old_label, old_sink) items = self.link_selector_maps[old_source].pop((old_label, old_sink)) for item in items: if hasattr(item, 'destroy'): item.destroy() if source is not None or label is not None or sink is not None: if source is None: source = old_source if label is None: label = old_label if sink is None: sink = old_sink assert source is not None if sink is not None and label is not None: if label not in self.link_types: self.link_types.append(label) label_drop_down = Combobox(self, values=self.link_types) label_drop_down.current(self.link_types.index(label)) label_drop_down.bind("<<ComboboxSelected>>", (lambda *a, r=(source, label, sink), v=label_drop_down, **k: self.modify_link(r, label=v.get()))) sink_drop_down = Combobox(self, values=self.token_listing) sink_drop_down.current(sink) sink_drop_down.bind('<<ComboboxSelected>>', (lambda *a, r=(source, label, sink), v=sink_drop_down, **k: self.modify_link(r, sink=v.current()))) remove_button = Button(self, text='-', command=lambda r=(source, label, sink): self.modify_link(r)) self.graph.add_link(source, label, sink) self.link_selector_maps[source][label, sink] = (label_drop_down, sink_drop_down, remove_button) if new or source is None: self.refresh() if self.graph_change_callback: self.graph_change_callback()
def Select_Download_proteome(self, pattern) : """This method is called when user presses enter on his keyboard. It display a dropdown list of all proteomes, that correspond to the pattern given by the user, available in RefSeq database. Parameters ---------- pattern : str pattern that contains a few letters write by user. Returns ------- dropdown_list : list A list that contains all names of proteomes available in RefSeq database which contain the pattern written by the user. """ pattern = pattern.get() library = RefSeqScraper() elements_with_pattern = library.data.loc[(library.data['readable'].str.contains(pattern)),'readable'] list_elements = list(set(elements_with_pattern)) list_elements = sorted(list_elements) dropdown_list = Combobox(self, values=list_elements, font=("courier", 16), width=50) dropdown_list.pack(pady=40) dropdown_list.bind("<<ComboboxSelected>>", lambda x=None: self.Download_proteome(dropdown_list))
def charger(): """load a language""" #-------------------------------------------------------------------------- def select(event): """Select the language""" print(combobox.get()) for language in languages: name, a, b, c, d = language if name == combobox.get(): msg = hill.check_matrix(a, b, c, d) print(msg) top = Toplevel(fenetre) popup(top) _, _, X, Y = geoliste(fenetre.geometry()) top.geometry("150x200%+d%+d" % (X, Y)) top.title("charger") languageSelect = StringVar() languages = read_file("languages.txt") languages_name = [] for language in languages: languages_name.append(language[0]) combobox = Combobox(top, textvariable=languageSelect, values=languages_name, \ state='readonly') combobox.bind('<<ComboboxSelected>>', func=select) combobox.pack()
def __init__(self): self.app = Tk() self.app.maxsize(900, 700) self.app.minsize(900, 700) self.app.title('Passport Seva') font11 = "-family Calibri -size 15 -weight bold -slant roman " \ "-underline 0 -overstrike 0" self.v = StringVar() Label(self.app, text="Appointment Availability", font="Calibri 26", fg="blue").place(x=20, y=10) Label(self.app, text="Passport Office", font="Arial 18").place(x=20, y=100) city = [ 'Amritsar', 'Bhopal', 'Chandigarh', 'Chennai', 'Delhi', 'Goa', 'Hyderabad', 'Jaipur', 'Jammu', 'Kolkata', 'Lucknow', 'Mumbai', 'Ranchi', 'Shimla', 'Trivandrum', 'Visakhapatnam' ] TCombobox1 = Combobox(self.app, values=city, takefocus="", textvariable=self.v, font=font11) TCombobox1.configure(state="readonly") TCombobox1.place(x=200, y=100, relheight=0.051, relwidth=0.280) TCombobox1.bind("<<ComboboxSelected>>", self.fetch) self.app.mainloop()
class Valaszto(LabelFrame): def __init__(self, cimke, valasztek, master=None, **kw): super().__init__(master=master, text=cimke, **kw) self._valasztek = valasztek self._valaszto = Combobox(self, width=42) self.beallit(valasztek) self._valaszto.grid() def beallit(self, valasztek): self._valasztek = valasztek self._valaszto["values"] = [elem.listanezet() for elem in valasztek] try: self._valaszto.current(0) except TclError: self._valaszto.set("") @property def valaszto(self): return self._valaszto @property def elem(self): try: return self._valasztek[self._valaszto.current()] except IndexError: return None def set_callback(self, fv_ref): self._valaszto.bind("<<ComboboxSelected>>", fv_ref)
def __init__(self, master, field, color, parent): Frame.__init__(self, master) self.grid(column=0, row=0, sticky=(N, S, W, E)) self.columnconfigure(2, weight=1) self.controls = list() self.bg_color = color self.temp_entry = None self.hidden_label = None self.temp_text = StringVar() self.column_num = 0 self.parent = parent self.field = field self.bind('<Enter>', self._mark_row) self.bind('<Leave>', self._unmark_row) # Создаем надписи self.create_lb(0, field.name, 32, W) self.create_lb(1, field.type, 24, CENTER) self.create_lb(2, field.comment, 24, W) # Создаем выпадающий список с вариантами статуса cbb = Combobox(self, textvariable=field.state.var, values=states, width=25) cbb.state(['readonly']) cbb.grid(column=3, row=0, sticky=(W, E)) cbb.bind('<MouseWheel>', self._on_mousewheel) # Создаем чекбокс для отметки события self.create_cb(field.event.var, 4)
def win2(): global win2 win2 = Toplevel(win1) win2.geometry("1350x700+0+0") win2.title("Shortlisting Tool") global combo global frame4 frame3 = Frame(win2) frame3.pack() frame4 = Frame(frame3, bd=5, height=500, width=500, relief='ridge') frame4.grid(row=1, column=0) lbltitle = Label(frame3, text="Analysis CV", font=('arial', 25, 'bold'), bd=20) lbltitle.grid(row=0, column=0, columnspan=2, pady=10) lbltitle = Label(frame4, text="Select Job ID", font=('arial', 10, 'bold'), bd=20) lbltitle.grid(row=0, column=0, columnspan=2, pady=10) combo = Combobox(frame4, width=20, font=("bold", 12), state='readonly') combo.set("Select") combo['value'] = combo_input() combo.bind("<<ComboboxSelected>>", view_data) combo.grid(row=0, column=2, padx=100)
def __init__(self, window, initial=' ', options=[], instance=str, command=None, width=None): if initial not in options: raise RuntimeError('DropDown menu: Not valid initial value ({0}).'.format(initial)) self.variable = StringVar(window.root, value=initial) self.instance = instance self.command = command try: combostyle = Style() combostyle.theme_create('combostyle', parent='alt', settings={'TCombobox': {'configure': {'selectbackground': 'white', 'fieldbackground': 'white', 'background': 'white'}}}) combostyle.theme_use('combostyle') except: pass if width: widget = Combobox(window.main_frame, textvariable=self.variable, state='readonly', width=width) else: widget = Combobox(window.main_frame, textvariable=self.variable, state='readonly', width=int(window.log.entries_width * 0.8)) options = [str(ff) for ff in options] widget['values'] = tuple(options) widget.bind('<<ComboboxSelected>>', self.internal_command) HOPSWidget.__init__(self, window, widget, 'DropDown')
def SPLIT_SINGLE_COLUMN(): # SPLIT COLUMNS global splitSrc global splitTrgt1 global splitTrgt2 global splitTrgt3 Label(splitColumnFrame, text='Source Column').grid(row=0, column=0) Label(splitColumnFrame, text='Target Column 1').grid(row=1, column=0) Label(splitColumnFrame, text='Target Column 2').grid(row=1, column=2) Label(splitColumnFrame, text='Target Column 3').grid(row=1, column=4) # Source column input # splitSrc = Entry(splitColumnFrame) # splitSrc.grid(row=0, column=1, padx=5, pady=5) splitSrc = Combobox(splitColumnFrame, width=27) splitSrc['values'] = columnHeaders splitSrc.grid(row=0, column=1, padx=5, pady=5) splitSrc.current() def dtsrcEnter(event): global splitSrcValue splitSrcValue = event.widget.get() splitSrc.bind('<<ComboboxSelected>>', dtsrcEnter) # Target column 1 input splitTrgt1 = Entry(splitColumnFrame) splitTrgt1.grid(row=1, column=1, padx=2, pady=2) # Target column 2 input splitTrgt2 = Entry(splitColumnFrame) splitTrgt2.grid(row=1, column=3, padx=2, pady=2) # Target column 3 input splitTrgt3 = Entry(splitColumnFrame) splitTrgt3.grid(row=1, column=5, padx=2, pady=2)
class SelectWithDropDown(TwoCells): def __init__(self, parent, text, values, callback, width=30, **kwargs): super().__init__(parent, **kwargs) self.callback = callback self.label = Label(self.frame, text=text) self.label.grid(column=0, row=0, padx=5, pady=5, sticky=W) self.combobox = Combobox(self.frame, validate="key", validatecommand=self.validate_command, width=width) self.combobox["values"] = values self.combobox.current(0) self.combobox.grid(column=1, row=0, padx=5, pady=5, sticky=E) self.combobox.bind("<<ComboboxSelected>>", self._selection_changed) self._selection_changed(values[0]) def _selection_changed(self, value): self.callback(self.combobox.get()) def update_values(self, values): self.combobox["values"] = values self.combobox.current(0) self._selection_changed(values[0]) def select(self, name): for index, value_text in enumerate(self.combobox["values"]): if value_text == name: self.combobox.current(index) self._selection_changed(value_text) def get(self): return self.combobox["values"][self.combobox.current()]
class Volumes(Areas): def __init__(self): self.lst = ['Cube', 'Rectangular Prism', 'Triangular Prism', 'Sphere', 'Cylinder', 'Cone', 'Pyramid'] self.cb = Combobox(frame2, value=self.lst, width=16, state="readonly") self.cb.current(0) self.cb.bind('<<ComboboxSelected>>', updateShapes)
def decoding_options(): decoding_ = Combobox(window, state="readonly", width=25) decoding_['values'] = ('Caesar_decode', 'Vigenere_decode', 'Vernam_decode', 'Caesar_decode_with_frequency_analysis', 'Vigenere_decode_with_frequency_analysis', 'BMP_Shorthand_decoding') decoding_.bind('<<ComboboxSelected>>', shorthand_decoding) return decoding_
def encoding_options(): encoding_ = Combobox(window, state="readonly", width=25) encoding_['values'] = ('Caesar_encode', 'Vigenere_encode', 'Vernam_encode', 'BMP_Shorthand_encoding') encoding_.current(0) encoding_.grid(padx=1075, pady=160) encoding_.bind('<<ComboboxSelected>>', shorthand_encoding) return encoding_
def main(): '''Main window of the program''' global root, entry, combo_box, text_area, scrollbar root = Tk() root.withdraw() root.after(0, root.deiconify) root.iconbitmap('included files/icon.ico') root.title('Number System') pos_x, pos_y = root.winfo_screenwidth() // 2 - 300 // 2, root.winfo_screenheight() // 2 - 300 // 2 root.geometry(f'260x369+{pos_x}+{pos_y}') root.resizable(0, 0) label_image_frame = Frame(root, bd=0, width=237, height=280) file_image_file = PIL.ImageTk.PhotoImage(PIL.Image.open('included files/temp.jpg')) label_image = Label(label_image_frame, image=file_image_file, bg='blue', borderwidth=0) label_image.grid(row=0, column=0) label_image_frame.place(x=0, y=0) combo_values = ['Binary to Decimal', 'Binary to Octal', 'Binary to Hexadecimal', 'Binary to Quinary', 'Decimal to Binary', 'Decimal to Octal', 'Decimal to Hexadecimal', 'Decimal to Quinary', 'Octal to Binary', 'Octal to Decimal', 'Octal to Hexadecimal', 'Octal to Quinary', 'Hexadecimal to Binary', 'Hexadecimal to Decimal', 'Hexadecimal to Octal', 'Hexadecimal to Quinary', 'Quinary to Binary', 'Quinary to Decimal', 'Quinary to Octal', 'Quinary to Hexadecimal'] entry_field = Frame(root) entry = Entry(entry_field, width=33, highlightcolor='grey', highlightthickness=1) entry.insert(0, 'Enter Number') entry.grid(row=0, column=0) entry_field.place(x=30, y=130) combo_frame = Frame(root) combo_box = Combobox(combo_frame, values=combo_values, width=30) combo_box.set('Select Number System') combo_box.grid(row=0, column=0) combo_frame.place(x=30, y=160) convert_frame = Frame(root) convert_button = Button(convert_frame, width=28, height=2, bg='Green', activebackground='Green', text='CONVERT', command=calculation) convert_button.pack() convert_frame.place(x=30, y=190) # Binding Keys entry.bind('<Return>', calculation) combo_box.bind('<Return>', calculation) convert_button.bind('<Return>', calculation) entry.bind('<Enter>', entry_enter) entry.bind('<Leave>', entry_leave) text_area_frame = Frame(root) text_area = Text(text_area_frame, width=23, height=5, bg='black', font="-weight bold", bd=0, fg='White', cursor='arrow') text_area.grid(column=0, row=0) text_area_frame.place(x=30, y=240) scrollbar = Scrollbar(text_area_frame, orient="vertical", command=text_area.yview) show_scrollbar() root.mainloop()
class Main(): def __init__(self): f=open('degur.yaml','r',encoding='utf-8') self.data=yaml.load(f.read()) f.close() root=Tk() root.wm_title('Дежурства v 0.1.1 (c) 2013-2015, Shershakov D.') root.geometry('{0}x{1}+0+0'.format(root.winfo_screenwidth()-10,root.winfo_screenheight()-80)) root.rowconfigure(1,weight=1) root.columnconfigure(1,weight=1) root.columnconfigure(2,weight=1) f0=Frame(root) f1=Frame(root) f2=Frame(root) self.y=Combobox(f0,width=4) self.m=Combobox(f0,width=4) self.y.grid(row=0,column=0) self.m.grid(row=1,column=0) self.y.bind('<<ComboboxSelected>>',self.setY) self.m.bind('<<ComboboxSelected>>',self.setM) f0.grid(row=0,column=0,rowspan=10,sticky=N+S+E+W) f1.grid(row=1,column=1,sticky=N+S+E+W) f2.grid(row=1,column=2,sticky=N+S+E+W) self.g1=Gr(f1,self.data) self.g2=Gr(f2,self.data,SCRY=self.g1.scrY) self.set0() self.g1.yview2=self.g2.yview root.bind('<F1>',lambda e: MyHelp(root,self.data,self.y.get())) root.bind_all('<Control-F3>',lambda e: statistic_q(self.data,self.y.get(),v='план')) root.bind_all('<Shift-F3>',lambda e: statistic_q(self.data,self.y.get(),v='табель')) root.bind_all('<Control-F4>',lambda e: statistic(self.data,self.y.get(),v='план')) root.bind_all('<Shift-F4>',lambda e: statistic(self.data,self.y.get(),v='табель')) root.bind_all('<F3>',lambda e: statistic_q(self.data,self.y.get(),v='авто')) root.bind_all('<F4>',lambda e: statistic(self.data,self.y.get(),v='авто')) root.bind_all('<F5>',lambda e: tabel(self.data,self.y.get(),self.m.get())) root.bind_all('<F7>',lambda e: otp(self.data,self.y.get(),v='авто')) root.bind_all('<F8>',lambda e: statistic_xx(self.data,self.y.get(),v='авто')) root.bind_all('<F9>',lambda e: per(self.data,self.y.get(),v='авто')) root.bind_all('<Control-F8>',lambda e: statistic_xx(self.data,self.y.get(),v='план')) FreeConsole() root.mainloop() def set0(self,*e): Y=sorted(list(self.data.keys())) self.y['values']=Y self.y.set(Y[0]) self.setY(*e) def setY(self,*e): M=sorted([x for x in self.data[self.y.get()] if str(x).isnumeric()]) self.m['values']=M self.m.set(M[0]) self.setM(*e) def setM(self,*e): y=self.y.get() m=self.m.get() self.g1.set(y,m) self.g2.set(y,m)
def select_day(): # wybierasz global value_date value_date = StringVar() combobox = Combobox(root, textvariable=value_date) combobox.grid(row=0, column=16) combobox['values'] = ('one day', 'one week', 'one month', 'one year') combobox.bind("<<ComboboxSelected>>", selected_day)
def make_commonframe(self): # 每个页面都要显示的书选择 Label(self.commonframe, text='Choice Book').pack(side=LEFT) comboxlist = Combobox(self.commonframe) comboxlist["values"] = self.book.search_book() comboxlist.current(0) self.phraselist = comboxlist comboxlist.bind("<<ComboboxSelected>>", self.choice_book(self.phraselist.get())) comboxlist.pack(side=LEFT) self.commonframe.pack()
class Mswitch_Widget(Frame): def __init__(self, parent, controller, system=None, num_channels=None, background_color=None): if system == None: self.system = controller.system if num_channels == None: num_channels = controller.channels if background_color == None: background_color = controller.widget_background font1 = font.Font(family='Calibri', size=12, weight='bold') font2 = font.Font(family='Verdana', size=8) font3 = font.Font(family='Verdana', size=10, weight='bold') Frame.__init__(self, parent) self.configure(borderwidth=3, relief="ridge") self.config(height=8, width=5) self.configure(bg=background_color) self.button_width = 10 self.title = 'Reservoir Control' self.title_label = Label(self, text=self.title, bg=background_color).pack() self.title = "Reservoir" self.label = Label(self, text=self.title, font=font1, bg=background_color) self.values = list(range(1, self.system.getNumberOfReservoirs() + 1)) self.reservoir_combobox = Combobox(self, values=self.values, state='readonly') self.reservoir_combobox.bind("<<ComboboxSelected>>", self.setRes) self.label.pack(side="left", padx=5) self.reservoir_combobox.pack(side="right", padx=5) self.reservoir_combobox.set('1') def setRes(self, event): self.system.setReservoir(self.reservoir_combobox.get()) def getVals(self): return [self.reservoir_combobox.get()]
class ControlPanel(Frame): """Allows the user to control elements of the sorting algorithm.""" def __init__(self, master, **options): Frame.__init__(self, master=master, **options) self.master = master self.grid(row=1, column=0) self.config(padx=5, pady=5) Label(self, text="Algorithm:").pack(side=LEFT) self.combo_algo = Combobox(self, values=list(master.ALGORITHMS.keys())) self.combo_algo.current(0) self.combo_algo.bind("<<ComboboxSelected>>", self.restart) self.combo_algo.pack(side=LEFT, padx=(2, 5)) self.b_restart = Button(self, text="Restart (new data)", command=self.restart) self.b_restart.pack(side=LEFT, padx=(5, 0)) self.b_pauseplay = Button(self, text="Play", command=master.pauseplay) self.b_pauseplay.pack(side=LEFT, padx=(0, 5)) self.scl_speed = Scale(self, from_=1, to=100, orient=HORIZONTAL, sliderlength=10, showvalue=0, length=125, label="Speed: 30 iters/s", command=self.change_speed) self.scl_speed.set(30) self.scl_speed.pack(side=LEFT, padx=5) def query_params(self): min_val = simpledialog.askinteger("Input", "Minimum value:", parent=self.master, initialvalue=0) if min_val is None: return None max_val = simpledialog.askinteger("Input", "Maximum value:", parent=self.master, minvalue=min_val, initialvalue=min_val+100) size = simpledialog.askinteger("Input", "Size of data:", parent=self.master, minvalue=2, initialvalue=100) if max_val is None or size is None: return None return min_val, max_val, size def restart(self, e=None): min_val, max_val, size = self.query_params() self.master.new_algo(self.combo_algo.get(), min_val, max_val, size) def change_speed(self, e=None): speed = self.scl_speed.get() self.master.sort_delay = 1000/speed self.scl_speed.config(label="Speed: {} iters/s".format(speed)) print("Sort speed:", self.scl_speed.get())
def addPage(self, values): """@summary: Ajoute un onglet avec les valeurs de personnages données. """ self.persoViews.append(PersoView(values)) persoVw = self.persoViews[-1] self.framesPersos.append(Frame(self.notebk)) framePerso = self.framesPersos[-1] persoVw.framePerso = framePerso self.caracsNotebk.append(Notebook(framePerso)) caracNotebk = self.caracsNotebk[-1] caracNotebk.pack() persoVw.caracsNotebk = caracNotebk for inputsCategory, inputValues in persoVw.perso.items(): frameCaracs = LabelFrame(framePerso, text=inputsCategory) if persoVw.inputs.get(inputsCategory, None) is None: persoVw.inputs[inputsCategory] = dict() j = 0 if inputsCategory == "Sorts": self.addPageSorts(persoVw) continue for inputName, inputValue in inputValues.items(): if inputName == "Classe": classesDisponibles = \ Combobox(frameCaracs, textvariable=StringVar(), values=["Cra", "Xelor", "Iop", "Sacrieur", "Sram", "Poutch", "Eniripsa", "Pandawa"], state='readonly') classesDisponibles.bind('<<ComboboxSelected>>', self.onClassChange) persoVw.inputs[inputsCategory][inputName] = classesDisponibles persoVw.inputs[inputsCategory][inputName].set(inputValue) else: persoVw.inputs[inputsCategory][inputName] = \ Entry(frameCaracs, textvariable=StringVar(), width=10) persoVw.inputs[inputsCategory][inputName].insert(END, inputValue) lblCarac = Label(frameCaracs, text=inputName+":") lblCarac.grid(row=j, column=0) persoVw.inputs[inputsCategory][inputName].grid(row=j, column=1) j += 1 caracNotebk.add(frameCaracs, text=inputsCategory) # Pack de la fenêtre, détermine la taille de la fenêtre selon la taille des composants. #framePerso.pack(fill="both", expand="yes") self.notebk.add(framePerso, text="Perso "+str(len(self.persoViews))) saveBtn = Button(framePerso, text='Sauvegarder ce perso', command=persoVw.save) loadBtn = Button(framePerso, text='Charger un perso', command=persoVw.load) deleteThisBtn = Button(framePerso, text="Supprimer ce perso", command=self.deleteActiveNotePage) # Mise du bouton sur la droite de la fenetre saveBtn.pack(side="left") # Mise du bouton sur la droite de la fenetre loadBtn.pack(side="left") deleteThisBtn.pack(side="left")
class FilterSelectionFrame(LabelFrame): def __init__(self, parent, get_all, get_selection, set_selection): log.debug(f"creating {type(self).__name__}...") super().__init__(parent, text=" Filters ") self.parent = parent self.get_all = get_all self.get_selection = get_selection self.set_selection = set_selection Label(self, text="Country: ").grid(row=0, column=0, padx=PAD_X, pady=PAD_Y, sticky=EW) self.cb_country = Combobox(self, state="readonly", values=("All",), width=30) self.cb_country.bind("<<ComboboxSelected>>", self.apply_country_filter) self.cb_country.grid(row=0, column=1, padx=PAD_X, pady=PAD_Y, sticky=EW) self.cb_country.current(0) Label(self, text="Tournament: ").grid(row=0, column=2, padx=PAD_X, pady=PAD_Y, sticky=EW) self.cb_tournament = Combobox(self, state="readonly", values=("All",), width=50) self.cb_tournament.bind("<<ComboboxSelected>>", self.apply_tournament_filter) self.cb_tournament.current(0) self.cb_tournament.grid(row=0, column=3, padx=PAD_X, pady=PAD_Y, sticky=EW) Button(self, text="Reset", command=self.reset_filters).grid(row=0, column=4) def set_countries(self, countries): values = (ALL,) if countries: values += tuple(countries) self.cb_country.configure(values=values) def set_tournaments(self, tournaments): values = (ALL,) if tournaments: values += tuple(tournaments) self.cb_tournament.configure(values=values) def apply_country_filter(self, _): country = self.cb_country.get() selection = self.get_all() if country == ALL else self.get_selection().with_country(country) self.set_selection(selection) def apply_tournament_filter(self, _): tournament = self.cb_tournament.get() selection = self.get_all() if tournament == ALL else self.get_selection().with_tournament(tournament) self.set_selection(selection) def reset_filters(self): self.set_selection(self.get_all()) self.cb_country.current(0) self.cb_tournament.current(0)
def startupScreen(): #window startWindow = Tk() startWindow.title('COVID-19 Tracker') startWindow.geometry('600x370') startWindow.config(bg=DARK_BURGANDY) icon = PhotoImage(file='images\COVID-19-virus-white.png') startWindow.iconphoto(False, icon) #window title titleLabel = Label(startWindow, text="COVID-19 Cases Predictor", font=("Times New Roman Bold", 25), bg=DARK_BURGANDY, fg='white') titleLabel.pack(pady=10) #grid(column=0, row=0, padx=13,pady=10) #logo main_image = PhotoImage(file='images\COVID-19-virus.png') main_image_lbl = Label(image=main_image) main_image_lbl.image = main_image main_image_lbl.place(relx=0.04, rely=0.2) #Select Data lbl_combo = Label(startWindow, text="Select Data:", font=("Times New Roman Bold", 18), bg=DARK_BURGANDY, fg='white') lbl_combo.place(relx=0.55, rely=0.4) comboValues = [ 'Select Data', 'USA NATIONAL DATA', 'USA STATES DATA', 'USA COUNTIES DATA' ] combo = Combobox(startWindow, values=comboValues, state="readonly", width=35) combo.place(relx=0.55, rely=0.5) combo.current(0) def comboFunc(event): if combo.get() == comboValues[1]: startWindow.destroy() loadingScreen("National") elif combo.get() == comboValues[2]: startWindow.destroy() loadingScreen("State") elif combo.get() == comboValues[3]: startWindow.destroy() loadingScreen("County") combo.bind("<<ComboboxSelected>>", comboFunc) startWindow.mainloop()
class Application_ui(Frame): # 这个类仅实现界面生成功能,具体事件处理代码在子类Application中。 def __init__(self, master=None): Frame.__init__(self, master) self.master.title('Excel转化Rpy工具') self.master.geometry('600x343') self.createWidgets() def createWidgets(self): self.top = self.winfo_toplevel() self.style = Style() self.bkg_gif = PhotoImage(data=base64.b64decode(back_ground_gif_data)) self.background_label = Label(self.top, image=self.bkg_gif) self.background_label.place(x=0, y=0, relwidth=1, relheight=1) self.Text = Text(self.top, font=('宋体', 9)) self.Text.place(relx=0.066, rely=0.07, relwidth=0.869, relheight=0.563) self.saveAddr = Entry(self.top, font=('宋体', 9)) self.saveAddr.place(relx=0.355, rely=0.84, relwidth=0.409, relheight=0.052) self.ComboList = ['源文件目录', '自定义目录'] self.Combo = Combobox(self.top, values=self.ComboList, font=('宋体', 9), state='readonly') self.Combo.place(relx=0.184, rely=0.84, relwidth=0.146, relheight=0.058) self.Combo.set(self.ComboList[0]) self.Combo.bind('<<ComboboxSelected>>', self.comboEvent) self.style.configure('InputButton.TButton', font=('宋体', 9)) self.InputButton = Button(self.top, text='浏览', command=self.InputButton_Cmd, style='InputButton.TButton') self.InputButton.place(relx=0.184, rely=0.7, relwidth=0.133, relheight=0.073) self.Haruhi_gif = PhotoImage(data=base64.b64decode(haruhi_gif_data)) self.style.configure('ConvertButton.TButton', font=('宋体', 9)) self.ConvertButton = Button(self.top, image=self.Haruhi_gif, command=self.ConvertButton_Cmd, style='ConvertButton.TButton') self.ConvertButton.place(relx=0.788, rely=0.7, relwidth=0.146, relheight=0.236) self.style.configure('OutputLabel.TLabel', anchor='w', font=('宋体', 9)) self.OutputLabel = Label(self.top, text='保存目录:', style='OutputLabel.TLabel') self.OutputLabel.place(relx=0.066, rely=0.84, relwidth=0.107, relheight=0.05) self.style.configure('InputLabel.TLabel', anchor='w', font=('宋体', 9)) self.InputLabel = Label(self.top, text='输入设置:', style='InputLabel.TLabel') self.InputLabel.place(relx=0.066, rely=0.723, relwidth=0.107, relheight=0.05) menubar = Menu(self.top) filemenu = Menu(menubar, tearoff=0) # tearoff意为下拉 menubar.add_cascade(label='帮助', menu=filemenu) filemenu.add_command(label='视频教程', command=self.open_help_url) filemenu.add_command(label='检查更新', command=self.check_for_update) self.top.config(menu=menubar)
class history_record(object): def __init__(self): self.win = Tk() self.width = 250 self.height = 200 self.win.title('历史记录') self.win.iconbitmap(LOGO) screenwidth = self.win.winfo_screenwidth() screenheight = self.win.winfo_screenheight() aligner = '%dx%d+%d+%d' % (self.width, self.height, (screenwidth - self.width) / 2, (screenheight - self.height) / 2) self.win.geometry(aligner) self.db = Mongodb_server(mongo_host, mongo_port) def handle(self, *args): return self.db.search_one(f"record", self.comboxlist.get(), {"_id": 0, "destination": 1, "local": 1, "source": 1}) @staticmethod def _db_record(): return {"_id": 0, "destination": 1, "local": 1, "source": 1} def _exit_win(self): self.win.quit() def ok(self): Transmit().arg_down(self.handle()['destination'], self.handle()['source'], self.handle()['local']) showinfo('提示', '还原成功') self._exit_win() def del_data(self): self.db.del_key('record', self.comboxlist.get(), self._db_record()) exit() def _win(self): time_list = [] comvalue = StringVar() # 窗体自带的文本,新建一个值 self.comboxlist = Combobox(self.win, textvariable=comvalue, state='readonly') # 初始化 for get_time in get_db_table(): time_list.append( f"{get_time[0:4]}-{get_time[4:6]}-{get_time[6:8]} {get_time[8:10]}:{get_time[10:12]}:{get_time[12:14]}" ) self.comboxlist["values"] = tuple(time_list) self.comboxlist.current(0) # 选择第一个 self.comboxlist.bind("<<ComboboxSelected>>", self.handle) # 绑定事件,(下拉列表框被选中时,绑定handle()函数) self.comboxlist.place(relx=0.2, rely=0.25, width=150, height=40) # noinspection PyPep8Naming def main(self): self._win() self.win.mainloop()
def make_eqution2(): list1 = root.pack_slaves() for l in list1: l.destroy() row = tk.Frame(root) combo_type = Combobox(row, width=20) combo_type.pack(side=tk.LEFT, padx=10) combo_type['values'] = ['Система', 'Уравнение 3 порядка'] combo_type.bind("<<ComboboxSelected>>", combo_type_callback) combo_type.current(1) row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5) ents = makeform(root, fields)
def hash_box(): win = Tk() # 构造窗体 def exit_os(): # 退出 win.quit() exit() def handle(*args): # 处理事件,*args表示可变参数 filename = str(askopenfilename()) hash_path, hash_file = os.path.split(filename) h = Hash(filename) if comboxlist.get() == "MD5": h.sava_hash(h.md5(), '.md5', hash_path) elif comboxlist.get() == "SHA1": h.sava_hash(h.sha1(), '.sha1', hash_path) elif comboxlist.get() == "SHA256": h.sava_hash(h.sha256(), '.sha256', hash_path) width = 250 height = 200 win.title(tk_title) win.iconbitmap(LOGO) screenwidth = win.winfo_screenwidth() screenheight = win.winfo_screenheight() aligner = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) win.geometry(aligner) comvalue = StringVar() # 窗体自带的文本,新建一个值S comboxlist = Combobox(win, textvariable=comvalue, state='readonly') # 初始化 comboxlist["values"] = ('选择方法', "MD5", "SHA1", "SHA256") comboxlist.current(0) # 选择第一个 comboxlist.bind("<<ComboboxSelected>>", handle) # 绑定事件,(下拉列表框被选中时,绑定handle()函数) comboxlist.place(relx=0.1, rely=0.4, width=200, height=35) Label(win, text='计算哈希', font=("微软雅黑", 16)).place(relx=0.11, rely=0.12, width=200, height=30) Button(win, text='确定', command=exit_os).place(relx=0.12, rely=0.75, width=80, height=30) Button(win, text='取消', command=exit_os).place(relx=0.56, rely=0.75, width=80, height=30) win.mainloop()
class AlgoSelGroup(Group): def __init__(self, *args, **kwargs): self._topwin = kwargs.pop('topwin') super().__init__(*args, **kwargs) self.__algorithm_list = Combobox(self, value=[], takefocus=1, stat='readonly', width=12) self.__algorithm_list['values'] = [] self.__algorithm_list.pack() self.__algorithm_list.bind('<<ComboboxSelected>>', self._on_algorithm_change) Button(self, text='Load Algorithm', command=self._on_load_algorithm).pack() Button(self, text='Reload', command=self._on_reload_algorithm).pack() self.name = 'Algorithms' @property def algorithm_list(self): return self.__algorithm_list def _on_algorithm_change(self, event): self._topwin.change_algorithm(event.widget.get()) def _on_load_algorithm(self): new_thread_do = self._topwin.root_node.thread_manager.new_thread_do main_thread_do = self._topwin.root_node.thread_manager.main_thread_do @new_thread_do def select_and_load(): class_info = ask_class_name('wavesynlib.algorithms', Algorithm) if not class_info: return module_name, class_name = class_info if isinstance(module_name, bytes): module_name = module_name.decode('utf-8') if isinstance(class_name, bytes): class_name = class_name.decode('utf-8') @main_thread_do() def load(): with code_printer(): self._topwin.load_algorithm(module_name=module_name, class_name=class_name) def _on_reload_algorithm(self): with code_printer(): self._topwin.current_algorithm.reload_algorithm()
def build_combobox_with_label(values, master, row, col, toggle_background_elements): def toggle_display(): for element in toggle_background_elements: if var.get() == 'True': element.configure(state='normal') elif var.get() == 'False': element.configure(state='disabled') frame = Frame(master=master, bg='#FFCFC9') frame.grid(row=row, column=col, padx=5) label = Label(master=frame, text='Is logged in: ', justify=LEFT) label.config(justify='right', bg='white') label.grid(row=0, column=0, pady=2.5) var = StringVar(master=frame, value=values[0]) cb = Combobox(master=frame, textvariable=var) cb['values'] = values cb.grid(row=0, column=1) cb.bind('<<ComboboxSelected>>', lambda x: (var.set(cb.get()), toggle_display())) if var.get() == 'False': for element in toggle_background_elements: element.configure(state='disabled') return frame, var
def _initsearchcondpanel(self): frame = Frame(self) frame.grid(row=0, column=1, sticky=E + W + S + N, padx=5) label = Label(frame, text="Search Condition: ") label.grid(row=0, column=0, columnspan=1, sticky=W) relationlable = Label(frame, text="Relation") relationlable.grid(row=0, column=1, columnspan=1, sticky=E) self.condrelationvar = StringVar(frame) relationinput = Combobox(frame, textvariable=self.condrelationvar, values=["and", "or"]) relationinput.grid(row=0, column=2, padx=5, sticky=E) relationinput.bind('<<ComboboxSelected>>', self._onrelationchange) self.searchcondlist = Listbox(frame) self.searchcondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N) vsl = Scrollbar(frame, orient=VERTICAL) vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W) hsl = Scrollbar(frame, orient=HORIZONTAL) hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N) self.searchcondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set) hsl.config(command=self.searchcondlist.xview) vsl.config(command=self.searchcondlist.yview) newbtn = Button(frame, text="New", width=7, command=self._addsearchcondition) newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E) delbtn = Button(frame, text="Delete", width=7, command=self._deletesearchcondition) delbtn.grid(row=3, column=1, sticky=E) modbtn = Button(frame, text="Update", width=7, command=self._modifysearchcondition) modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
from tkinter import * from tkinter.ttk import Combobox def cbox_do(event): 'Used for cbox.' clabel.config(text=cbox.get()) a = Tk() cbox = Combobox(a, value=('Luke','Biggs','Wedge'), takefocus=0) cbox.bind("<<ComboboxSelected>>", cbox_do) cbox.pack() clabel = Label(a) clabel.pack() a.mainloop() master = Tk() variable = StringVar(master) variable.set("one") w = Combobox(master, textvariable=variable, values=["one", "two", "three"]) w.pack() master.mainloop()
helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Help Index", command=donothing) helpmenu.add_command(label="About...", command=about) menubar.add_cascade(label="Help", menu=helpmenu) root.config(menu=menubar) filebox = Combobox(root, textvariable=filevar, values=openfiles, state='readonly') filebox.current(0) colorbox = Combobox(root, textvariable=colorvar, values=colors, state='readonly') colorbox.current(0) label1 = Label(root, textvariable = mode, bg="white", fg="black") label3 = Label(root, text="vakant", bg="white", fg="black") draw = Canvas(root, cursor="none", width=WidthHeight[0], height=WidthHeight[1]) draw.bind("<Motion>", functools.partial(motion, objects1=objects, keyes1=keyes, new1=new, arc=arc, WidthHeight=WidthHeight , color=color)) draw.bind("<Button-1>", functools.partial(paint, keyes1=keyes, snapp1=snapp, new1=new, arc=arc)) draw.bind_all("<KeyPress>", keypressed) filebox.bind("<<ComboboxSelected>>", fileop.changeactive) colorbox.bind("<<ComboboxSelected>>", fileop.colorset) filebox.grid(row=0, column=0, columnspan=1, sticky=W+E) colorbox.grid(row=0, column=1, columnspan=1, sticky=W+E) draw.grid(row=1, column=0, columnspan=10, sticky=W+E) label1.grid(row=2, column=0, columnspan=1, sticky=W+E) label3.grid(row=2, column=2, columnspan=8, sticky=W+E) root.mainloop()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) timer = TkTimer(widget=self, interval=200, active=False) self.__battery_images = battery_images = {} image_dir = Path(Scripting.root_node.get_gui_image_path('battery')) for image_name in ['10per', '25per', '50per', '75per', '100per', '10per_charge', '25per_charge', '50per_charge', '75per_charge', '100per_charge']: battery_images[image_name] = ImageTk.PhotoImage( file=str(image_dir/(image_name+'.png'))) self.__busy_images = busy_images = {} image_dir = Path(Scripting.root_node.get_gui_image_path('busysignal')) busy_images['busy'] = ImageTk.PhotoImage(file=str(image_dir/('busy'+'.png'))) busy_images['available'] = ImageTk.PhotoImage(file=str(image_dir/('available'+'.png'))) balloon = Scripting.root_node.gui.balloon self.__busy_lamp = busy_lamp = Label(self) busy_lamp['image'] = busy_images['available'] busy_lamp.pack(side='right', fill='y') balloon.bind_widget(busy_lamp, balloonmsg='''Main-thread status. Green: main-thread is available; Red: main-thread is busy.''') battery_meter = Label(self) battery_meter.pack(side='right', fill='y') battery_meter_tip = balloon.bind_widget(battery_meter, balloonmsg='Battery: ') def battery_meter_tip_show_callback(): battery_status = Scripting.root_node.interfaces.os.get_battery_status() if battery_status is None: return 'No battery detected.' else: return f'{battery_status.percent}%' battery_meter_tip.show_callback = battery_meter_tip_show_callback self.__membar = IntVar(0) self.__cpubar = IntVar(0) self._make_cpu_mem_status() # Transparent Scale { def on_scale(val): Scripting.root_node.gui.console.set_opacity(val) trans_scale = Scale(self, from_=0.2, to=1.0, orient='horizontal', value=1, command=on_scale) trans_scale.pack(side='right') balloon.bind_widget(trans_scale, balloonmsg='Set the opacity of the console.') # } End Transparent Scale # Topmost Button { import tkinter topmost_button = tkinter.Button(self, text='TOP', relief='groove') topmost_button.pack(side='right') def on_click(): console =Scripting.root_node.gui.console b = console.is_topmost fg = 'black' if b else 'lime green' topmost_button['fg'] = fg with code_printer(True): console.set_topmost(not b) topmost_button['command'] = on_click balloon.bind_widget(topmost_button, balloonmsg='Set the console as a topmost window.') # } End Topmost Button # Doc Button { docbtn = tkinter.Button(self, text='DOC', relief='groove') docbtn.pack(side='right') def on_click(): docwin = Scripting.root_node.gui.console.doc_window with code_printer(True): docwin.show_window() docbtn['command'] = on_click balloon.bind_widget(docbtn, balloonmsg='Show document window.') #} End Doc Window # Debug Button { debbtn = tkinter.Button(self, text='DEB', relief='groove') debbtn.pack(side='right') def on_click(): debwin = Scripting.root_node.gui.console.debug_window with code_printer(True): debwin.show_window() debbtn['command'] = on_click balloon.bind_widget(debbtn, balloonmsg='Show debug window.') #} End Debug Button #{ Window Combo window_combo = Combobox(self, value=[], takefocus=1, stat='readonly') def on_selected(event): text = event.widget.get() wid = int(text.split(':')[1].strip()) Scripting.root_node.gui.windows[wid].tk_object.deiconify() window_combo.bind('<<ComboboxSelected>>', on_selected) window_combo.pack(side='right', fill='y') # deiconify a window @Scripting.root_node.gui.windows.add_observer def on_windows_change(node, command): values = window_combo['values'] if values == '': values = [] if isinstance(values, tuple): values = list(values) node_id = id(node) if command == 'new': type_name = node.__class__.__name__ values.append(f'{type_name}: {node_id}') elif command == 'del': for index, value in enumerate(values): wid = int(value.split(':')[1].strip()) if node_id == wid: del values[index] window_combo['values'] = values if len(values) > 0: window_combo.current(len(values)-1) else: window_combo.set('') #} End Window Combo self.__lock = thread.allocate_lock() self.__busy = False os_node = Scripting.root_node.interfaces.os get_memory_usage = os_node.get_memory_usage get_cpu_usage = os_node.get_cpu_usage get_battery_status = os_node.get_battery_status def check_cpu_mem_battery(): with code_printer(print_=False): self.__membar.set(get_memory_usage()) self.__cpubar.set(get_cpu_usage()) battery_status = get_battery_status() if battery_status: percent = battery_status.percent if percent > 75: percent = 100 elif percent > 50: percent = 75 elif percent > 25: percent = 50 elif percent > 10: percent = 25 else: percent = 10 charge = '_charge' if battery_status.power_plugged else '' image_name = f'{percent}per{charge}' image = battery_images[image_name] if battery_meter['image'] != image: battery_meter['image'] = image timer.divider(divide_by=10).add_observer(check_cpu_mem_battery) timer.active = True
def run_with_gui(): root = Tk() root.title("PyEncConv") def browse_in(): name = askopenfilename() if name: in_txt.delete(0, END) in_txt.insert(END, name) def browse_out(): name = asksaveasfilename() if name: out_txt.delete(0, END) out_txt.insert(END, name) # input file f = Frame(root) f.pack(anchor=W, fill=X) Label(f, text="input file:").pack(side=LEFT) in_txt = Entry(f) in_txt.pack(fill=X, expand=True, side=LEFT) in_browse = Button(f, text="browse...", command=browse_in) in_browse.pack(side=LEFT) def load_file(): try: txt_area.delete(1.0, END) in_enc = in_enc_cmb.get() in_alias_lbl.config(text=(' '.join(get_alt_names(in_enc)))) with open(in_txt.get(), 'r', encoding=in_enc) as f: txt_area.insert(END, f.read()) except IOError as e: txt_area.insert(END, str(e)) except OSError as e: txt_area.insert(END, str(e)) except LookupError as e: txt_area.insert(END, str(e)) except Exception as e: txt_area.insert(END, str(e)) # input encoding f = Frame(root) f.pack(anchor=W, fill=X) Label(f, text="input encoding:").pack(side=LEFT) in_enc_cmb = Combobox(f) in_enc_cmb.pack(side=LEFT) in_enc_cmb['values'] = enc_set in_enc_cmb.insert(END, getpreferredencoding()) in_enc_cmb.bind('<Return>', lambda event:load_file()) in_alias_lbl = Label(f) in_alias_lbl.pack(side=LEFT) Button(root, text="Load for preview", command=load_file).pack(anchor=W) def disable_output_file(): out_txt.config(state=DISABLED) out_browse.config(state=DISABLED) def enable_output_file(): out_txt.config(state=NORMAL) out_browse.config(state=NORMAL) # output file out_choice = IntVar(value=1) Radiobutton(root, text="overwrite original (after moving to .bak)", variable = out_choice, value=1, command=disable_output_file).pack(anchor=W) f = Frame(root) f.pack(anchor=W, fill=X) Radiobutton(f, text="output file:", variable = out_choice, value=2, command=enable_output_file).pack(side=LEFT) out_txt = Entry(f, state=DISABLED) out_txt.pack(fill=X, expand=True, side=LEFT) out_browse = Button(f, text="browse...", command=browse_out, state=DISABLED) out_browse.pack(side=LEFT) # output encoding f = Frame(root) f.pack(anchor=W, fill=X) Label(f, text="output encoding:").pack(side=LEFT) out_enc_cmb = Combobox(f) out_enc_cmb.pack(side=LEFT) out_enc_cmb['values'] = enc_set out_enc_cmb.insert(END, 'UTF-8') out_alias_lbl = Label(f) out_alias_lbl.pack(side=LEFT) def convert(): try: txt_area.delete(1.0, END) in_enc = in_enc_cmb.get() in_alias_lbl.config(text=(' '.join(get_alt_names(in_enc)))) out_enc = out_enc_cmb.get() out_alias_lbl.config(text=(' '.join(get_alt_names(out_enc)))) src_file = in_txt.get() if out_choice.get() == 1: dest_file = None else: dest_file = out_txt.get() fileops.convert(src_file, in_enc, dest_file, out_enc) except IOError as e: txt_area.insert(END, str(e)) except OSError as e: txt_area.insert(END, str(e)) except LookupError as e: txt_area.insert(END, str(e)) except Exception as e: txt_area.insert(END, str(e)) Button(root, text='Convert', command=convert).pack(anchor=W) # Text Area f = Frame(root) f.pack(expand=True, fill=BOTH) txt_area = Text(f, height=8, width=10, wrap=NONE) v_scroll = Scrollbar(f, command=txt_area.yview) v_scroll.pack(side=RIGHT, fill=Y) h_scroll = Scrollbar(f, orient=HORIZONTAL, command=txt_area.xview) h_scroll.pack(side=BOTTOM, fill=X) txt_area.config(yscrollcommand=v_scroll.set, xscrollcommand=h_scroll.set) txt_area.pack(expand=True, fill=BOTH) root.update() root.pack_propagate(False) root.mainloop()
def makeentry(parent, caption, width=None, **options): Label(parent, text=caption).pack(side=LEFT) entry = Entry(parent, **options) if width: entry.config(width=width) entry.pack(side=LEFT) return entry # # user = makeentry(root, "User name:", 10) # password = makeentry(root, "Password:"******"*") # # def login_clicked(): # print(user.get(), password.get()) # # login = Button(root, text="Login", command=login_clicked, height="5") # login.pack(fill=BOTH) # îòîáðàçèòü íà îêíå def set(*args): print(combo.get()) e.delete(0, END) e.insert(0, combo.get()) combo = Combobox(root, values=['1', '2', '3'], state='readonly') combo.bind('<<ComboboxSelected>>', set) combo.pack() root.protocol('WM_DELETE_WINDOW', close) # çàêðîåòñÿ ïðèëîæåíèå ïî çàêðûòèþ îêíà root.mainloop() # çàïóñêàåì ïðîãðàììó
class ButtonsFrame(Frame): def print_hi(self): print('hi') def print_content(self,event): print(self.content.get()) def sendState(self): print(self.varState.get()) self.sendCmd({'type':'stateCMD','instr':self.varState.get()}) def sendEmergency(self): self.sendCmd({'type':'stateCMD','instr':'error'}) def sendMode(self,event): print(self.varMode.get()) self.sendCmd({'type':'modeCMD','instr':self.varMode.get()}) def sendPerc(self,event): print('perc:' + str(self.varPerc.get())) self.sendRigCmd({'type':'setCMD','instr':'setPumpPerc','percentage':self.varPerc.get()}) def sendDataDump(self,activate): print('DataDump ' + str(activate)) if (activate==True): self.sendRigCmd({'type':'testerCMD','instr':'activateDataDump'}) elif(activate==False): self.sendRigCmd({'type':'testerCMD','instr':'deactivateDataDump'}) def sendManual(self,instr): print('Send manual ' + instr) self.sendRigCmd({'type':'manualCMD','instr':instr}) def createWidgets(self): rowC =0 self.lblMode = Label(text='Mode:') self.lblMode.grid(row=rowC,column=0) self.varMode = StringVar() self.cmbMode = Combobox(values = ['auto_continue','stepthrough','singlestate'],textvariable = self.varMode) self.cmbMode.grid(row=rowC,column = 1) self.cmbMode.bind('<<ComboboxSelected>>',self.sendMode) self.lblState = Label(text='State:') self.lblState.grid(row=rowC,column = 2) self.varState = StringVar() self.lstStates = ["clearError","prime","fill","forceFill","idle","pump","setPressure","error","override","leakageTest","continue", "preempt", "waitIsolate","isolationTest", "preempt","terminate"] self.cmbState = Combobox(values = self.lstStates,textvariable = self.varState) self.cmbState.grid(row=rowC,column = 3) self.btnState = Button(text='Send state',command=self.sendState) self.btnState.grid(row=rowC,column = 4) self.btnEmer = Button(text= "EMERGENCY",command=self.sendEmergency,bg='red') self.btnEmer.grid(row=rowC,column = 6, columnspan=2, rowspan=2,sticky='nsew') rowC +=1 self.lblFbMode = Label(text = 'Mode:') self.lblFbMode.grid(row=rowC,column=0) self.varFbMode = StringVar() self.entMode = Entry(state = 'readonly',textvariable = self.varFbMode) self.entMode.grid(row=rowC,column=1) self.lblFbState = Label(text = 'State:') self.lblFbState.grid(row=rowC,column=2) self.varFbState = StringVar() self.entState = Entry(state = 'readonly',textvariable = self.varFbState) self.entState.grid(row=rowC,column=3) self.lblFbStep = Label(text = 'Step:') self.lblFbStep.grid(row=rowC,column=4) self.varFbStep = StringVar() self.entStep = Entry(state = 'readonly',textvariable = self.varFbStep) self.entStep.grid(row=rowC,column=5) rowC+=1 self.lblPerc = Label(text='Pump percentage:') self.lblPerc.grid(row=rowC, column=0) self.varPerc = DoubleVar() self.entPerc = Entry(textvariable = self.varPerc) self.entPerc.grid(row=rowC, column =1) self.entPerc.bind('<FocusOut>',self.sendPerc) self.btnActivateDump = Button(text = "Activate data dump",command = lambda:self.sendDataDump(True)) self.btnActivateDump.grid(row=rowC, column=2) self.btnActivateDump = Button(text = "Deactivate data dump",command = lambda:self.sendDataDump(False)) self.btnActivateDump.grid(row=rowC, column=3) rowC+=1 self.btnStartPump = Button(text = 'startPump',command = lambda:self.sendManual('startPump')) self.btnStartPump.grid(row=rowC,column=0,sticky='we') self.btnStartPump = Button(text = 'stopPump',command = lambda:self.sendManual('stopPump')) self.btnStartPump.grid(row=rowC,column=1,sticky='we') self.btnStartPump = Button(text = 'openInflow',command = lambda:self.sendManual('openInflowValve')) self.btnStartPump.grid(row=rowC,column=2,sticky='we') self.btnStartPump = Button(text = 'closeInflow',command = lambda:self.sendManual('closeInflowValve')) self.btnStartPump.grid(row=rowC,column=3,sticky='we') self.btnStartPump = Button(text = 'openOut',command = lambda:self.sendManual('openOutflowValve')) self.btnStartPump.grid(row=rowC,column=4,sticky='we') self.btnStartPump = Button(text = 'closeOut',command = lambda:self.sendManual('closeOutflowValve')) self.btnStartPump.grid(row=rowC,column=5,sticky='we') self.btnStartPump = Button(text = 'openRelease',command = lambda:self.sendManual('openReleaseValve')) self.btnStartPump.grid(row=rowC,column=6,sticky='we') self.btnStartPump = Button(text = 'closeRelease',command = lambda:self.sendManual('closeReleaseValve')) self.btnStartPump.grid(row=rowC,column=7,sticky='we') rowC+=1 self.lblReply = Label(text='Reply:') self.lblReply.grid(row=rowC,column=0,sticky='w') rowC+=1 self.txtReply = Text(wrap=WORD, height = 1) self.txtReply.grid(row=rowC,column = 0,columnspan=7) rowC+=1 self.lblWarning = Label(text='Warnings:') self.lblWarning.grid(row=rowC,column=0,sticky='w') self.scrlWarning = Scrollbar() rowC+=1 self.scrlWarning.grid(row=rowC,column = 7,sticky = 'nsw') self.txtWarning = Text(wrap=WORD, height = 5, state=DISABLED) self.txtWarning.grid(row=rowC,column = 0,columnspan=7,sticky='we') self.txtWarning['yscrollcommand'] = self.scrlWarning.set self.scrlWarning['command'] = self.txtWarning.yview rowC+=1 self.lblError = Label(text='Errors:') self.lblError.grid(row=rowC,column=0,sticky='w') self.scrlError = Scrollbar() rowC+=1 self.scrlError.grid(row=rowC,column = 7,sticky = 'nsw') self.txtError = Text(wrap=WORD, height = 5, state=DISABLED) self.txtError.grid(row=rowC,column = 0,columnspan=7,sticky='we') self.txtError['yscrollcommand'] = self.scrlError.set self.scrlError['command'] = self.txtError.yview rowC+=1 self.lblRigStatus = Label(text='Rig status:') self.lblRigStatus.grid(row=rowC,column=0,sticky='w') rowC+=1 self.txtRigStatus = Text(wrap=WORD, height = 30, width =40, state=DISABLED) self.txtRigStatus.grid(row=rowC,column = 0,columnspan=3,sticky='w') rowC-=1 self.lblAppStatus = Label(text='Main status:') self.lblAppStatus.grid(row=rowC,column=3,sticky='w') rowC+=1 self.scrlAppStatus = Scrollbar() self.scrlAppStatus.grid(row=rowC,column=7,sticky='wns') self.txtAppStatus = Text(wrap=WORD, height = 30, width =40, state=DISABLED) self.txtAppStatus.grid(row=rowC,column = 3,columnspan=4,sticky='e') def addWarningMsg(self,msg): self.txtWarning.config(state=NORMAL) self.txtWarning.insert(END, "\n"+json.dumps(msg)) self.txtWarning.config(state=DISABLED) def addErrorMsg(self,msg): self.txtError.config(state=NORMAL) self.txtError.insert(END, "\n"+json.dumps(msg)) self.txtError.config(state=DISABLED) def addReply(self,msg): self.txtReply.config(state=NORMAL) self.txtReply.delete(0.0,END) self.txtReply.insert(INSERT, json.dumps(msg)) self.txtReply.config(state=DISABLED) def __init__(self,sendCmd,sendRigCmd,master=None): Frame.__init__(self, master) self.grid(row=0,column = 0) self.createWidgets() self.sendCmd = sendCmd self.sendRigCmd = sendRigCmd
class CadGui(object): def __init__(self,root): self.root = root root.title("APOS CAD") self.xy1 = StringVar() self.mode = StringVar() self.IdEntry = StringVar() self.XEntry = StringVar() self.XEntry.trace('w',self.numbers_val) self.YEntry = StringVar() self.YEntry.trace('w',self.numbers_val) self.ZEntry = StringVar() self.ZEntry.trace('w',self.numbers_val) self.CodeEntry = StringVar() self.WidthHeight = [800,500] self.filevar = StringVar() # Filebox self.openfiles = [data.data[0][1]] self.colorvar = StringVar() #Colorbox self.colors = ["Red","Green","Blue","Cyan","Magenta","Yellow","Black","khaki","Orange"] self.scroll = IntVar() # Scaltefactor self.scroll.set(1) self.wheel = IntVar() # Wheel self.wheel.set(1) self.savedyx = [0,0] # Last canvas xy for calc self.modyx = [self.WidthHeight[1],0] # Moved origo self.modyxset = [0,0] # moved origo hold self.Map_XY = [0,0] # Crosshairs place on map self.xy1 = StringVar() self.mode = StringVar() self.keyes_w = [0,0] self.keyes = ["nn"] self.snapp = ["so"] self.snapp_xy = [0,0,0] self.new = [0] def passit(): pass self.menubar = Menu(root) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="New", command= self.newfile) self.filemenu.add_command(label="Open", command= self.openfile) self.filemenu.add_command(label="Save", command= self.save) self.filemenu.add_command(label="Save as...", command= self.saveas) self.filemenu.add_command(label="Close", command= self.close) self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self.root.quit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.editmenu = Menu(self.menubar, tearoff=0) self.editmenu.add_command(label="Undo", command=passit()) self.editmenu.add_separator() self.editmenu.add_command(label="Cut", command=passit()) self.editmenu.add_command(label="Copy", command=passit()) self.editmenu.add_command(label="Paste", command=passit()) self.editmenu.add_command(label="Delete", command=passit()) self.editmenu.add_command(label="Select All", command=passit()) self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.drawmenu = Menu(self.menubar, tearoff=0) self.drawmenu.add_command(label="Point D>P", command=functools.partial(self.keypressed,event='<tkinter.Event object>', char1=['d','p'])) self.drawmenu.add_command(label="Line D>L", command=functools.partial(self.keypressed,event='<tkinter.Event object>', char1=['d','l'])) self.drawmenu.add_separator() self.drawmenu.add_command(label="ARC_3p A>3", command=functools.partial(self.keypressed,event='<tkinter.Event object>', char1=['a','3'])) self.menubar.add_cascade(label="Draw", menu=self.drawmenu) self.snappmenu = Menu(self.menubar, tearoff=0) self.snappmenu.add_command(label="Point S>P", command=functools.partial(self.keypressed,event='<tkinter.Event object>', char1=['s','p'])) self.snappmenu.add_command(label="NoSnapp S>O", command=functools.partial(self.keypressed,event='<tkinter.Event object>', char1=['s','o'])) self.menubar.add_cascade(label="Snapp", menu=self.snappmenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="Help", command=passit()) self.helpmenu.add_command(label="About...", command=passit()) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.root.config(menu=self.menubar) self.filebox = Combobox(root, textvariable=self.filevar, values=self.openfiles, state='readonly') self.filebox.current(0) self.colorbox = Combobox(root, textvariable=self.colorvar, values=self.colors, state='readonly') self.colorbox.current(data.data[0][0]) self.draw = Canvas(root, cursor="none", width=self.WidthHeight[0], height=self.WidthHeight[1]) self.label1 = Label(root, textvariable = self.mode, bg="white", fg="black") self.label2 = Label(root, textvariable = self.xy1, bg="white", fg="black") self.label3 = Label(root, textvariable = self.scroll, bg="white", fg="black") self.label4 = Label(root, text = "Tools", bg="white", fg="black") self.xyzgroup = LabelFrame(root, text="Insert", padx=5, pady=5,width=100,height=self.WidthHeight[1]) self.ID = Label(self.xyzgroup,text="Id:") self.IdE = Entry(self.xyzgroup, textvariable = self.IdEntry) self.XT = Label(self.xyzgroup,text="X:") self.XE = Entry(self.xyzgroup, textvariable = self.XEntry) self.YT = Label(self.xyzgroup,text="Y:") self.YE = Entry(self.xyzgroup, textvariable = self.YEntry) self.ZT = Label(self.xyzgroup,text="Z:") self.ZE = Entry(self.xyzgroup, textvariable = self.ZEntry) self.CT = Label(self.xyzgroup,text="Code:") self.CE = Entry(self.xyzgroup, textvariable = self.CodeEntry) self.ok = Button(self.xyzgroup, text='Add', command = self.OkRespons) self.draw.bind("<Motion>",functools.partial(self.motion, WidthHeight=self.WidthHeight, moving = 0)) self.draw.bind("<Button-1>", self.MouseRespons ) self.draw.bind_all("<KeyPress>", functools.partial(self.keypressed, char1='none')) # Scrollwheel self.draw.bind("<MouseWheel>", functools.partial(self.motion, WidthHeight=self.WidthHeight, moving = 2)) #win/osx self.draw.bind("<Button-4>", functools.partial(self.motion, WidthHeight=self.WidthHeight, moving = 2)) #linux self.draw.bind("<Button-5>", functools.partial(self.motion, WidthHeight=self.WidthHeight, moving = 2)) #linux # middlebutton + move self.draw.bind("<B2-Motion>",functools.partial(self.motion, WidthHeight=self.WidthHeight, moving=1)) self.filebox.bind("<<ComboboxSelected>>", lambda f: self.colorbox.current(data.data[self.filebox.current()][0])) self.colorbox.bind("<<ComboboxSelected>>", lambda c: data.change_color(self.filebox.current(),self.colorbox.current())) self.filebox.grid(row=0, rowspan = 1, column=2, columnspan=1, sticky=W+E) self.colorbox.grid(row=0, rowspan = 1, column=3, columnspan=1, sticky=W+E) self.draw.grid(row=1,column=2, columnspan=9, sticky=W+E) self.xyzgroup.grid(row=1, column=0, columnspan=2, sticky=W+E+N) self.ID.grid(row=0, rowspan = 1,column=0, columnspan=1) self.IdE.grid(row=0, rowspan = 1,column=1, columnspan=1) self.XT.grid(row=1, rowspan = 1,column=0, columnspan=1) self.XE.grid(row=1, rowspan = 1,column=1, columnspan=1) self.YT.grid(row=2, rowspan = 1,column=0, columnspan=1) self.YE.grid(row=2, rowspan = 1,column=1, columnspan=1) self.ZT.grid(row=3, rowspan = 1,column=0, columnspan=1) self.ZE.grid(row=3, rowspan = 1,column=1, columnspan=1) self.CT.grid(row=4, rowspan = 1,column=0, columnspan=1) self.CE.grid(row=4, rowspan = 1,column=1, columnspan=1) self.ok.grid(row=5, rowspan = 1,column=1, columnspan=1) self.label4.grid(row=0, rowspan = 1, column=0, columnspan=2, sticky=W+E) self.label1.grid(row=2, rowspan = 1, column=2, columnspan=1, sticky=W+E) self.label2.grid(row=2, rowspan = 1, column=3, columnspan=1, sticky=W+E) self.label3.grid(row=2, rowspan = 1, column=4, columnspan=1, sticky=W+E) self.root.resizable(0,0) self.draw.focus_set() def newfile(self): data.new_file() self.openfiles.append(data.data[-1][1]) self.filebox['values'] = self.openfiles def save(self): currentfile = self.filebox.current() if len(data.data[currentfile][2]) > 0: data.save_file(currentfile,data.data[currentfile][2]) else: print('nono') def saveas(self): currentfile = self.filebox.current() data.save_file(currentfile,filedialog.asksaveasfilename(defaultextension=".cad")) self.openfiles[currentfile] = data.data[currentfile][1] self.filebox['values'] = self.openfiles self.filebox.current(currentfile) print(currentfile) print(data.data) def openfile(self): data.open_file(filedialog.askopenfilename()) self.openfiles.append(data.data[-1][1]) self.filebox['values'] = self.openfiles print(data.data) def close(self): currentfile = self.filebox.current() data.close_file(currentfile) self.openfiles.pop(currentfile) self.filebox['values'] = self.openfiles self.filebox.current(0) print(data.data) def keypressed(self,event,char1): # Short commands print(event) if char1 == 'none': chars = [event.char] else: chars = char1 command_sel = { "nn": "none", "nn": "none", "d" : "Draw:","dp": "Draw: Point", "dl" : "Draw: Line", "a" : "Arc:", "a3" : "Arc: 3point", "s" : "Snapp:", "sp": "Snapp: Point", "so":"Snapp: Off" } for char in chars: if char == chr(27): self.draw.focus_set() self.mode.set("") del self.keyes_w[:] del self.keyes[:] del self.snapp[:] self.keyes_w.append(0) self.keyes_w.append(0) self.keyes.append("nn") self.snapp.append("so") self.new[0] = 1 else: if self.draw.focus_get()== self.draw: if len(self.keyes_w) == 2 : if char == "n": # flag for new object self.new[0] = 1 elif char not in command_sel: print("not in dict") else: del self.keyes_w[:] self.keyes_w.append(char) elif len(self.keyes_w) == 1: self.keyes_w.append(char) if self.keyes_w[0]+self.keyes_w[1] not in command_sel: print("not in dict") self.keyes_w.pop() print(self.keyes_w) if len(self.keyes_w) == 2 and self.keyes_w[0] != "s" : del self.keyes[:] self.keyes.append(self.keyes_w[0]+self.keyes_w[1]) if len(self.keyes_w) == 2 and self.keyes_w[0] == "s" : del self.snapp[:] self.snapp.append(self.keyes_w[0]+self.keyes_w[1]) # Show active mode if len(self.keyes_w) == 1: if self.keyes_w[0] == "s": self.mode.set(command_sel[self.keyes[0]]+">>"+command_sel[self.keyes_w[0]]) else: self.mode.set(command_sel[self.keyes_w[0]]+">>"+command_sel[self.snapp[0]]) if len(self.keyes_w) == 2: self.mode.set(command_sel[self.keyes[0]]+">>"+command_sel[self.snapp[0]]) return def MouseRespons(self,event): if self.snapp[0] != 'so' and len(data.data[self.filebox.current()][3][0]) == 0: pass else: data.paint(self.IdE.get(),int(self.Map_XY[0]),int(self.Map_XY[1]),0, self.CE.get(), self.keyes, self.snapp, self.new, self.filebox.current()) self.new[0] = 0 def OkRespons(self): if len(self.XE.get()) > 0 and len(self.YE.get()) > 0 and len(self.ZE.get()) > 0: data.paint(self.IdE.get(),int(float(self.XE.get())*1000),int(float(self.YE.get())*1000),int(float(self.ZE.get())*1000), self.CE.get(), self.keyes, self.snapp, self.new, self.filebox.current()) self.new[0] = 0 def numbers_val(self, *args): XE = self.XEntry.get() YE = self.YEntry.get() ZE = self.ZEntry.get() XEN = [""] YEN = [""] ZEN = [""] Xdott = False Ydott = False Zdott = False numbers = '0123456789.,' for char in XE: if char in numbers: if char == '.' or char == ',': if Xdott == True: pass elif char == ',': XEN[0] += '.' Xdott = True else: XEN[0] += '.' Xdott = True else: XEN[0] += char for char in YE: if char in numbers: if char == '.' or char == ',': if Ydott == True: pass elif char == ',': YEN[0] += '.' Ydott = True else: YEN[0] += '.' Ydott = True else: YEN[0] += char for char in ZE: if char in numbers: if char == '.' or char == ',': if Zdott == True: pass elif char == ',': ZEN[0] += '.' Zdott = True else: ZEN[0] += '.' Zdott = True else: ZEN[0] += char self.XEntry.set(XEN[0]) self.YEntry.set(YEN[0]) self.ZEntry.set(ZEN[0]) def motion(self,event,WidthHeight, moving): # mouse event responsese and draw the canvas # Catching events Canvas_YX = [event.y , event.x] # Respons to Linux/Windows wheel event if moving == 2: # CHECK !!! if event.num == 5 or event.delta == -120: # CHECK !!! if self.wheel.get() > 1: self.wheel.set(self.wheel.get() - 1) self.scroll.set(self.wheel.get()*self.wheel.get()) self.modyx[0] += Canvas_YX[0]/(1/self.scroll.get())-Canvas_YX[0]/(1/((self.wheel.get()+1)*(self.wheel.get()+1))) self.modyx[1] += Canvas_YX[1]/(1/self.scroll.get())-Canvas_YX[1]/(1/((self.wheel.get()+1)*(self.wheel.get()+1))) if event.num == 4 or event.delta == 120: # CHECK !!!! self.wheel.set(self.wheel.get() + 1) self.scroll.set(self.wheel.get()*self.wheel.get()) self.modyx[0] += Canvas_YX[0]/(1/self.scroll.get())-Canvas_YX[0]/(1/((self.wheel.get()-1)*(self.wheel.get()-1))) self.modyx[1] += Canvas_YX[1]/(1/self.scroll.get())-Canvas_YX[1]/(1/((self.wheel.get()-1)*(self.wheel.get()-1))) # Respons to B2-Motion CHECK! if moving == 0: self.savedyx[0] = Canvas_YX[0] self.savedyx[1] = Canvas_YX[1] if self.modyxset[:] != self.modyx[:]: self.modyxset[:] = self.modyx[:] if moving == 1: self.modyx[0]= self.modyxset[0] + (Canvas_YX[0] - self.savedyx[0]) / (1/self.scroll.get()) self.modyx[1]= self.modyxset[1] + (Canvas_YX[1] - self.savedyx[1]) / (1/self.scroll.get()) # Map coord CHECK! self.Map_XY[1] = -self.modyx[1] - ((Canvas_YX[1] * -1) / (1/self.scroll.get())) self.Map_XY[0] = self.modyx[0] - (Canvas_YX[0] / (1/self.scroll.get())) # Transalte operation CHECK! def modifying_XtoY(value): scroll = self.scroll.get() y = 0 y = Canvas_YX[0] - ((value - self.Map_XY[0])*1/scroll) return y def modifying_YtoX(value): scroll = self.scroll.get() x = 0 x = Canvas_YX[1] + ((value - self.Map_XY[1])*1/scroll) return x def zoomit(value): return (value / (1/self.scroll.get())) def findOjectNear(): pass # Draws the shit. self.draw.delete(ALL) # Clear the canvas self.xy1.set("N = %0.3fm E = %0.3fm " % (float(self.Map_XY[0])/1000,float(self.Map_XY[1])/1000)) self.draw.create_rectangle(0, 0, WidthHeight[0], WidthHeight[1], fill="white") # Origo_lines self.draw.create_line(modifying_YtoX(0),modifying_XtoY(-10),modifying_YtoX(0),modifying_XtoY(zoomit(Canvas_YX[0])+ self.Map_XY[0]), fill="black", dash=(4,4)) self.draw.create_line(modifying_YtoX(-10),modifying_XtoY(0),modifying_YtoX(zoomit(WidthHeight[0]-Canvas_YX[1])+ self.Map_XY[1]),modifying_XtoY(0), fill="black",dash=(4,4)) # Arcfunction used in "DrawIt()" def tk_arc_calculate(arc1): oxy = [] angels = [] r1 = [] coord = [] check = [] try: oxy.append((((arc1[3]**2-arc1[1]**2+arc1[2]**2-arc1[0]**2)/(2*(arc1[2]-arc1[0])))-((arc1[5]**2-arc1[3]**2+arc1[4]**2-arc1[2]**2)/(2*(arc1[4]-arc1[2])))) /(((arc1[3]-arc1[5])/(arc1[4]-arc1[2]))-((arc1[1]-arc1[3])/(arc1[2]-arc1[0])))) oxy.append((oxy[0]*((arc1[1]-arc1[3])/(arc1[2]-arc1[0])))+((arc1[3]**2-arc1[1]**2+arc1[2]**2-arc1[0]**2)/(2*(arc1[2]-arc1[0])))) except ZeroDivisionError: oxy.append((arc1[1]+arc1[5])/2) oxy.append((arc1[0]+arc1[4])/2) oxy.reverse() r1.append(math.sqrt((arc1[1]-oxy[1])**2+(arc1[0]-oxy[0])**2)) # Radius angels.append((math.atan((arc1[1]-oxy[1])/(arc1[0]-oxy[0]))*57.29577951)) #Degrees point angels.append((math.atan((arc1[5]-oxy[1])/(arc1[4]-oxy[0]))*57.29577951)) #Degrees point check.append((math.atan((arc1[3]-oxy[1])/(arc1[2]-oxy[0]))*57.29577951)) #Degrees point # Point one if (arc1[0]-oxy[0]) < 0: angels[0] = angels[0] + 180 if (arc1[0]-oxy[0]) > 0 and (arc1[1]-oxy[1]) < 0: angels[0] = angels[0] + 360 # Point two if (arc1[4]-oxy[0]) < 0: angels[1] = angels[1] + 180 if (arc1[4]-oxy[0]) > 0 and (arc1[5]-oxy[1]) < 0: angels[1] = angels[1] + 360 # Check point if (arc1[2]-oxy[0]) < 0: check[0] = check[0] + 180 if (arc1[2]-oxy[0]) > 0 and (arc1[3]-oxy[1]) < 0: check[0] = check[0] + 360 if angels[0] > angels[1]: angels.reverse() if check[0] < angels[0] or check[0] > angels[1]: #print("Wrong") angels[0] = 360 - angels[0] angels[1] = 360 + (360 - angels[1] - angels[0]) #print(angels) else: angels[0] = 360 - angels[0] angels[1] = 360 - angels[1] - angels[0] if angels[1] > 0: angels[1] *= -1 # Now wee got a raidus, two angels and a center point. coord = [oxy[0] - r1[0],oxy[1] + r1[0],oxy[0] + r1[0], oxy[1] - r1[0]] return [coord, angels,r1,oxy] # Arcfunction for large radius def Arc_as_line(center_x,center_y,radius,start,extent): points = [] slices = int(radius) * 2 if extent < 0: start,extent = extent + start,start elif extent > 0: extent += start if extent > 360: extent -= 360 start,extent = 360 - extent,360 - start currentAngle = start * (math.pi*2)/360 # startAngle in radians endAngle = extent * (math.pi*2)/360 # endAngle in radians def findxy(center_x,center_y,radius,currentAngle,endAngle,slices): for i in range(slices): px = center_x + radius * math.cos(currentAngle) py = center_y + radius * math.sin(currentAngle) points.append((int(px), int(py))) currentAngle += ((math.pi*2)/slices) if currentAngle >= endAngle: px = center_x + radius * math.cos(endAngle) py = center_y + radius * math.sin(endAngle) points.append((int(px), int(py))) break if currentAngle >= endAngle: findxy(center_x,center_y,radius,currentAngle,math.pi*2,slices) findxy(center_x,center_y,radius,0,endAngle,slices) else: findxy(center_x,center_y,radius,currentAngle,endAngle,slices) return points # Draw everything for file in range(len(data.data)): current = self.filebox.current() def DrawIt(): index = len(data.data[file][3][5]) linexy = [] # For linedraw arc1 = [] tk_arc = [] for x,y,thetype in zip(data.data[file][3][1],data.data[file][3][2],data.data[file][3][5]): # Draw points if thetype == "dp": self.draw.create_oval(modifying_YtoX(y) - 2 , modifying_XtoY(x) - 2 , modifying_YtoX(y) + 2, modifying_XtoY(x) + 2, fill=self.colors[data.data[file][0]]) # Draw lines if thetype == "dl": linexy.append(modifying_YtoX(y)) linexy.append(modifying_XtoY(x)) elif thetype == "/dl": linexy.append(modifying_YtoX(y)) linexy.append(modifying_XtoY(x)) self.draw.create_line(linexy,fill=self.colors[data.data[file][0]]) del linexy linexy = [] # Draw arcs if thetype == "a3": arc1.append(modifying_YtoX(y)) arc1.append(modifying_XtoY(x)) elif thetype == "/a3": arc1.append(modifying_YtoX(y)) arc1.append(modifying_XtoY(x)) tk_arc = tk_arc_calculate(arc1) #self.draw.create_arc(tk_arc[0],start=tk_arc[1][0],extent=tk_arc[1][1], style="arc", outline=self.colors[data.data[file][0]]) if tk_arc[2][0] > 1: arcline = Arc_as_line(tk_arc[3][0],tk_arc[3][1],tk_arc[2][0],tk_arc[1][0],tk_arc[1][1]) self.draw.create_line(arcline,fill=self.colors[data.data[file][0]]) arcline = [] tk_arc = [] arc1 = [] # If only one linepoint paint dott if index > 0: if data.data[file][3][5][index - 1] == "dl": self.draw.create_oval(modifying_YtoX(y) - 2 , modifying_XtoY(x) - 2 , modifying_YtoX(y) + 2, modifying_XtoY(x) + 2, fill=self.colors[data.data[file][0]]) # Draw last linepoint to cross if file == current: if index >= 1: if self.keyes[0] == "dl" and self.new[0] == 0 and data.data[file][3][5][index - 1] == "/dl" or data.data[file][3][5][index - 1] == "dl": linexy.append(modifying_YtoX(data.data[file][3][2][index - 1])) linexy.append(modifying_XtoY(data.data[file][3][1][index - 1])) linexy.append(Canvas_YX[1]) linexy.append(Canvas_YX[0]) self.draw.create_line(linexy,fill=self.colors[data.data[file][0]]) # Draw arc as you paint if len(data.arc) == 6 and self.Map_XY[0] != data.arc[0] and self.Map_XY[1] != data.arc[1] and self.Map_XY[0] != data.arc[3] and self.Map_XY[1] != data.arc[4] and ( data.arc[0]*(data.arc[4]-self.Map_XY[1]) + data.arc[3]*(self.Map_XY[1]-data.arc[1]) + self.Map_XY[0]*(data.arc[1]-data.arc[4]) ) != 0: tk_arc = tk_arc_calculate([modifying_YtoX(data.arc[1]),modifying_XtoY(data.arc[0]), modifying_YtoX(data.arc[4]),modifying_XtoY(data.arc[3]), modifying_YtoX(self.Map_XY[1]),modifying_XtoY(self.Map_XY[0])]) #self.draw.create_arc(tk_arc[0],start=tk_arc[1][0],extent=tk_arc[1][1], style="arc", outline=self.colors[data.data[file][0]]) if tk_arc[2][0] > 1: arcline = Arc_as_line(tk_arc[3][0],tk_arc[3][1],tk_arc[2][0],tk_arc[1][0],tk_arc[1][1]) self.draw.create_line(arcline,fill=self.colors[data.data[file][0]]) print(len(arcline)) arcline = [] # Crosshair self.draw.create_line(Canvas_YX[1], 0, Canvas_YX[1], WidthHeight[1], fill="black") self.draw.create_line(0, Canvas_YX[0], WidthHeight[0], Canvas_YX[0], fill="black") self.draw.create_rectangle(Canvas_YX[1] - 10,Canvas_YX[0] - 10,Canvas_YX[1] + 10 ,Canvas_YX[0] + 10, outline="black") DrawIt() # Show snapp point if self.snapp[0] == "sp" and len(data.data[self.filebox.current()][3][1]) > 0: maxl = 0 minl = 0 for xy in range(len(data.data[self.filebox.current()][3][1])): l = math.sqrt((self.Map_XY[0] - data.data[self.filebox.current()][3][1][xy])**2+(self.Map_XY[1] - data.data[self.filebox.current()][3][2][xy])**2) if l > minl: maxl = l minl = maxl for xyz in range(len(data.data[self.filebox.current()][3][1])): l = math.sqrt((self.Map_XY[0] - data.data[self.filebox.current()][3][1][xyz])**2+(self.Map_XY[1] - data.data[self.filebox.current()][3][2][xyz])**2) if l <= minl: minl = l del self.snapp_xy[:] self.snapp_xy.append(data.data[self.filebox.current()][3][1][xyz]) self.snapp_xy.append(data.data[self.filebox.current()][3][2][xyz]) self.snapp_xy.append(data.data[self.filebox.current()][3][3][xyz]) self.draw.create_rectangle(modifying_YtoX(self.snapp_xy[1]) - 5,modifying_XtoY(self.snapp_xy[0]) - 5,modifying_YtoX(self.snapp_xy[1]) + 5 ,modifying_XtoY(self.snapp_xy[0]) + 5, width=2, outline="black")
class Gr(): def __init__(self,root,data,SCRY=None): self.data=data self.columns=[x for x in range(1,8)]+['day'] root.rowconfigure(1,weight=1) root.columnconfigure(0,weight=1) root.columnconfigure(1,weight=1) root.columnconfigure(2,weight=1) f=Frame(root) f.columnconfigure(0,weight=1) f.rowconfigure(1,weight=1) self.v=Combobox(root) self.v.grid(row=0,column=0) self.v.bind('<<ComboboxSelected>>',self.select_ver) f.grid(row=1,column=0,columnspan=3,sticky=N+S) self.tree=Treeview(f, columns=self.columns, displaycolumns=['day']+self.columns[:-1], show='headings') #self.tree.tag_configure('odd',background='white') #self.tree.tag_configure('even',background='gray') self.tree.tag_configure('dif',foreground='brown') self.tree.tag_configure('work',background='white') self.tree.tag_configure('short',background='#F5EFE0') self.tree.tag_configure('rest',background='#E0B0B0') self.tree.tag_configure('holyday',background='#E7B7A4') for c in self.columns: self.tree.heading(c,text=c) self.tree.column(c,width=65,anchor='center') self.tree.column('day',width=30) scrX=Scrollbar(f,orient='horizontal',command=self.tree.xview) self.tree['xscrollcommand']=scrX.set if not SCRY: self.scrY=Scrollbar(f,orient='vertical',command=self.yview) self.tree['yscrollcommand']=self.scrY.set else: self.tree['yscrollcommand']=SCRY.set self.tree.grid(row=1,column=0,sticky=N+S) if not SCRY: self.scrY.grid(row=1,column=1,sticky=N+S) scrX.grid(row=2,column=0,sticky=E+W) def set(self,y,m): self.y=y self.m=m self.show() def yview(self,*args): self.tree.yview(*args) self.yview2(*args) def yview2(self,*args): pass def show(self): d=self.data[self.y][self.m] V=list(d['degur'].keys()) self.v['values']=V self.v.set(V[0]) self.select_ver() def select_ver(self,*e): self.tree.delete(*self.tree.get_children()) d=self.data[self.y][self.m] offset=d['offset'] v=self.v.get() col=[] for i,deg in enumerate(d['degurs']): self.tree.heading(i+1,text=deg) col.append(i+1) self.tree.configure(displaycolumns=['day']+col) items=dict() if 'табель' in d['degur']: a=[''.join(x) for x in zip(*[[x for x in d['degur']['план'][j]] \ for j in d['degurs']])] b=[''.join(x) for x in zip(*[[x for x in d['degur']['табель'][j]] \ for j in d['degurs']])] c=[x!=y for x,y in zip(a,b)] else: c=[False]*32 for i in range(1,d['days']+1): tag = (i+offset) % 7 in [0,6] and 'rest' or 'work' if i in d['holydays'] : tag='holyday' elif i in d['restdays'] : tag='rest' elif i in d['shortdays'] : tag='short' elif i in d['workdays'] : tag='work' if c[i]: tag=[tag,'dif'] ii=self.tree.insert('','end',values=['-','-','-','-','-'],tag=tag) self.tree.set(ii,column='day',value=i) items[i]=ii for j,s in d['degur'][v].items(): # j-degur if not s: continue for i,val in enumerate(s[1:-1]): if val=='J': val='до' elif val=='j': val='од' elif val=='a': val='10' self.tree.set(items[i+1],column=d['degurs'].index(j)+1,value=val) if s[0]=='Н': if s[1]=='-': self.tree.set(items[1],column=d['degurs'].index(j)+1,value='Н(8)') else: self.tree.set(items[1],column=d['degurs'].index(j)+1,value='!') if s[-2]=='Н': if s[-1]=='-': self.tree.set(items[len(s)-2],column=d['degurs'].index(j)+1,value='Н(4)') else: self.tree.set(items[len(s)-2],column=d['degurs'].index(j)+1,value='!') self.calc(self.y,self.m) def calc(self,y,m): d=self.data[y][m] offset=d['offset'] WH=0 for i in range(1,d['days']+1): if i in d['holydays']: wh=0 elif i in d['restdays'] : wh=0 elif i in d['shortdays'] : wh=7 elif i in d['workdays'] : wh=8 elif (i+offset) % 7 in [0,6]: wh=0 else: wh=8 WH+=wh
entry.config(width=width) entry.pack(side=LEFT) return entry # # user = makeentry(root, "User name:", 10) # password = makeentry(root, "Password:"******"*") # # def login_clicked(): # print(user.get(), password.get()) # # login = Button(root, text="Login", command=login_clicked, height="5") # login.pack(fill=BOTH) # отобразить на окне def set(*args): print(combo.get()) e.delete(0, END) e.insert(0, combo.get()) combo = Combobox(root, values=["1", "2", "3"], state="readonly") combo.bind("<<ComboboxSelected>>", set) combo.pack() root.protocol("WM_DELETE_WINDOW", close) # закроется приложение по закрытию окна root.mainloop() # запускаем программу
class EntryVidget( Vidget, Eventor, ): """ EntryVidget contains a main Frame and an Entry widget. The entry widget takes all space of the main frame. The main frame can be used to configure the size of the entry widget. EntryVidget adds the following abilities: - Simplify the use of validator function. - Notify pre-change and and post-change events. """ # Default validator function _DEFAULT_VALIDATOR = (lambda x: True) # Event notified when text is to be changed TEXT_CHANGE_SOON = 'TEXT_CHANGE_SOON' # Event notified when text is changed TEXT_CHANGE_DONE = 'TEXT_CHANGE_DONE' def __init__( self, text=None, validator=None, widget_type=None, master=None, ): """ Initialize object. @param text: Initial text. Default is empty. @param validator: Validator function that determines whether text entered by user or set by `text_set` method is valid. The validator function takes the new value as argument and returns True if the new value is valid. @param widget_type: One of ['Entry', 'Spinbox', 'Combobox']. Default is 'Entry'. @param master: Master widget. @return: None. """ # Initialize Vidget. # Create main frame widget. Vidget.__init__(self, master=master) # Initialize Eventor Eventor.__init__(self) # If widget type is None or `Entry` if widget_type is None or widget_type == 'Entry': # Create Entry widget self._text_widget = Entry(master=self.widget()) # If widget type is `Spinbox` elif widget_type == 'Spinbox': # Create Spinbox widget self._text_widget = Spinbox(master=self.widget()) # If widget type is `Combobox` elif widget_type == 'Combobox': # Create Combobox widget self._text_widget = Combobox(master=self.widget()) # If widget type is something else else: # Raise error raise ValueError(widget_type) # Set the text widget as config target self.config_target_set(self._text_widget) # Whether the text widget's value is changing self._is_changing = False # Old widget state self._old_widget_state = NORMAL # Validator function self._validator = validator \ if validator is not None else EntryVidget._DEFAULT_VALIDATOR # Create validator wrapper self._validator_wrapper = self._validator_wrapper_create() # Register the validator wrapper with Tkinter. Get reference ID. self._validator_wrapper_ref_id = \ self.text_widget().winfo_toplevel().register( self._validator_wrapper ) # Mount the validator wrapper to the text widget self._validator_wrapper_mount() # If the text widget is Combobox if isinstance(self._text_widget, Combobox): # Bind selected event to event handler self._text_widget.bind( '<<ComboboxSelected>>', self._on_combobox_selected ) # Cached text self._text = self._text_widget.get() # Set initial text self.text_set(text if text is not None else '', notify=False) # Update widget self._widget_update() def _widget_update(self): """ Update widget config and layout. @return: None. """ # Do not use children to compute main frame's geometry self.widget().grid_propagate(False) # Configure layout weights for children self.widget().rowconfigure(0, weight=1) self.widget().columnconfigure(0, weight=1) # Lay out the text widget to take all space of the main frame self._text_widget.grid( in_=self.widget(), row=0, column=0, sticky='NSEW', ) def text_widget(self): """ Get the text widget. @return: Text widget. """ # Return the text widget return self._text_widget def text(self): """ Get cached text. `self._text` and `self._text_widget.get()` usually give same value. But from within the validator wrapper at 3Q7EB, when the new value is being validated, the new value is only available in `self._text`. Tkinter widget's interval value has not been updated yet. @return: Cached text. """ # Return the cached text return self._text def text_set( self, text, notify=True, notify_arg=None, is_validator=False, ): """ Set text. @param text: Text to set. @param notify: Whether notify text change events. @param notify_arg: Event argument. @param is_validator: Whether caller is validator. @return: None. """ # If the text is not valid if not self.text_is_valid(text): # Raise error raise ValueError('Text is not valid: {}'.format(text)) # If the text is valid. # If the text is changing if self._is_changing: # Raise error raise ValueError('Text is changing') # If the text is not changing. # Set text changing flag on self._is_changing = True # If notify event if notify: # Notify pre-change event self.handler_notify( self.TEXT_CHANGE_SOON, arg=notify_arg, need_info=True, ) # Cache the text self._text = text # If caller is not validator, # need change text widget's value. if not is_validator: # Unmount the validator wrapper before changing text widget's value self._validator_wrapper_unmount() # Set text widget to NORMAL state self.state_set(NORMAL) # Delete the old text from text widget. # This will not trigger validation because the validator wrapper # has been unmounted. self._text_widget.delete(0, END) # Insert the new text into text widget. self._text_widget.insert(0, text) # Set text widget to previous state self.state_set_back() # Mount the validator wrapper after changing text widget's value self._validator_wrapper_mount() # If caller is validator # no need change text widget's value. # If the cached text is not EQ text widget's value if self._text != self._text_widget.get(): # If caller is not validator if not is_validator: # Set changing flag off self._is_changing = False # Raise error raise ValueError( 'Inconsistent state. `{}` != `{}`'.format( repr(self._text), repr(self._text_widget.get()), ) ) # If caller is validator, # this is normal because text widget's value will be updated after # the validator returns. # If notify event if notify: # Notify post-change event self.handler_notify( self.TEXT_CHANGE_DONE, arg=notify_arg, need_info=True, ) # Set changing flag off self._is_changing = False def enabled(self): """ Test whether the text widget is not in DISABLED state. @return: Boolean. """ # Get the text widget's state. One of [NORMAL, DISABLED, ACTIVE]. state = str(self.text_widget()['state']) # Test whether the text widget is not in DISABLED state return state != DISABLED def disabled(self): """ Test whether the text widget is in DISABLED state. @return: Boolean. """ # Get the text widget's state. One of [NORMAL, DISABLED, ACTIVE]. state = str(self.text_widget()['state']) # Test whether the text widget is in DISABLED state return state == DISABLED def state_set(self, state): """ Set the text widget's state. @param state: State to set. @return: None. """ # If given state is not valid if state not in [NORMAL, DISABLED, ACTIVE]: # Raise error raise ValueError(state) # If given state is valid. # Store old state self._old_widget_state = str(self.text_widget()['state']) # Set new state self.text_widget()['state'] = state def state_set_back(self): """ Set the text widget to old state. @return: None. """ # If old state is not valid if self._old_widget_state not in [NORMAL, DISABLED, ACTIVE]: # Raise error raise ValueError(self._old_widget_state) # If old state is valid. # Set the text widget to old state self.text_widget()['state'] = self._old_widget_state def is_changing(self): """ Test whether the text widget's value is changing. @return: Boolean. """ # Return whether the text widget's value is changing return self._is_changing def text_is_valid(self, text): """ Test whether given text is valid according to validator. @param text: Text to test. @return: Boolean. """ # Return whether given text is valid according to validator return self._validator(text) def _validator_wrapper_create(self): """ Create validator wrapper. The wrapper calls original validator to validate the new text value. If the new text value is valid, the wrapper will set the text widget to the new value, and notify text change events. @return: Validator function wrapper. """ # 3Q7EB # Create validator wrapper def validator_wrapper(new_value): # If the text widget is changing if self._is_changing: # Raise error raise ValueError('Text is changing') # If the validator function is not given if self._validator is None: # Set validation result to True is_valid = True # If the validator function is given else: try: # Get validation result is_valid = self._validator(new_value) # If have error except Exception: # Set validation result to False is_valid = False # If the new value is valid if is_valid: # If the text widget is changing if self._is_changing: # Raise error raise ValueError('Text is changing') # Set the text widget's value. # Notify text change events. self.text_set( new_value, notify=True, is_validator=True, ) # If the text widget is changing if self._is_changing: # Raise error raise ValueError('Text is changing') # If the new value is not valid, # do nothing. # Return the validation result return is_valid # Return the validator wrapper return validator_wrapper def _validator_wrapper_mount(self): """ Mount the validator wrapper to the text widget. @return: None. """ # Mount the validator wrapper to the text widget self.text_widget().config( # Validation type validate='key', # Validator function reference ID, and argument type. # Argument type `%P` means the new value. validatecommand=(self._validator_wrapper_ref_id, '%P') ) def _validator_wrapper_unmount(self): """ Unmount the validator wrapper from the text widget. @return: None. """ # Unmount the validator wrapper from the text widget. # Notice `validatecommand=None` does not work. self.text_widget().config(validatecommand='') def _on_combobox_selected(self, event): """ Combobox selected event handler. @param event: Tkinter event object. @return: None. """ # Get new value new_value = self.text_widget().get() # If the new value is not valid if not self._validator(new_value): # Set old value back self.text_widget().set(self._text) # If the new value is valid else: # Set the new value. # Notify text change events. self.text_set(new_value, notify=True)
def _popupjoincondwindow(self, index=-1): if index < 0: cond = JoinSearchCondition(("", "")) tofilename = "" else: condtuple = self._getselectedfile().joincondtuples[index] cond = condtuple[0] tofilename = condtuple[1] window = Toplevel(self) title = Label(window, text="New Search Condition") title.grid(row=0, column=0, padx=5, pady=5, sticky=W + N) filenamelabel = Label(window, text="Target Field Name: ") filenamelabel.grid(row=1, column=0, padx=5, pady=5, sticky=W) filevar = StringVar(window) filenameinput = Combobox(window, textvariable=filevar, values=self.filelist.get(0, END), width=30) filenameinput.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=W) fromfieldlabel = Label(window, text="Field in From File: ") fromfieldlabel.grid(row=3, column=0, padx=5, pady=5, sticky=W) fromfields = csvhandler.getfields(self._getselectedfile().filename) fromfieldvar = StringVar(window) fieldinput = Combobox(window, textvariable=fromfieldvar, values=fromfields, width=20) fieldinput.grid(row=3, column=1, columnspan=2, padx=5, pady=5, sticky=W) tofieldlabel = Label(window, text="Field in Target File: ") tofieldlabel.grid(row=4, column=0, padx=5, pady=5, sticky=W) tofields = [] tofieldvar = StringVar(window) tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20) tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) def updatetofieldinput(evt): if filevar.get() is not None and len(filevar.get()) > 0: tofields = csvhandler.getfields(filevar.get()) window.grid_slaves(4, 1)[0].grid_forget() tofieldinput = Combobox(window, textvariable=tofieldvar, values=tofields, width=20) tofieldinput.grid(row=4, column=1, columnspan=2, padx=5, pady=5, sticky=W) filenameinput.bind('<<ComboboxSelected>>', updatetofieldinput) # init value filevar.set(tofilename) fromfieldvar.set(cond.fieldtuple[0]) updatetofieldinput(None) tofieldvar.set(cond.fieldtuple[1]) def _newcond(): '''create new condition ''' cond = JoinSearchCondition((fromfieldvar.get(), tofieldvar.get())) tofilename = filevar.get() selectedfile = self._getselectedfile() if index < 0: selectedfile.joincondtuples.append((cond, tofilename)) else: del selectedfile.joincondtuples[index] selectedfile.joincondtuples[index:index] = [(cond, tofilename)] self._inflatejoincondlist(selectedfile.joincondtuples) window.destroy() okbtn = Button(window, text="Confirm", width=7, command=_newcond) okbtn.grid(row=6, column=1, rowspan=1, columnspan=1, sticky=E, padx=5, pady=5) clsbtn = Button(window, text="Close", width=7, command=lambda: window.destroy()) clsbtn.grid(row=6, column=2, rowspan=1, columnspan=1, sticky=W, padx=5, pady=5)
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 FenOptions: def __init__(self): self.root=Tk() self.root.title('Donjon & Python-Option') self.root.bind('<F12>', switchDebug) #--------Barres de volume------# self.varVolumeGlobal = IntVar() self.varVolumeGlobal.set(Audio.volumeGlobal) self.varVolumeMusique = IntVar() self.varVolumeMusique.set(Audio.volumeMusic) self.varVolumeSons = IntVar() self.varVolumeSons.set(Audio.volumeSound) self.scaleVolumeGlobal = Scale(self.root,from_=0, to=100,resolution=1, orient=HORIZONTAL, length=300,width=20, label="Volume principal", tickinterval=20, variable=self.varVolumeGlobal, command = self.setVolumeGlobal) self.scaleVolumeMusique = Scale(self.root,from_=0, to=100,resolution=1,orient=HORIZONTAL, length=300, width=20, label="Volume Musique", tickinterval=20, variable=self.varVolumeMusique, command = self.setVolumeMusique) self.scaleVolumeSons = Scale(self.root, from_=0, to=100, resolution=1, orient=HORIZONTAL, length=300, width=20, label="Volume Bruitages", tickinterval=20, variable=self.varVolumeSons, command = self.setVolumeSons) self.scaleVolumeGlobal.set(Audio.volumeGlobal) self.scaleVolumeMusique.set(Audio.volumeMusic) self.scaleVolumeSons.set(Audio.volumeSound) self.scaleVolumeGlobal.pack(padx=10,pady=10) self.scaleVolumeMusique.pack(padx=10,pady=10) self.scaleVolumeSons.pack(padx=10,pady=10) #-----Sélection des textures----# Label(self.root, text='Texture Pack :').pack() self.box = Combobox(self.root, values=listdir('TexturePack'), state='readonly') self.box.bind('<<ComboboxSelected>>', self.selectionnerPack) self.box.current(0) self.box.pack() def selectionnerPack(self, event) : global texturePack texturePack = self.box.get() def run(self): self.root.mainloop() Audio.volumeGlobal = volume Audio.setVolumeMusic() def setVolumeGlobal(self, volume): Audio.volumeGlobal = volume Audio.setVolumeMusic() def setVolumeMusique(self, volume): Audio.volumeMusic = volume Audio.setVolumeMusic() def setVolumeSons(self, volume): Audio.volumeSound = volume
class SimUI(object): def __init__(self, manager, fake_time, config_obj): """ initializes all default values and creates a board, waits for run() to be called to start the board manager - sim manager class instance """ self.manager = manager self.fake_time = fake_time self.config_obj = config_obj # Set up idle_add self.queue = queue.Queue() self.root = tk.Tk() self.root.wm_title("PyFRC Robot Simulator v%s" % __version__) self.root.protocol("WM_DELETE_WINDOW", self._delete_window) # setup mode switch frame = tk.Frame(self.root) frame.pack(side=tk.TOP, anchor=tk.W) self._setup_widgets(frame) self.root.resizable(width=0, height=0) # Allow extending the simulation from 3rd party libraries # -> TODO: better API for this self.extensions = [] for ep in iter_entry_points(group="robotpysim", name=None): try: extension = ep.load() except ImportError: logger.debug("Error importing extension '%s'", ep.name, exc_info=True) else: logger.debug("Loaded simulation extension '%s'", ep.name) extension = extension() if hasattr(extension, "update_tk_widgets"): self.extensions.append(extension) self.mode_start_tm = 0 self.text_id = None # connect to the controller self.manager.on_mode_change( lambda mode: self.idle_add(self.on_robot_mode_change, mode) ) self.on_robot_mode_change(self.manager.get_mode()) # create pygame joystick if supported try: from .pygame_joysticks import UsbJoysticks except ImportError: logger.warn("pygame not detected, real joystick support not loaded") self.usb_joysticks = None else: self.usb_joysticks = UsbJoysticks(self) logger.info("pygame was detected, real joystick support loaded!") try: self.root.lift() self.root.attributes("-topmost", True) self.root.attributes("-topmost", False) except Exception: pass self.timer_fired() def _delete_window(self): self.root.destroy() if self.usb_joysticks is not None: self.usb_joysticks.close() def _setup_widgets(self, frame): top = tk.Frame(frame) top.grid(column=0, row=0) bottom = tk.Frame(frame) bottom.grid(column=0, row=1) self.field = RobotField(frame, self.manager, self.config_obj) self.field.grid(column=1, row=0, rowspan=2) # status bar self.status = tk.Label(frame, bd=1, relief=tk.SUNKEN, anchor=tk.E) self.status.grid(column=0, row=2, columnspan=2, sticky=tk.W + tk.E) # analog slot = tk.LabelFrame(top, text="Analog") self.analog = [] for i in range(len(hal_data["analog_in"])): if ( hal_data["analog_in"][i]["initialized"] or hal_data["analog_out"][i]["initialized"] ): label = tk.Label(slot, text=str(i)) label.grid(column=0, row=i + 1) vw = ValueWidget(slot, clickable=True, minval=-10.0, maxval=10.0) vw.grid(column=1, row=i + 1) self.set_tooltip(vw, "analog", i) else: vw = None self.analog.append(vw) slot.pack(side=tk.LEFT, fill=tk.Y, padx=5) # digital slot = tk.LabelFrame(top, text="Digital") label = tk.Label(slot, text="PWM") label.grid(column=0, columnspan=4, row=0) self.pwm = [] for i in range(len(hal_data["pwm"])): if hal_data["pwm"][i]["initialized"]: c = i // 10 label = tk.Label(slot, text=str(i)) label.grid(column=0 + 2 * c, row=1 + i % 10) vw = ValueWidget(slot) vw.grid(column=1 + 2 * c, row=1 + i % 10) self.set_tooltip(vw, "pwm", i) else: vw = None self.pwm.append(vw) label = tk.Label(slot, text="Digital I/O") label.grid(column=4, columnspan=6, row=0) self.dio = [] for i in range(len(hal_data["dio"])): if hal_data["dio"][i]["initialized"]: c = i // 9 label = tk.Label(slot, text=str(i)) label.grid(column=4 + c * 2, row=1 + i % 9) pi = PanelIndicator(slot, clickable=True) pi.grid(column=5 + c * 2, row=1 + i % 9) self.set_tooltip(pi, "dio", i) else: pi = None self.dio.append(pi) label = tk.Label(slot, text="Relay") label.grid(column=10, columnspan=2, row=0, padx=5) self.relays = [] for i in range(len(hal_data["relay"])): if hal_data["relay"][i]["initialized"]: label = tk.Label(slot, text=str(i)) label.grid(column=10, row=1 + i, sticky=tk.E) pi = PanelIndicator(slot) pi.grid(column=11, row=1 + i) self.set_tooltip(pi, "relay", i) else: pi = None self.relays.append(pi) slot.pack(side=tk.LEFT, fill=tk.Y, padx=5) self.csfm = csfm = tk.Frame(top) # solenoid (pcm) self.pcm = {} # values self.values = {} # CAN self.can_slot = tk.LabelFrame(csfm, text="CAN") self.can_slot.pack(side=tk.LEFT, fill=tk.BOTH, expand=1, padx=5) self.can = {} csfm.pack(side=tk.LEFT, fill=tk.Y) # joysticks slot = tk.LabelFrame(bottom, text="Joysticks") self.joysticks = [] for i in range(4): axes = [] buttons = [] col = 1 + i * 3 row = 0 label = tk.Label(slot, text="Stick %s" % i) label.grid(column=col, columnspan=3, row=row) row += 1 # TODO: make this configurable for j, t in enumerate(["X", "Y", "Z", "T", "4", "5"]): label = tk.Label(slot, text=t) label.grid(column=col, row=row) vw = ValueWidget(slot, clickable=True, default=0.0) vw.grid(column=col + 1, row=row, columnspan=2) self.set_joy_tooltip(vw, i, "axes", t) axes.append(vw) row += 1 # POV: this needs improvement label = tk.Label(slot, text="POV") label.grid(column=col, row=row) pov = ValueWidget( slot, clickable=True, default=-1, minval=-1, maxval=360, step=45, round_to_step=True, ) pov.grid(column=col + 1, row=row, columnspan=2) row += 1 for j in range(1, 11): var = tk.IntVar() ck = tk.Checkbutton(slot, text=str(j), variable=var) ck.grid(column=col + 1 + (1 - j % 2), row=row + int((j - 1) / 2)) self.set_joy_tooltip(ck, i, "buttons", j) buttons.append((ck, var)) self.joysticks.append((axes, buttons, [pov])) slot.pack(side=tk.LEFT, fill=tk.Y, padx=5) ctrl_frame = tk.Frame(bottom) # timing control timing_control = tk.LabelFrame(ctrl_frame, text="Time") def _set_realtime(): if realtime_mode.get() == 0: step_button.pack_forget() step_entry.pack_forget() self.on_pause(False) else: step_button.pack(fill=tk.X) step_entry.pack() self.on_pause(True) realtime_mode = tk.IntVar() button = tk.Radiobutton( timing_control, text="Run", variable=realtime_mode, value=0, command=_set_realtime, ) button.pack(fill=tk.X) button = tk.Radiobutton( timing_control, text="Pause", variable=realtime_mode, value=1, command=_set_realtime, ) button.pack(fill=tk.X) step_button = tk.Button(timing_control, text="Step", command=self.on_step_time) self.step_entry = tk.StringVar() self.step_entry.set("0.025") step_entry = tk.Entry(timing_control, width=6, textvariable=self.step_entry) Tooltip.create(step_button, "Click this to increment time by the step value") Tooltip.create(step_entry, "Time to step (in seconds)") realtime_mode.set(0) timing_control.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # simulation control sim = tk.LabelFrame(ctrl_frame, text="Robot") self.state_buttons = [] self.mode = tk.IntVar() def _set_mode(): self.manager.set_mode(self.mode.get()) button = tk.Radiobutton( sim, text="Disabled", variable=self.mode, value=self.manager.MODE_DISABLED, command=_set_mode, ) button.pack(fill=tk.X) self.state_buttons.append(button) button = tk.Radiobutton( sim, text="Autonomous", variable=self.mode, value=self.manager.MODE_AUTONOMOUS, command=_set_mode, ) button.pack(fill=tk.X) self.state_buttons.append(button) button = tk.Radiobutton( sim, text="Teleoperated", variable=self.mode, value=self.manager.MODE_OPERATOR_CONTROL, command=_set_mode, ) button.pack(fill=tk.X) self.state_buttons.append(button) button = tk.Radiobutton( sim, text="Test", variable=self.mode, value=self.manager.MODE_TEST, command=_set_mode, ) button.pack(fill=tk.X) self.state_buttons.append(button) self.robot_dead = tk.Label(sim, text="Robot died!", fg="red") sim.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # # Set up a combo box that allows you to select an autonomous # mode in the simulator # try: from tkinter.ttk import Combobox except: pass else: auton = tk.LabelFrame(ctrl_frame, text="Autonomous") self.autobox = Combobox(auton, state="readonly") self.autobox.bind("<<ComboboxSelected>>", self.on_auton_selected) self.autobox["width"] = 12 self.autobox.pack(fill=tk.X) Tooltip.create( self.autobox, "Use robotpy_ext.autonomous.AutonomousModeSelector to use this selection box", ) from networktables.util import ChooserControl self.auton_ctrl = ChooserControl( "Autonomous Mode", lambda v: self.idle_add(self.on_auton_choices, v), lambda v: self.idle_add(self.on_auton_selection, v), ) auton.pack(side=tk.TOP) messages = self.config_obj["pyfrc"]["game_specific_messages"] if messages: gamedata = tk.LabelFrame(ctrl_frame, text="Game Data") self.gamedataval = tk.StringVar() if hasattr(self.gamedataval, "trace_add"): self.gamedataval.trace_add("write", self.on_gamedata_selected) else: self.gamedataval.trace_variable("w", self.on_gamedata_selected) self.gamedatabox = Combobox(gamedata, textvariable=self.gamedataval) self.gamedatabox["width"] = 12 self.gamedatabox.pack(fill=tk.X) self.gamedatabox["values"] = messages self.gamedatabox.current(0) self.manager.game_specific_message = self.gamedatabox.get() Tooltip.create( self.gamedatabox, "Use this selection box to simulate game specific data", ) gamedata.pack(side=tk.TOP) def _reset_robot(): for robot in self.manager.robots: robot.physics_controller.reset_position() button = tk.Button(ctrl_frame, text="Reset Robot", command=_reset_robot) button.pack(side=tk.TOP) ctrl_frame.pack(side=tk.LEFT, fill=tk.Y) def _render_pcm(self): for k, data in sorted(hal_data["pcm"].items()): if k not in self.pcm: slot = tk.LabelFrame(self.csfm, text="Solenoid (PCM %s)" % k) solenoids = [] self.pcm[k] = solenoids for i in range(len(data)): label = tk.Label(slot, text=str(i)) c = int(i / 2) * 2 r = i % 2 label.grid(column=0 + c, row=r) pi = PanelIndicator(slot) pi.grid(column=1 + c, row=r) self.set_tooltip(pi, "solenoid", i) solenoids.append(pi) slot.pack(side=tk.TOP, fill=tk.BOTH, padx=5) solenoids = self.pcm[k] for i, ch in enumerate(data): sol = solenoids[i] if not ch["initialized"]: sol.set_disabled() else: sol.set_value(ch["value"]) def _render_values(self): for k, v in hal_data["robot"].items(): if not k.endswith("_angle"): continue gyro_label = self.values.get(k) if not gyro_label: gyro_label = self._create_value(k, k, "Angle (Degrees)") gyro_label["text"] = "%.3f" % v for i, gyro in enumerate(hal_data["analog_gyro"]): if not gyro["initialized"]: continue k = "Gyro %s" % i gyro_label = self.values.get(k) if not gyro_label: gyro_label = self._create_value(k, k, "Angle (Degrees)") gyro_label["text"] = "%.3f" % gyro["angle"] for i, encoder in enumerate(hal_data["encoder"]): if not encoder["initialized"]: continue k = "Encoder %s" % i label = self.values.get(k) if not label: txt = "Encoder (%s,%s)" % ( encoder["config"]["ASource_Channel"], encoder["config"]["BSource_Channel"], ) label = self._create_value(k, txt, "Count / Distance") label["text"] = "%s / %.3f" % ( encoder["count"], encoder["count"] * encoder["distance_per_pulse"], ) for k, v in hal_data.get("custom", {}).items(): label = self.values.get(k) if not label: label = self._create_value(k, k, k) if isinstance(v, float): label["text"] = "%.3f" % v else: label["text"] = str(v) def _create_value(self, key, text, tooltip): slot = tk.LabelFrame(self.csfm, text=text) label = tk.Label(slot) label.pack(side=tk.TOP, fill=tk.BOTH) slot.pack(side=tk.TOP, fill=tk.BOTH, padx=5) self.values[key] = label Tooltip.create(label, tooltip) return label def idle_add(self, callable, *args): """Call this with a function as the argument, and that function will be called on the GUI thread via an event This function returns immediately """ self.queue.put((callable, args)) def __process_idle_events(self): """This should never be called directly, it is called via an event, and should always be on the GUI thread""" while True: try: callable, args = self.queue.get(block=False) except queue.Empty: break callable(*args) def run(self): # and launch the thread self.root.mainloop() # This call BLOCKS def timer_fired(self): """Polling loop for events from other threads""" self.__process_idle_events() # grab the simulation lock, gather all of the # wpilib objects, and display them on the screen self.update_widgets() # call next timer_fired (or we'll never call timer_fired again!) delay = 100 # milliseconds self.root.after(delay, self.timer_fired) # pause, then call timer_fired again def update_widgets(self): # TODO: support multiple slots? # joystick stuff if self.usb_joysticks is not None: self.usb_joysticks.update() # analog module for i, (ain, aout) in enumerate( zip(hal_data["analog_in"], hal_data["analog_out"]) ): aio = self.analog[i] if aio is not None: if ain["initialized"]: aio.set_disabled(False) ain["voltage"] = aio.get_value() elif aout["initialized"]: aio.set_value(aout["voltage"]) # digital module for i, ch in enumerate(hal_data["dio"]): dio = self.dio[i] if dio is not None: if not ch["initialized"]: dio.set_disabled() else: # determine which one changed, and set the appropriate one ret = dio.sync_value(ch["value"]) if ret is not None: ch["value"] = ret for i, ch in enumerate(hal_data["pwm"]): pwm = self.pwm[i] if pwm is not None: pwm.set_value(ch["value"]) for i, ch in enumerate(hal_data["relay"]): relay = self.relays[i] if relay is not None: if ch["fwd"]: relay.set_on() elif ch["rev"]: relay.set_back() else: relay.set_off() # solenoid self._render_pcm() # gyro/encoder self._render_values() # joystick/driver station # sticks = _core.DriverStation.GetInstance().sticks # stick_buttons = _core.DriverStation.GetInstance().stick_buttons for i, (axes, buttons, povs) in enumerate(self.joysticks): joy = hal_data["joysticks"][i] jaxes = joy["axes"] for j, ax in enumerate(axes): jaxes[j] = ax.get_value() jbuttons = joy["buttons"] for j, (ck, var) in enumerate(buttons): jbuttons[j + 1] = True if var.get() else False jpovs = joy["povs"] for j, pov in enumerate(povs): jpovs[j] = int(pov.get_value()) for extension in self.extensions: extension.update_tk_widgets(self) self.field.update_widgets() tm = self.fake_time.get() mode_tm = tm - self.mode_start_tm self.status.config(text="Time: %.03f mode, %.03f total" % (mode_tm, tm)) def set_tooltip(self, widget, cat, idx): tooltip = self.config_obj["pyfrc"][cat].get(str(idx)) if tooltip is not None: Tooltip.create(widget, tooltip) def set_joy_tooltip(self, widget, idx, typ, idx2): tooltip = self.config_obj["pyfrc"]["joysticks"][str(idx)][typ].get(str(idx2)) if tooltip is not None: Tooltip.create(widget, tooltip) def on_auton_choices(self, choices): self.autobox["values"] = choices[:] def on_auton_selection(self, selection): self.autobox.set(selection) def on_auton_selected(self, e): self.auton_ctrl.setSelected(self.autobox.get()) def on_gamedata_selected(self, *args): self.manager.game_specific_message = self.gamedatabox.get() def on_robot_mode_change(self, mode): self.mode.set(mode) self.mode_start_tm = self.fake_time.get() # this is not strictly true... a robot can actually receive joystick # commands from the driver station in disabled mode. However, most # people aren't going to use that functionality... controls_disabled = ( False if mode == self.manager.MODE_OPERATOR_CONTROL else True ) state = tk.DISABLED if controls_disabled else tk.NORMAL for axes, buttons, povs in self.joysticks: for axis in axes: axis.set_disabled(disabled=controls_disabled) for ck, var in buttons: ck.config(state=state) for pov in povs: pov.set_disabled(disabled=controls_disabled) if not self.manager.is_alive(): for button in self.state_buttons: button.config(state=tk.DISABLED) self.robot_dead.pack() # # Time related callbacks # def on_pause(self, pause): if pause: self.fake_time.pause() else: self.fake_time.resume() def on_step_time(self): val = self.step_entry.get() try: tm = float(self.step_entry.get()) except ValueError: tk.messagebox.showerror( "Invalid step time", "'%s' is not a valid number" % val ) return if tm > 0: self.fake_time.resume(tm)
class LevelWindow(object): """Fenêtre de configuration du niveau de l'algorithme""" def __init__(self, parent): # Dictionnaire contenant les paramètres self.lv_param={} self.lv_param['niveau'] = 5 self.lv_param['seuil'] = 60 self.lv_param['échantillons'] = 100 # Initialisation et création de la fenêtre self.window = Toplevel(parent) self.window.geometry("580x160") self.window.title("Paramètres") self.window.resizable(False, False) self.window.protocol("WM_DELETE_WINDOW", self.valide) self.window.bind("<Return>", self.valide) Label(self.window,text="Niveau de l'algorithme",font=(FONT, 16)).pack(pady=5) self.frame_param = Frame(self.window) self.frame_param.pack(fill=BOTH, padx=10, pady=10) # Choix du niveau self.cb_lv = Combobox(self.frame_param, values=["Niveau 1", "Niveau 2", "Niveau 3", "Niveau 4", "Niveau 5", "Niveau 6"], state="readonly") self.cb_lv.pack(side=LEFT) self.cb_lv.current(4) self.cb_lv.bind("<<ComboboxSelected>>", self.on_cb_change) # Paramètres supplémentaires self.lb_param = Label(self.frame_param, text="") self.txt_param = Text(self.frame_param, height=1, width=6) self.txt_param.insert(END, "0") # Informations sur les niveaux self.infos_niveaux = ["Niveau 1 : Que des tirs aléatoires uniformes sans file d'attente", "Niveau 2 : Tirs aléatoires uniformes et file d'attente", "Niveau 3 : Tirs aléatoires sur les cases noires et file d'attente", "Niveau 4 : Optimisation par des échantillons", "Niveau 5 : Optimisation par nombre de bateaux local", "Niveau 6 : Optimisation par énumération de tous les arrangements à partir d'un seuil"] frame_infos = Frame(self.window) frame_infos.pack(fill=X) self.lb_info = Label(frame_infos, justify=LEFT, pady=5) self.lb_info['text'] = self.infos_niveaux[self.cb_lv.current()] self.lb_info.pack(side=LEFT, padx=10) Button(self.window, text="Valider", command=self.valide).pack(side=BOTTOM, pady=5) def on_cb_change(self, event=None) : """Quand on change le niveau""" self.cb_lv.selection_clear() niveau = self.cb_lv.current()+1 self.lv_param['niveau'] = niveau self.lb_info['text'] = self.infos_niveaux[self.cb_lv.current()] # Pour les niveaux 4 et 6, paramètres supplémentaires if niveau == 4 : self.lb_param['text'] = "Échantillons : " self.txt_param.delete('1.0', END) self.txt_param.insert(END, "100") self.lb_param.pack(side=LEFT, padx=10) self.txt_param.pack(side=LEFT) elif niveau == 6 : self.lb_param['text'] = "Seuil : " self.txt_param.delete('1.0', END) self.txt_param.insert(END, "60") self.lb_param.pack(side=LEFT, padx=10) self.txt_param.pack(side=LEFT) else : self.lb_param.pack_forget() self.txt_param.pack_forget() def valide(self, event=None): """Validation des paramètres""" self.lv_param['seuil'] = int(self.txt_param.get('1.0', END)[:-1]) self.lv_param['échantillons'] = int(self.txt_param.get('1.0', END)[:-1]) self.window.destroy()
class AppGUI(Frame): def __init__(self, master=None): # Avoiding to send it continuously. self.lock = False Frame.__init__(self, master) self.grid() self.master = master # Setting for ComboBox. self.url_lang_combobox_str = StringVar() self.url_lang_combobox_list = lang_list # UI components. self.receiver_email_text = Label(self, text="Receiver:") self.receiver_email_field = Entry(self, width=50) self.subject_text = Label(self, text='Subject:') self.subject_field = Entry(self, width=50) self.receiver_name_text = Label(self, text='Name:') self.receiver_name_field = Entry(self, width=50) self.url_lang_text = Label(self, text='Link lang:') self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly') self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300) self.send_button = Button(self, text='Send', command=self._send_mail) self.quit_button = Button(self, text='Exit', command=self.__exit) self.log_msg_text = ScrolledText(self) # Attachment. self.mail_attachment_list = attachment_list[:] self.url_lang_link_title = None self.url_lang_link = copy.deepcopy(content_link) # Mailer self._mailer = None # Let Mailer can control components. Mailer.window_content = self self.__create_widgets() def _send_mail(self): if not self.lock: threading.Thread(target=self.__send_mail).start() else: messagebox.showinfo('Warning', "Now it's processing...") def _choose(self, event): # arr = self.url_lang_link.get(self.url_lang_combobox_str.get()) # Get the array by choosing language. pass def _modify_content_url_link(self): link_arr = self.url_lang_link.get(self.url_lang_combobox_str.get()) content = self._mailer.content for index in range(len(link_arr)): content_index = content.index(self.url_lang_link_title[index]) + len(self.url_lang_link_title[index]) content = content[:content_index] + '\n' + link_arr[index] + content[content_index:] self._mailer.content = content return False def _make_mailer(self): self.mail_attachment_list = attachment_list[:] # Clone a list. if atta_lang_list[self.url_lang_combobox.current()]: for i in range(len(self.mail_attachment_list)): # Only from the third file to the end file can change language. if i > 2: # Modify the file name. att = self.mail_attachment_list[i].split('.') self.mail_attachment_list[i] = ''.join([' ', atta_lang_list[self.url_lang_combobox.current()], '.']).join(att) # ** IMPORTANT, we set the content path here!! path = 'content.docx' if self.url_lang_combobox.get() == lang_list[2] or self.url_lang_combobox.get() == lang_list[3]: path = 'content chinese.docx' if debug_log: print(self.mail_attachment_list) # ** IMPORTANT, we have to new an object here. Otherwise, we couldn't check the error checking. return Mailer(content_path=path, attachment_list=self.mail_attachment_list) def __create_widgets(self): """ Construct all of the UI components. """ self.receiver_email_text.grid(row=0, column=0) self.receiver_email_field.grid(row=0, column=1, columnspan=6) self.subject_text.grid(row=1, column=0) self.subject_field.grid(row=1, column=1, columnspan=6) self.subject_field.insert(0, 'Osaka Mariko Apartment Location & Condition') self.receiver_name_text.grid(row=2, column=0) self.receiver_name_field.grid(row=2, column=1, columnspan=6) self.url_lang_text.grid(row=3, column=0) self.url_lang_combobox.grid(row=3, column=2, columnspan=2) self.send_progressbar.grid(row=4, column=0, columnspan=7) self.send_button.grid(row=5, column=2) self.quit_button.grid(row=5, column=3) self.log_msg_text.grid(row=6, column=0, columnspan=7) # Default setting. self.url_lang_combobox.current(0) self.url_lang_combobox.bind("<<ComboboxSelected>>", self._choose) def __exit(self): if not self.lock: self.log_msg_text.insert(END, '\n\n -- Bye Bye --\n') self.master.quit() else: messagebox.showinfo('Error', "Now it's processing...please wait it ;)") @DecoratorThreadLockerApp() @DecoratorErrorCheckAndInitApp() def __send_mail(self): self.send_progressbar.start() # Start processing the progress. ending = 'Welcome to use my application :)' if self._mailer.send_mail() \ else '** Your sending was failed :( please send it again!' self.log_msg_text.insert(END, ending) self.send_progressbar.stop() # Stop processing the progress.
class SimUI(object): def __init__(self, manager, fake_time, config_obj): """ initializes all default values and creates a board, waits for run() to be called to start the board manager - sim manager class instance """ self.manager = manager self.fake_time = fake_time self.config_obj = config_obj # Set up idle_add self.queue = queue.Queue() self.root = tk.Tk() self.root.wm_title("PyFRC Robot Simulator v%s" % __version__) # setup mode switch frame = tk.Frame(self.root) frame.pack(side=tk.TOP, anchor=tk.W) self._setup_widgets(frame) self.root.resizable(width=0, height=0) self.mode_start_tm = 0 self.text_id = None # connect to the controller self.manager.on_mode_change(lambda mode: self.idle_add(self.on_robot_mode_change, mode)) self.on_robot_mode_change(self.manager.get_mode()) # create pygame joystick if supported try: from .pygame_joysticks import UsbJoysticks except ImportError: logger.warn("pygame not detected, real joystick support not loaded") self.usb_joysticks = None else: self.usb_joysticks = UsbJoysticks(self) logger.info("pygame was detected, real joystick support loaded!") try: self.root.lift() self.root.attributes("-topmost", True) self.root.attributes("-topmost", False) except Exception: pass self.timer_fired() def _setup_widgets(self, frame): top = tk.Frame(frame) top.grid(column=0, row=0) bottom = tk.Frame(frame) bottom.grid(column=0, row=1) self.field = RobotField(frame, self.manager, self.config_obj) self.field.grid(column=1, row=0, rowspan=2) # status bar self.status = tk.Label(frame, bd=1, relief=tk.SUNKEN, anchor=tk.E) self.status.grid(column=0, row=2, columnspan=2, sticky=tk.W + tk.E) # analog slot = tk.LabelFrame(top, text="Analog") self.analog = [] for i in range(len(hal_data["analog_in"])): if hal_data["analog_in"][i]["initialized"] or hal_data["analog_out"][i]["initialized"]: label = tk.Label(slot, text=str(i)) label.grid(column=0, row=i + 1) vw = ValueWidget(slot, clickable=True, minval=-10.0, maxval=10.0) vw.grid(column=1, row=i + 1) self.set_tooltip(vw, "analog", i) else: vw = None self.analog.append(vw) slot.pack(side=tk.LEFT, fill=tk.Y, padx=5) # digital slot = tk.LabelFrame(top, text="Digital") label = tk.Label(slot, text="PWM") label.grid(column=0, columnspan=4, row=0) self.pwm = [] for i in range(len(hal_data["pwm"])): if hal_data["pwm"][i]["initialized"]: c = i // 10 label = tk.Label(slot, text=str(i)) label.grid(column=0 + 2 * c, row=1 + i % 10) vw = ValueWidget(slot) vw.grid(column=1 + 2 * c, row=1 + i % 10) self.set_tooltip(vw, "pwm", i) else: vw = None self.pwm.append(vw) label = tk.Label(slot, text="Digital I/O") label.grid(column=4, columnspan=6, row=0) self.dio = [] for i in range(len(hal_data["dio"])): if hal_data["dio"][i]["initialized"]: c = i // 9 label = tk.Label(slot, text=str(i)) label.grid(column=4 + c * 2, row=1 + i % 9) pi = PanelIndicator(slot, clickable=True) pi.grid(column=5 + c * 2, row=1 + i % 9) self.set_tooltip(pi, "dio", i) else: pi = None self.dio.append(pi) label = tk.Label(slot, text="Relay") label.grid(column=10, columnspan=2, row=0, padx=5) self.relays = [] for i in range(len(hal_data["relay"])): if hal_data["relay"][i]["initialized"]: label = tk.Label(slot, text=str(i)) label.grid(column=10, row=1 + i, sticky=tk.E) pi = PanelIndicator(slot) pi.grid(column=11, row=1 + i) self.set_tooltip(pi, "relay", i) else: pi = None self.relays.append(pi) slot.pack(side=tk.LEFT, fill=tk.Y, padx=5) csfm = tk.Frame(top) # solenoid slot = tk.LabelFrame(csfm, text="Solenoid") self.solenoids = [] for i in range(len(hal_data["solenoid"])): label = tk.Label(slot, text=str(i)) c = int(i / 2) * 2 r = i % 2 label.grid(column=0 + c, row=r) pi = PanelIndicator(slot) pi.grid(column=1 + c, row=r) self.set_tooltip(pi, "solenoid", i) self.solenoids.append(pi) slot.pack(side=tk.TOP, fill=tk.BOTH, padx=5) # CAN self.can_slot = tk.LabelFrame(csfm, text="CAN") self.can_slot.pack(side=tk.LEFT, fill=tk.BOTH, expand=1, padx=5) self.can_mode_map = { tsrxc.kMode_CurrentCloseLoop: "PercentVbus", tsrxc.kMode_DutyCycle: "PercentVbus", tsrxc.kMode_NoDrive: "Disabled", tsrxc.kMode_PositionCloseLoop: "Position", tsrxc.kMode_SlaveFollower: "Follower", tsrxc.kMode_VelocityCloseLoop: "Speed", tsrxc.kMode_VoltCompen: "Voltage", } self.can = {} # detect new devices for k in sorted(hal_data["CAN"].keys()): self._add_CAN(k, hal_data["CAN"][k]) csfm.pack(side=tk.LEFT, fill=tk.Y) # joysticks slot = tk.LabelFrame(bottom, text="Joysticks") self.joysticks = [] for i in range(4): axes = [] buttons = [] col = 1 + i * 3 row = 0 label = tk.Label(slot, text="Stick %s" % i) label.grid(column=col, columnspan=3, row=row) row += 1 # TODO: make this configurable for j, t in enumerate(["X", "Y", "Z", "T", "4", "5"]): label = tk.Label(slot, text=t) label.grid(column=col, row=row) vw = ValueWidget(slot, clickable=True, default=0.0) vw.grid(column=col + 1, row=row, columnspan=2) self.set_joy_tooltip(vw, i, "axes", t) axes.append(vw) row += 1 # POV: this needs improvement label = tk.Label(slot, text="POV") label.grid(column=col, row=row) pov = ValueWidget(slot, clickable=True, default=-1, minval=-1, maxval=360, step=45, round_to_step=True) pov.grid(column=col + 1, row=row, columnspan=2) row += 1 for j in range(1, 11): var = tk.IntVar() ck = tk.Checkbutton(slot, text=str(j), variable=var) ck.grid(column=col + 1 + (1 - j % 2), row=row + int((j - 1) / 2)) self.set_joy_tooltip(ck, i, "buttons", j) buttons.append((ck, var)) self.joysticks.append((axes, buttons, [pov])) slot.pack(side=tk.LEFT, fill=tk.Y, padx=5) ctrl_frame = tk.Frame(bottom) # timing control timing_control = tk.LabelFrame(ctrl_frame, text="Time") def _set_realtime(): if realtime_mode.get() == 0: step_button.pack_forget() step_entry.pack_forget() self.on_pause(False) else: step_button.pack(fill=tk.X) step_entry.pack() self.on_pause(True) realtime_mode = tk.IntVar() button = tk.Radiobutton(timing_control, text="Run", variable=realtime_mode, value=0, command=_set_realtime) button.pack(fill=tk.X) button = tk.Radiobutton(timing_control, text="Pause", variable=realtime_mode, value=1, command=_set_realtime) button.pack(fill=tk.X) step_button = tk.Button(timing_control, text="Step", command=self.on_step_time) self.step_entry = tk.StringVar() self.step_entry.set("0.025") step_entry = tk.Entry(timing_control, width=6, textvariable=self.step_entry) Tooltip.create(step_button, "Click this to increment time by the step value") Tooltip.create(step_entry, "Time to step (in seconds)") realtime_mode.set(0) timing_control.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # simulation control sim = tk.LabelFrame(ctrl_frame, text="Robot") self.state_buttons = [] self.mode = tk.IntVar() def _set_mode(): self.manager.set_mode(self.mode.get()) button = tk.Radiobutton( sim, text="Disabled", variable=self.mode, value=self.manager.MODE_DISABLED, command=_set_mode ) button.pack(fill=tk.X) self.state_buttons.append(button) button = tk.Radiobutton( sim, text="Autonomous", variable=self.mode, value=self.manager.MODE_AUTONOMOUS, command=_set_mode ) button.pack(fill=tk.X) self.state_buttons.append(button) button = tk.Radiobutton( sim, text="Teleoperated", variable=self.mode, value=self.manager.MODE_OPERATOR_CONTROL, command=_set_mode ) button.pack(fill=tk.X) self.state_buttons.append(button) button = tk.Radiobutton(sim, text="Test", variable=self.mode, value=self.manager.MODE_TEST, command=_set_mode) button.pack(fill=tk.X) self.state_buttons.append(button) self.robot_dead = tk.Label(sim, text="Robot died!", fg="red") sim.pack(side=tk.TOP, fill=tk.BOTH, expand=1) # # Set up a combo box that allows you to select an autonomous # mode in the simulator # try: from tkinter.ttk import Combobox except: pass else: auton = tk.LabelFrame(ctrl_frame, text="Autonomous") self.autobox = Combobox(auton, state="readonly") self.autobox.bind("<<ComboboxSelected>>", self.on_auton_selected) self.autobox["width"] = 12 self.autobox.pack(fill=tk.X) Tooltip.create(self.autobox, "Use robotpy_ext.autonomous.AutonomousModeSelector to use this selection box") from networktables.util import ChooserControl self.auton_ctrl = ChooserControl( "Autonomous Mode", lambda v: self.idle_add(self.on_auton_choices, v), lambda v: self.idle_add(self.on_auton_selection, v), ) auton.pack(side=tk.TOP) ctrl_frame.pack(side=tk.LEFT, fill=tk.Y) def _add_CAN(self, canId, device): row = len(self.can) * 2 lbl = tk.Label(self.can_slot, text=str(canId)) lbl.grid(column=0, row=row) motor = ValueWidget(self.can_slot, default=0.0) motor.grid(column=1, row=row) self.set_tooltip(motor, "CAN", canId) fl = CheckButtonWrapper(self.can_slot, text="F") fl.grid(column=2, row=row) rl = CheckButtonWrapper(self.can_slot, text="R") rl.grid(column=3, row=row) Tooltip.create(fl, "Forward limit switch") Tooltip.create(rl, "Reverse limit switch") mode_lbl_txt = tk.StringVar(value=self.can_mode_map[device["mode_select"]]) mode_label = tk.Label(self.can_slot, textvariable=mode_lbl_txt) mode_label.grid(column=4, row=row) labels = tk.Frame(self.can_slot) labels.grid(column=0, row=row + 1, columnspan=6) enc_value = tk.StringVar(value="E: 0") enc_label = tk.Label(labels, textvariable=enc_value) enc_label.pack(side=tk.LEFT) analog_value = tk.StringVar(value="A: 0") analog_label = tk.Label(labels, textvariable=analog_value) analog_label.pack(side=tk.LEFT) pwm_value = tk.StringVar(value="P: 0") pwm_label = tk.Label(labels, textvariable=pwm_value) pwm_label.pack(side=tk.LEFT) Tooltip.create(enc_label, "Encoder Input") Tooltip.create(analog_label, "Analog Input") Tooltip.create(pwm_label, "PWM Input") self.can[canId] = (motor, fl, rl, mode_lbl_txt, enc_value, analog_value, pwm_value) def idle_add(self, callable, *args): """Call this with a function as the argument, and that function will be called on the GUI thread via an event This function returns immediately """ self.queue.put((callable, args)) def __process_idle_events(self): """This should never be called directly, it is called via an event, and should always be on the GUI thread""" while True: try: callable, args = self.queue.get(block=False) except queue.Empty: break callable(*args) def run(self): # and launch the thread self.root.mainloop() # This call BLOCKS def timer_fired(self): """Polling loop for events from other threads""" self.__process_idle_events() # grab the simulation lock, gather all of the # wpilib objects, and display them on the screen self.update_widgets() # call next timer_fired (or we'll never call timer_fired again!) delay = 100 # milliseconds self.root.after(delay, self.timer_fired) # pause, then call timer_fired again def update_widgets(self): # TODO: support multiple slots? # joystick stuff if self.usb_joysticks is not None: self.usb_joysticks.update() # analog module for i, (ain, aout) in enumerate(zip(hal_data["analog_in"], hal_data["analog_out"])): aio = self.analog[i] if aio is not None: if ain["initialized"]: aio.set_disabled(False) ain["voltage"] = aio.get_value() elif aout["initialized"]: aio.set_value(aout["voltage"]) # digital module for i, ch in enumerate(hal_data["dio"]): dio = self.dio[i] if dio is not None: if not ch["initialized"]: dio.set_disabled() else: # determine which one changed, and set the appropriate one ret = dio.sync_value(ch["value"]) if ret is not None: ch["value"] = ret for i, ch in enumerate(hal_data["pwm"]): pwm = self.pwm[i] if pwm is not None: pwm.set_value(ch["value"]) for i, ch in enumerate(hal_data["relay"]): relay = self.relays[i] if relay is not None: if ch["fwd"]: relay.set_on() elif ch["rev"]: relay.set_back() else: relay.set_off() # solenoid for i, ch in enumerate(hal_data["solenoid"]): sol = self.solenoids[i] if not ch["initialized"]: sol.set_disabled() else: sol.set_value(ch["value"]) # CAN for k, (motor, fl, rl, mode_lbl_txt, enc_txt, analog_txt, pwm_txt) in self.can.items(): can = hal_data["CAN"][k] mode = can["mode_select"] mode_lbl_txt.set(self.can_mode_map[mode]) # change how output works based on control mode if mode == tsrxc.kMode_DutyCycle: # based on the fact that the vbus has 1023 steps motor.set_value(can["value"] / 1023) elif mode == tsrxc.kMode_VoltCompen: # assume voltage is 12 divide by muliplier in cantalon code (256) motor.set_value(can["value"] / 12 / 256) elif mode == tsrxc.kMode_SlaveFollower: # follow the value of the motor value is equal too motor.set_value(self.can[can["value"]][0].get_value()) # # currently other control modes are not correctly implemented # else: motor.set_value(can["value"]) enc_txt.set("E: %s" % can["enc_position"]) analog_txt.set("A: %s" % can["analog_in_position"]) pwm_txt.set("P: %s" % can["pulse_width_position"]) ret = fl.sync_value(can["limit_switch_closed_for"]) if ret is not None: can["limit_switch_closed_for"] = ret ret = rl.sync_value(can["limit_switch_closed_rev"]) if ret is not None: can["limit_switch_closed_rev"] = ret # joystick/driver station # sticks = _core.DriverStation.GetInstance().sticks # stick_buttons = _core.DriverStation.GetInstance().stick_buttons for i, (axes, buttons, povs) in enumerate(self.joysticks): joy = hal_data["joysticks"][i] jaxes = joy["axes"] for j, ax in enumerate(axes): jaxes[j] = ax.get_value() jbuttons = joy["buttons"] for j, (ck, var) in enumerate(buttons): jbuttons[j + 1] = True if var.get() else False jpovs = joy["povs"] for j, pov in enumerate(povs): jpovs[j] = int(pov.get_value()) self.field.update_widgets() tm = self.fake_time.get() mode_tm = tm - self.mode_start_tm self.status.config(text="Time: %.03f mode, %.03f total" % (mode_tm, tm)) def set_tooltip(self, widget, cat, idx): tooltip = self.config_obj["pyfrc"][cat].get(str(idx)) if tooltip is not None: Tooltip.create(widget, tooltip) def set_joy_tooltip(self, widget, idx, typ, idx2): tooltip = self.config_obj["pyfrc"]["joysticks"][str(idx)][typ].get(str(idx2)) if tooltip is not None: Tooltip.create(widget, tooltip) def on_auton_choices(self, choices): self.autobox["values"] = choices[:] def on_auton_selection(self, selection): self.autobox.set(selection) def on_auton_selected(self, e): self.auton_ctrl.setSelected(self.autobox.get()) def on_robot_mode_change(self, mode): self.mode.set(mode) self.mode_start_tm = self.fake_time.get() # this is not strictly true... a robot can actually receive joystick # commands from the driver station in disabled mode. However, most # people aren't going to use that functionality... controls_disabled = False if mode == self.manager.MODE_OPERATOR_CONTROL else True state = tk.DISABLED if controls_disabled else tk.NORMAL for axes, buttons, povs in self.joysticks: for axis in axes: axis.set_disabled(disabled=controls_disabled) for ck, var in buttons: ck.config(state=state) for pov in povs: pov.set_disabled(disabled=controls_disabled) if not self.manager.is_alive(): for button in self.state_buttons: button.config(state=tk.DISABLED) self.robot_dead.pack() # # Time related callbacks # def on_pause(self, pause): if pause: self.fake_time.pause() else: self.fake_time.resume() def on_step_time(self): val = self.step_entry.get() try: tm = float(self.step_entry.get()) except ValueError: tk.messagebox.showerror("Invalid step time", "'%s' is not a valid number" % val) return if tm > 0: self.fake_time.resume(tm)
class Panel: def __init__(self, frame, treater, settings): self.is_active = False self.oposite = lambda: None self.treater = treater self.placer = Placer() self.settings = settings self.sort_by = "name" self.sort_rev = False self.pwd = StringVar() self._places = None self.has_pardir = False self.pwd.set(self.treater.get_cur_dir()) self.body(frame) ddir = join(dirname(__file__), "data") self.imgs = {} for t, f in (("directory", "folder.gif"), ("regular", "file.gif"), ("link", "link.gif"), ("fifo", "fifo.gif"), ("socket", "socket.gif"), ("block", "block.gif"), ("character", "character.gif"), ("Parent_dir", "pardir.gif")): self.imgs[t] = PhotoImage(master=frame, file=join(ddir, f)) self.str_ids = {} self.id_range = [] self.selected_ids = set() self.br_hist = [] self.fresh() self.renheadings() def body(self, frame): "Place panel widgets" frame.grid_columnconfigure(0, weight=1) frame.grid_rowconfigure(1, weight=1) top = Frame(frame) top.grid(column=0, row=0, sticky="ew") self.mounts = Combobox(top, takefocus=False, state="readonly") self.mounts["postcommand"] = self.get_places self.mounts.bind("<<ComboboxSelected>>", self.goto_place) self.mounts.pack(anchor="nw") pthl = Label(top, textvariable=self.pwd) pthl.pack(expand=True, anchor="w") self.tree = tree = Treeview(frame, columns=("size", "modified", "mode")) tree.grid(column=0, row=1, sticky="nwes") vsb = Scrollbar(frame, command=self.tree.yview, orient="vertical") vsb.grid(column=1, row=1, sticky="ns") tree["yscrollcommand"] = lambda f, l: autoscroll(vsb, f, l) hsb = Scrollbar(frame, command=self.tree.xview, orient="horizontal") hsb.grid(column=0, row=2, sticky="ew") tree["xscrollcommand"] = lambda f, l: autoscroll(hsb, f, l) tree.column("size", width=70, anchor="center") tree.column("modified", width=70, anchor="center") tree.column("mode", width=70, anchor="center") tree.heading("#0", command=lambda: self.on_heading("name")) tree.heading("size", command=lambda: self.on_heading("size")) tree.heading("modified", command=lambda: self.on_heading("date")) tree.tag_configure("selected", foreground="red") for i in (("<Return>", self.enter_file), ("<Double-Button-1>", self.enter_file), ("<Right>", self.enter_file), ("<Left>", self.go_back), ("<Tab>", self.switch), ("<Home>", self.go_top), ("<Button-1>", self.activate), ("<Insert>", self.turn_selection), ("<Control-r>", self.refresh)): tree.bind(*i) def renheadings(self): "Rename headings due to new sorting conditions" arrow_up = " \u2191" arrow_down = " \u2193" for col, name, sb in ( ("#0", _("Name"), "name"), ("size", _("Size"), "size"), ("modified", _("Date"), "date"), ("mode", _("Attr."), None)): if self.sort_by == sb: name += arrow_down if self.sort_rev else arrow_up self.tree.heading(col, text=name) def on_heading(self, name): "An heading was clicked" if self.sort_by == name: self.sort_rev = not self.sort_rev else: self.sort_by = name self.sort_rev = False self.sort_tree() self.renheadings() def fresh(self): "Update tree items. Returns True on error." files = self.treater.list_visible(self.settings) if files is None: return True self.clear() self.has_pardir = self.treater.has_pardir() if self.has_pardir: self.tree.insert("", "end", "Parent_dir", text=pardir, image=self.imgs["Parent_dir"]) ltp = localtime(time()) for name, ft, sz, mt, mode in files: mt = localtime(mt) if ltp.tm_year > mt.tm_year: smt = strftime("%b %Y", mt) elif ltp.tm_yday > mt.tm_yday: smt = strftime("%d %b", mt) else: smt = strftime("%H:%M") if sz < 1024: ssz = sz elif sz < 1048576: ssz = "%dK" % (sz // 1024) else: ssz = "%dM" % (sz // 1048576) mod_arr = [] # NOTE: Mentions of letters are: X - execute, W - write, R - read, # H - hidden, S - symbolic link for i, l in enumerate(_("XWRHS")): mod_arr.append(l if mode & (1 << i) else "-") mod_arr.reverse() mds = "".join(mod_arr) iid = self.tree.insert("", "end", text=name, values=(ssz, smt, mds), image=self.imgs[ft]) self.str_ids[iid] = (name, ft, sz, mt, mode) self.id_range.append(iid) self.sort_tree() def clear(self): for i in reversed(self.id_range): self.tree.delete(i) if self.has_pardir: self.tree.delete("Parent_dir") self.str_ids.clear() self.selected_ids.clear() del self.id_range[:] def sort_tree(self): si = {"name": 0, "size": 2, "date": 3}[self.sort_by] sd = self.str_ids key = lambda x: sd[x][si] self.id_range.sort(key=key, reverse=self.sort_rev) key = lambda x: 2 if sd[x][1] != "directory" else 1 self.id_range.sort(key=key) mv = self.tree.move start = 1 if self.has_pardir else 0 for pos, iid in enumerate(self.id_range, start): mv(iid, "", pos) def enter_file(self, evt=None): iid = self.tree.focus() if iid == "Parent_dir": self._change_dir(pardir) return if self.str_ids[iid][FT_TYPE] == "directory": mode = self.str_ids[iid][FT_MODE] mask = M_READABLE | M_EXECUTABLE if mode & mask != mask: return self._change_dir(self.str_ids[iid][FT_NAME]) def turn_selection(self, evt=None): iid = self.tree.focus() if iid != "Parent_dir": selected = self.selected_ids if iid in selected: self.tree.item(iid, tags=()) selected.discard(iid) else: selected.add(iid) self.tree.item(iid, tags=("selected")) if self.settings.get("insert_moves_down", True) and self.id_range: if iid == "Parent_dir": move_to = 0 else: move_to = self.id_range.index(iid) + 1 if move_to >= len(self.id_range): move_to = -1 tree = self.tree tree.focus(item=self.id_range[move_to]) tree.selection_remove(*(tree.selection())) tree.selection_add(tree.focus()) def go_back(self, evt=None): try: prdir = self.br_hist.pop(-1) except IndexError: return self._change_dir(prdir, False) def refresh(self, evt=None): iid = self.tree.focus() fid = self.str_ids fn = fid[iid][0] pos = self.id_range.index(iid) self.fresh() iid = "" for i in fid: if fid[i][0] == fn: iid = i break if iid == "": if pos < len(self.id_range): iid = self.id_range[pos] else: iid = self.id_range[-1] self.tree.focus(item=iid) self.activate() def activate(self, evt=None): if self.tree.focus() == "": self.tree.focus(item=self.id_range[0]) self.tree.selection_add(self.tree.focus()) oposite = self.oposite() if oposite is not None: opt = oposite.tree sel = opt.selection() if sel: opt.selection_remove(*sel) oposite.is_active = False self.tree.focus_set() self.is_active = True def switch(self, evt=None): if self.oposite() is None: return self.oposite().activate() def go_top(self, evt=None): self.tree.focus(item=self.id_range[0]) sel = self.tree.selection() if sel: self.tree.selection_remove(*sel) self.tree.selection_add(self.id_range[0]) def get_places(self): try: places = self.placer.placing_items() except AttributeError: self._places = None self.mounts["values"] = None return self.mounts["values"] = [i[0] for i in places] # self.mounts["values"] can be changet after assignment. Therefore # it is more safe to replace names of mount points by changed ones. self._places = dict((j, i[1]) for i, j in zip(places, self.mounts["values"])) def goto_place(self, evt=None): if self._places is None: return place = self._places[self.mounts.get()] self._change_dir(place) def _change_dir(self, path, remember=True): previous = self.treater.get_cur_dir() if self.treater.cd(path): return if self.fresh(): self.treater.cd(previous) elif remember: self.br_hist.append(previous) self.pwd.set(self.treater.get_cur_dir()) self.activate() def get_selected_filenames(self): result = [] if not self.selected_ids: iid = self.tree.focus() if iid != "Parent_dir": result.append(self.str_ids[iid][FT_NAME]) for iid in self.selected_ids: result.append(self.str_ids[iid][FT_NAME]) return result