def __init__(self, boss, repertoire): contenu = listdir('Objets/' + repertoire) self.listObjets = {} listStrObjets = [] for nom in contenu: self.listObjets[nom[:-4]] = Objet(repertoire, nom) #Le [:-4] permet de supprimer le ".txt" listStrObjets.append(nom[:-4]) Combobox.__init__(self, boss, values = listStrObjets, state='readonly')
def createWidgets(self): frame1 = Frame(self) season_frame = Frame(frame1) self.seasonlabel = Label(season_frame, text="Season") season_list = ('2013-2014', '2012-2013', '2011-2012', '2010-2011', '2009-2010', '2008-2009', '2007-2008', '2006-2007', '2005-2006', '2003-2004', '2002-2003', '2001-2002', '2000-2001', '1999-2000', '1998-1999', '1997-1998') self.season = Combobox(season_frame, values=season_list, state='readonly') self.season.current(0) self.seasonlabel.pack() self.season.pack() season_frame.pack(side=LEFT, padx=5, pady=5) position_frame = Frame(frame1) self.positionlabel = Label(position_frame, text="Position") position_list = ('All Skaters', 'Goalies', 'Forwards', 'Defenseman', 'Center', 'Left Wing', 'Right Wing') self.position = Combobox(position_frame, values=position_list, state='readonly') self.position.current(0) self.positionlabel.pack() self.position.pack() position_frame.pack(side=LEFT, padx=5, pady=5) frame1.pack(side=TOP) frame2 = Frame(self) gameType_frame = Frame(frame2) self.gameTypelabel = Label(gameType_frame, text="Game Type") gameType_list = ('Regular Season', 'Playoffs') self.gameType = Combobox(gameType_frame, values=gameType_list, state='readonly') self.gameType.current(0) self.gameTypelabel.pack() self.gameType.pack() gameType_frame.pack(side=LEFT, padx=5, pady=5) grouping_frame = Frame(frame2) self.groupinglabel = Label(grouping_frame, text="Grouping") grouping_list = ('By League', 'By Team') self.grouping = Combobox(grouping_frame, values=grouping_list, state='readonly') self.grouping.current(0) self.groupinglabel.pack() self.grouping.pack() grouping_frame.pack(side=LEFT, padx=5, pady=5) frame2.pack(side=TOP) frame3 = Frame(self) self.progress = Label(frame3, text="Choose Options and Press Start", relief=SUNKEN, width=30) self.progress.pack() frame3.pack(side=TOP, padx=5, pady=5) frame4 = Frame(self) self.start = Button(frame4, text="Start", command=self.start) self.QUIT = Button(frame4, text="Quit", command=self.quit) self.start.pack(side=LEFT) self.QUIT.pack(side=LEFT) frame4.pack(side=TOP)
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 __make_widgets(self): widgets = {} for index, editor_field in enumerate(self.editor_fields): label = Label(self, width=50, padding=5, text=editor_field.title()) combo = Combobox(self, width=100) widgets[editor_field] = {} widgets[editor_field]['label'] = label widgets[editor_field]['widget'] = combo label.grid(row=index, column=0) combo.grid(row=index, column=1) index += 1 label = Label(self, width=50, padding=5, text="Pictures") button = Button(self, text="...", command=self.__load_pictures) label.grid(row=index, column=0) button.grid(row=index, column=1) return widgets
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 initialize(self): """ Initialize the combobox contening all available type of filter and the entry text to choose the value of Q factor """ self.typeCombo = Combobox(self.root, textvariable=self.typeFilter, values=F.values(), width="5") self.typeCombo.grid(row=1,column=self.id, padx=10) self.qText = Entry(self.root, textvariable=self.qFactor, width="5") self.qText.grid(row=2,column=self.id, padx=10, pady=5)
class SliderParameter(Frame): """ A frame contening additionnals parameters for filter (represented by a SliderFrequency) to set the type and the Q factor parameters: root: Canvas the canvas to place the SliderParameter type: String A string representing the type of a filter Q: String the Q factor of a filter id: int ID of th SliderParameter """ def __init__(self,root, type, Q, id): Frame.__init__(self,root) self.root = root self.typeFilter = StringVar() self.typeFilter.set(type) self.qFactor = StringVar() self.qFactor.set(Q) self.id = id self.initialize() def initialize(self): """ Initialize the combobox contening all available type of filter and the entry text to choose the value of Q factor """ self.typeCombo = Combobox(self.root, textvariable=self.typeFilter, values=F.values(), width="5") self.typeCombo.grid(row=1,column=self.id, padx=10) self.qText = Entry(self.root, textvariable=self.qFactor, width="5") self.qText.grid(row=2,column=self.id, padx=10, pady=5) def getQ(self): """ return the value of the Q factor """ return self.qFactor.get() def getType(self): """ Return the type of the filter """ return self.typeCombo.get()
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 __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'
def create_widgets(self, names): ''' Creates appropriate widgets. Args: names (list of str): list of available sheet names. ''' sheet_name_lbl = Label(self, text='Choose sheet name where data is stored:') sheet_name_lbl.grid(sticky=N+W, padx=5, pady=5) sheet_names_box = Combobox(self, state="readonly", width=20, textvariable=self.sheet_name_str, values=names) sheet_names_box.current(0) sheet_names_box.grid(row=1, column=0, columnspan=2, sticky=N+W, padx=5, pady=5) ok_btn = Button(self, text='OK', command=self.ok) ok_btn.grid(row=2, column=0, sticky=N+E, padx=5, pady=5) ok_btn.bind('<Return>', self.ok) ok_btn.focus() cancel_btn = Button(self, text='Cancel', command=self.cancel) cancel_btn.grid(row=2, column=1, sticky=N+E, padx=5, pady=5) cancel_btn.bind('<Return>', self.cancel)
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()
class AddDrawingRuleDialog(d.Dialog): def body(self, master, existingRule=None): self.cmd = String() Label(master, text= "Symbol:").grid(row=0) Label(master, text= "Rule:" ).grid(row=1) self.e1 = Input(master, width=20) self.e2 = Dropdown(master, textvariable= self.cmd, width= 7, state= 'readonly') self.e3 = Input(master, width=10) self.e2['values'] = ['draw', 'turn', 'skip', 'back', 'color', 'thick'] self.e1.grid(row=0, column=1, columnspan=2) self.e2.grid(row=1, column=1) self.e3.grid(row=1, column=2) if existingRule: self.e1.insert(0, existingRule[1]) self.e2.set(existingRule[2]) #self.e2.insert(0, existingRule[2]) if len(existingRule) > 3: self.e3.insert(0, existingRule[3]) return self.e1 def validate(self): symb = self.e1.get() rule = self.e2.get() param = self.e3.get() if symb and rule: symb = symb.strip() rule = rule.strip() if param: return (symb, rule, param) else: return (symb, rule) def apply(self): r = self.validate() if r: self.result = r
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)
def adb_Main(self): vcheck.auto_version_check() adbmain_frame = LabelFrame(self.parent, text="ADB Main function:", padx=3, pady=3) adbmain_frame.grid(column=0, row=2) check_device = Button(adbmain_frame, text="Check Device", command=lambda: adb("devices"),width=buttonw) check_device.pack(padx=2, pady=2) reboot = Button(adbmain_frame, text="Reboot", command=lambda: self.comboget(),width=buttonw) reboot.pack(padx=2, pady=2) global v v = StringVar() # a string variable to hold user selection options = ["Normal", "Recovery", "Bootloade"] # available combobox options combo = Combobox(adbmain_frame, textvariable=v, values=options, width=buttonw) #combo.bind('<<ComboboxSelected>>', self.comboget) # binding of user selection with a custom callback combo.current(0) # set as default "option 2" combo.pack() reboot_recovery = Button(adbmain_frame, text="Start Service", command=lambda: adb("start-server", after_print_text="Service startet"), width=buttonw) reboot_recovery.pack(padx=2, pady=2) reboot_bootloader = Button(adbmain_frame, text="Stop Service", command=lambda: adb("kill-server", after_print_text="Service Stopt"), width=buttonw) reboot_bootloader.pack(padx=2, pady=2)
def set_version_combobox(box: ttk.Combobox, item: 'UI.Item') -> list: """Set values on the variant combobox. This is in a function so itemconfig can reuse it. It returns a list of IDs in the same order as the names. """ ver_lookup, version_names = item.get_version_names() if len(version_names) <= 1: # There aren't any alternates to choose from, disable the box box.state(['disabled']) box['values'] = [_('No Alternate Versions!')] box.current(0) else: box.state(['!disabled']) box['values'] = version_names box.current(ver_lookup.index(item.selected_ver)) return ver_lookup
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 body(self, master, existingRule=None): self.cmd = String() Label(master, text= "Symbol:").grid(row=0) Label(master, text= "Rule:" ).grid(row=1) self.e1 = Input(master, width=20) self.e2 = Dropdown(master, textvariable= self.cmd, width= 7, state= 'readonly') self.e3 = Input(master, width=10) self.e2['values'] = ['draw', 'turn', 'skip', 'back', 'color', 'thick'] self.e1.grid(row=0, column=1, columnspan=2) self.e2.grid(row=1, column=1) self.e3.grid(row=1, column=2) if existingRule: self.e1.insert(0, existingRule[1]) self.e2.set(existingRule[2]) #self.e2.insert(0, existingRule[2]) if len(existingRule) > 3: self.e3.insert(0, existingRule[3]) return self.e1
def createWidgets(self): self.function_label = Label(self) self.function_label["text"] = "Задати функцію" self.function_label.grid(row=0, column=0) self.function_combo = Combobox(self) self.function_combo["values"] = ["x*x", "cos(x)"] self.function_combo.set("x*x") self.function_combo.grid(row=0, column=1) self.a_label = Label(self) self.a_label["text"] = "Задати ліву межу" self.a_label.grid(row=1, column=0) self.a = Entry(self) self.a.insert(END, '0') self.a.grid(row=1, column=1) self.b_label = Label(self) self.b_label["text"] = "Задати праву межу" self.b_label.grid(row=2, column=0) self.b = Entry(self) self.b.insert(END, '50') self.b.grid(row=2, column=1) self.learning_button = Button(self) self.learning_button["text"] = "Навчити" self.learning_button["command"] = self.make_points self.learning_button.grid(row=3, column=0) self.check_button = Button(self) self.check_button["text"] = "Розпізнати" self.check_button["command"] = self.check self.check_button.grid(row=3, column=1) self.learn_canvas = Canvas(self) self.learn_canvas.grid(row=4, column=0) self.check_canvas = Canvas(self) self.check_canvas.grid(row=4, column=1)
def _makesetting(setting_window, conf): setting_label = Label(setting_window, text=_('Setting'), font=('courier', 20, 'bold')) setting_label.pack(side=TOP) style_container = Frame(setting_window) style_container.pack(side=TOP) style_label = Label(style_container, text=_('Display wallpaper in style: '), font=('courier', 15, 'bold')) style_label.pack(side=LEFT) style_combobox = Combobox(style_container) available_style = {'3': 'zoom', '2': 'scaled', '1': 'stretched', '0': 'centered', '4': 'wallpaper'} style_combobox['value'] = (_('centered'), _('stretched'), _('scaled'), _('zoom'), _('wallpaper')) style_combobox.state(['readonly']) style_combobox.current(int(conf['style'])) style_combobox.pack(side=LEFT) random_container = Frame(setting_window) random_container.pack(side=TOP) random_label = Label(random_container, text=_('Choose wallpaper randomly? '), font=('courier', 15, 'bold')) random_label.pack(side=LEFT) random_checkbutton = Checkbutton(random_container) random_checkbutton.pack(side=LEFT) if conf['random'] == "1": random_checkbutton.select() interval_container = Frame(setting_window) interval_container.pack(side=TOP) interval_label = Label(interval_container, text=_('Change wallpaper every '), font=('courier', 15, 'bold')) interval_label.pack(side=LEFT) interval_text = Text(interval_container, height=1, width=4) interval_text.insert(END, conf['interval']) interval_text.pack(side=LEFT) minute_label = Label(interval_container, text=_(' minutes.'), font=('courier', 15, 'bold')) minute_label.pack(side=LEFT)
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 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 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 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() # çàïóñêàåì ïðîãðàììó
command=license_agreement) fileMenu.add_command(label='Справка', command=faq) fileMenu.add_separator() fileMenu.add_command(label='Выход', command=_quit) my_font = Font(family='Halvetica', size=10, weight='bold') labelEUR = Label(root, text=' Валютная пара', font=my_font) labelEUR.grid(row=1, column=1) vEUR = [ 'EUR/USD', 'USD/JPY', 'GBP/USD', 'USD/CHF', 'EUR/CHF', 'AUD/USD', 'USD/CAD', 'NZD/USD', 'EUR/GBP', 'EUR/JPY', 'GBP/JPY', 'AUD/JPY', 'GBP/AUD', 'USD/CNH', 'XAU/USD', 'XAG/USD' ] comboEUR = Combobox(root, values=vEUR, width=10) comboEUR.set('EUR/USD') comboEUR.grid(row=2, column=1) labelStart = Label(root, text=' \nТочка старта', font=my_font) labelStart.grid(row=3, column=1) labelYStart = Label(root, text='Год') labelYStart.grid(row=4, column=1) labelYStart = Label(root, text='День') labelYStart.grid(row=4, column=2) labelYStart = Label(root, text='Месяц') labelYStart.grid(row=4, column=3)
class NSE: def stop_all(self) -> None: self.stop = True def main_recursive(self) -> None: if (self.first_run): #print("FIRST time") self.refresh_data() self.first_run = False self.curr_time = time.time() time_passed = int(self.curr_time - self.prev_time) if (time_passed > self.interval): self.refresh_data() else: self.sh_window.after((10 * 1000), self.main_recursive) return if (not self.stop): self.sh_window.after((10 * 1000), self.main_recursive) return def __init__(self, window: Tk) -> None: self.first_run_live_price: List[float] = [] self.plot_only: bool = True self.graph_index, = plt.plot([], [], 'o-', label='BANKNIFTY') self.first_run: bool = True self.dict_dfs_INDEX: dict[pd.DataFrame] = {} self.dict_dfs_STOCK: dict[pd.DataFrame] = {} self.nb_names: List[String] = [ 'PCR OTM', 'DIFF OTM', 'PCR FAR OTM', 'CE-OTM', 'PE-OTM', 'CE-FAR_OTM', 'PE-FAR_OTM', 'LTP', 'PCR' ] for i in self.nb_names: self.dict_dfs_INDEX[i] = pd.DataFrame() self.dict_dfs_STOCK[i] = pd.DataFrame() self.stop: bool = False self.curr_time = "" self.interval = 5 #seconds self.red: str = "#e53935" self.green: str = "#00e676" self.df_INDEX: pd.DataFrame = pd.DataFrame() self.df_STOCK: pd.DataFrame = pd.DataFrame() self.popular_stocks: List[str] = ['AUROPHARMA','TATASTEEL','ASHOKLEY','AXISBANK', 'BAJAJ-AUTO', 'BAJAJFINSV',\ 'BRITANNIA','DRREDDY','GLENMARK','HDFC', 'HDFCBANK',\ 'ICICIBANK','INDUSINDBK','INFY','MANAPPURAM','MARUTI',\ 'MUTHOOTFIN','RELIANCE','SBILIFE', 'SBIN','TATAMOTORS',\ 'TCS','WIPRO','ZEEL'] self.hdr: Dict[str, str] = { 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \ (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36', 'accept-language': 'en-US,en;q=0.9' } self.stock_symbs: List[str] = [ 'AARTIIND', 'ACC', 'ADANIENT', 'ADANIPORTS', 'AMARAJABAT', 'AMBUJACEM', 'APOLLOHOSP', 'APOLLOTYRE', 'ASHOKLEY', 'ASIANPAINT', 'AUROPHARMA', 'AXISBANK', 'BAJAJ-AUTO', 'BAJAJFINSV', 'BAJFINANCE', 'BALKRISIND', 'BANDHANBNK', 'BANKBARODA', 'BATAINDIA', 'BEL', 'BERGEPAINT', 'BHARATFORG', 'BHARTIARTL', 'BHEL', 'BIOCON', 'BOSCHLTD', 'BPCL', 'BRITANNIA', 'CADILAHC', 'CANBK', 'CHOLAFIN', 'CIPLA', 'COALINDIA', 'COFORGE', 'COLPAL', 'CONCOR', 'CUMMINSIND', 'DABUR', 'DIVISLAB', 'DLF', 'DRREDDY', 'EICHERMOT', 'ESCORTS', 'EXIDEIND', 'FEDERALBNK', 'GAIL', 'GLENMARK', 'GMRINFRA', 'GODREJCP', 'GODREJPROP', 'GRASIM', 'HAVELLS', 'HCLTECH', 'HDFC', 'HDFCAMC', 'HDFCBANK', 'HDFCLIFE', 'HEROMOTOCO', 'HINDALCO', 'HINDPETRO', 'HINDUNILVR', 'IBULHSGFIN', 'ICICIBANK', 'ICICIGI', 'ICICIPRULI', 'IDEA', 'IDFCFIRSTB', 'IGL', 'INDIGO', 'INDUSINDBK', 'INDUSTOWER', 'INFY', 'IOC', 'ITC', 'JINDALSTEL', 'JSWSTEEL', 'JUBLFOOD', 'KOTAKBANK', 'LALPATHLAB', 'LICHSGFIN', 'LT', 'LUPIN', 'MANAPPURAM', 'MARICO', 'MARUTI', 'MCDOWELL-N', 'MFSL', 'MGL', 'MINDTREE', 'MOTHERSUMI', 'MRF', 'MUTHOOTFIN', 'NATIONALUM', 'NAUKRI', 'NESTLEIND', 'NMDC', 'NTPC', 'ONGC', 'PAGEIND', 'PEL', 'PETRONET', 'PFC', 'PIDILITIND', 'PNB', 'POWERGRID', 'PVR', 'RAMCOCEM', 'RBLBANK', 'RECLTD', 'RELIANCE', 'SAIL', 'SBILIFE', 'SBIN', 'SHREECEM', 'SIEMENS', 'SRF', 'SRTRANSFIN', 'SUNPHARMA', 'SUNTV', 'TATACHEM', 'TATACONSUM', 'TATAMOTORS', 'TATAPOWER', 'TATASTEEL', 'TCS', 'TECHM', 'TITAN', 'TORNTPHARM', 'TORNTPOWER', 'TVSMOTOR', 'UBL', 'ULTRACEMCO', 'UPL', 'VEDL', 'VOLTAS', 'WIPRO' ] #self.stock_symbs: List[str] = ['INFY','UPL', 'VEDL', 'VOLTAS', 'WIPRO', 'ZEEL'] #self.stock_symbs: List[str] = ['INFY','UPL'] self.stock_symbs = self.popular_stocks self.indices: List[str] = ['NIFTY', 'BANKNIFTY'] #self.indices: List[str] = ['BANKNIFTY'] self.SYMBS: List[String] = self.indices self.stock_symb: String = "" self.session: requests.Session = requests.Session() self.make_intial_nse_connection() self.expiry_date: String = "" self.setup_main_window(window) self.resposne: requests.Response = requests.Response() def make_intial_nse_connection(self) -> None: self.session.close() self.session = requests.Session() url_oc = 'https://www.nseindia.com/option-chain' try: self.response = self.session.get(url_oc, headers=self.hdr, timeout=5) except: self.sh_window.after((10 * 1000), self.make_intial_nse_connection) return self.cookies = self.response.cookies if (self.stock_symb != ""): try: self.response = self.session.get(url, headers=self.hdr, timeout=5, cookies=self.cookies) except: #self.make_intial_nse_connection() self.sh_window.after((10 * 1000), self.make_intial_nse_connection) return def refresh_data(self) -> None: self.col_time = datetime.now().strftime("%H:%M:%S") self.prev_time = time.time() if (self.sh_frame): self.sh_frame.destroy() self.sh_frame: Frame = Frame(self.sh_window, height=2) self.sh_frame.rowconfigure(0, weight=1) self.sh_frame.columnconfigure(0, weight=1) self.sh_frame.pack(anchor=N, fill="x", expand=False) if (self.stock_frame): self.stock_frame.destroy() self.stock_frame: Frame = Frame(self.sh_window) self.stock_frame.rowconfigure(3, weight=1) self.stock_frame.columnconfigure(0, weight=1) self.stock_frame.pack(anchor=N, fill="both", expand=True) if (self.check_index_var.get()): self.SYMBS = self.indices self.index_call = True if (self.plot_only): self.get_data_plot_only() else: self.set_sheet(self.sh_frame) self.sheet_formatting() self.draw_plots() if (self.check_stocks_var.get()): self.SYMBS = self.stock_symbs #selected_symbs = [] #for i in range(len(self.stock_check_var)): # if(self.stock_check_var[i].get()): # selected_symbs.append(self.stock_check[i].text) ##self.SYMBS.extend(selected_symbs) self.index_call = False self.set_sheet(self.stock_frame) self.sheet_formatting() def get_data_plot_only(self): self.NB_DF: List[pd.Dataframe] = [] df, dict_dfs = self.append_df_with_OC() for key in dict_dfs.keys(): self.NB_DF.append(pd.concat([df, dict_dfs[key]], axis=1)) def set_sheet(self, my_frame: Frame) -> None: self.NB: Notebook = Notebook(my_frame) self.NB.pack(anchor=N, fill="both", expand=True) self.NBF: List[Frame] = [] self.NBS: List[tksheet.Sheet] = [] self.NB_DF: List[pd.Dataframe] = [] df, dict_dfs = self.append_df_with_OC() for key in dict_dfs.keys(): self.NBF.append(Frame(self.NB)) self.NB_DF.append(pd.concat([df, dict_dfs[key]], axis=1)) self.NB.add(self.NBF[-1], text=key) sh = tksheet.Sheet(self.NBF[-1], column_width=80, align="center", headers=list(self.NB_DF[-1].columns), header_font=("TkDefaultFont", 10, "bold"), empty_horizontal=0, empty_vertical=20, header_height=35) sh.enable_bindings( ("toggle_select", "drag_select", "column_select", "row_select", "column_width_resize", "arrowkeys", "right_click_popup_menu", "rc_select", "copy", "select_all")) sh.pack(anchor=W, fill="both", expand=True) self.NBS.append(sh) def set_expiry_date(self, event) -> None: self.expiry_date = self.date_combo_box.get() def set_ref_intvl(self, event) -> None: self.interval = float(self.ref_intvl_cbox.get()) def sheet_formatting(self) -> None: num_std_cols = 3 #Symb & ATM for i in range(len(self.NBS)): curr_sh = self.NBS[i] num_cols = len(self.NB_DF[i].columns) for col in enumerate(self.NB_DF[i].columns): curr_sh.set_column_data(col[0], values=self.NB_DF[i][col[1]]) if (not self.first_run): for i in range(curr_sh.get_total_rows()): for j in range(num_std_cols, num_cols - 2, 1): diff = float(curr_sh.get_cell_data(i, j)) - float( curr_sh.get_cell_data(i, j + 1)) perc_change = 1. if (float(curr_sh.get_cell_data(i, j - 1)) > 0.0): perc_change = diff * 100 / float( curr_sh.get_cell_data(i, j - 1)) if (diff < 0.): curr_sh.highlight_cells(row=i, column=j, bg=self.red, fg='white') elif diff == 0.0: curr_sh.highlight_cells(row=i, column=j, bg='white', fg='black') else: curr_sh.highlight_cells(row=i, column=j, bg='blue', fg='white') if perc_change > 40.: curr_sh.highlight_cells(row=i, column=j, bg='green', fg='white') curr_sh.set_currently_selected(0, num_cols - 1) curr_sh.refresh() def setup_main_window(self, window) -> None: self.sh_window: Tk = window self.sh_window.title('Option chain analyzer') window_width: int = self.sh_window.winfo_reqwidth() window_height: int = self.sh_window.winfo_reqheight() position_right: int = int(self.sh_window.winfo_screenwidth() / 2 - window_width / 2) position_down: int = int(self.sh_window.winfo_screenheight() / 2 - window_height / 2) #self.sh_window.geometry("1200x600+{}+{}".format(position_right, position_down)) self.sh_window.geometry("1200x600+300+200") #self.sh_window.geometry("+{}+{}".format(position_right, position_down)) self.sh_frame: Frame = Frame(self.sh_window) self.stock_frame: Frame = Frame(self.sh_window) top_frame: Frame = Frame(self.sh_window) top_frame.rowconfigure(0, weight=1) top_frame.columnconfigure(0, weight=1) top_frame.pack(anchor=S, expand=False, side=TOP) row_idx: int = 0 self.index_call = True self.get_expiry_dates() date_var: StringVar = StringVar() date_var.set(" ") lbl_exp_date: Label = Label(top_frame, text='Index Expiry', justify=LEFT, font=("TkDefaultFont", 10, "bold")) #lbl_exp_date.grid(row=row_idx,column=0,sticky=N+S+W) lbl_exp_date.pack(anchor=N, expand=False, side=LEFT) self.date_combo_box = Combobox(top_frame, width=10, textvariable=date_var) self.date_combo_box.pack(anchor=N, expand=False, side=LEFT) #self.date_combo_box.grid(row=row_idx, column=1, sticky=N + S + E + W) self.date_combo_box.bind('<<ComboboxSelected>>', self.set_expiry_date) self.date_combo_box['values'] = tuple(self.expiry_dates) self.date_combo_box.set(self.expiry_dates[0]) self.date_combo_box.configure(state='readonly') row_idx += 1 self.index_call = False self.get_expiry_dates() date_var_stock: StringVar = StringVar() date_var_stock.set(" ") lbl_exp_date_stock: Label = Label(top_frame, text='Stock Expiry', justify=LEFT, font=("TkDefaultFont", 10, "bold")) #lbl_exp_date_stock.grid(row=row_idx,column=0,sticky=N+S+W) lbl_exp_date_stock.pack(anchor=N, expand=False, side=LEFT) self.date_combo_box_stock = Combobox(top_frame, width=10, textvariable=date_var_stock) self.date_combo_box_stock.pack(anchor=N, expand=False, side=LEFT) #self.date_combo_box_stock.grid(row=row_idx, column=1, sticky=N + S + E + W) self.date_combo_box_stock.bind('<<ComboboxSelected>>', self.set_expiry_date) self.date_combo_box_stock['values'] = tuple(self.expiry_dates) self.date_combo_box_stock.set(self.expiry_dates[0]) self.date_combo_box_stock.configure(state='readonly') row_idx += 1 self.check_stocks_var = IntVar() self.check_stocks = Checkbutton(top_frame, text = "Stocks", variable = self.check_stocks_var, \ onvalue = 1, offvalue = 0, width = 10) #self.check_stocks.grid(row=row_idx, column=1, sticky=N + S + E + W) self.check_stocks.pack(anchor=N, expand=False, side=LEFT) self.check_stocks_var.set(0) row_idx += 1 self.check_index_var = IntVar() self.check_index = Checkbutton(top_frame, text = "Index", variable = self.check_index_var, \ onvalue = 1, offvalue = 0, width = 10) #self.check_index.grid(row=row_idx, column=1, sticky=N + S + E + W) self.check_index.pack(anchor=N, expand=False, side=LEFT) self.check_index_var.set(1) row_idx += 1 ref_intvl: Stringvar = StringVar() ref_intvl.set(" ") lbl_refresh_interval: Label = Label(top_frame, text='Interval (min)', justify=LEFT, font=("TkDefaultFont", 10, "bold")) #lbl_refresh_interval.grid(row=row_idx,column=0,sticky=N+S+W) lbl_refresh_interval.pack(anchor=N, expand=False, side=LEFT) self.ref_intvl_cbox: Combobox = Combobox(top_frame, width=10, textvariable=ref_intvl) #self.ref_intvl_cbox.grid(row=row_idx, column=1, sticky=N + S + E + W) self.ref_intvl_cbox.pack(anchor=N, expand=False, side=LEFT) self.ref_intvl_cbox.bind('<<ComboboxSelected>>', self.set_ref_intvl) self.ref_intvl_cbox['values'] = tuple(range(10, 600, 20)) self.ref_intvl_cbox.configure(state='readonly') row_idx += 1 self.start_button: Button = Button(top_frame, text='START', command=self.main_recursive, width=10) #self.start_button.grid(row=row_idx, column=1, sticky=N + S + E + W) self.start_button.pack(anchor=N, expand=True, side=TOP) row_idx += 1 canvas = tk.Canvas(self.sh_window) scroll_y = tk.Scrollbar(self.sh_window, orient="vertical", command=canvas.yview) bot_frame: Frame = Frame(canvas) #bot_frame = ScrollFrame(bot_frame) #bot_frame.rowconfigure(0, weight=1) #bot_frame.columnconfigure(0, weight=1) #bot_frame.grid(row=row_idx,column=0,sticky=N+S+W) #bot_frame = ScrollableFrame(self.sh_window) #bot_frame = ScrollFrame(self.sh_window) #bot_frame.rowconfigure(1, weight=1) #bot_frame.columnconfigure(0, weight=1) #bot_frame.pack(anchor=N, expand=False, side=LEFT) #bot_frame: Listbox = Listbox(self.sh_window) #bot_frame.pack(side=LEFT,fill='both') #vscrollbar = Scrollbar(self.sh_window) #vscrollbar.pack(side = LEFT, fill = 'both') #for i in range(10000): # bot_frame.insert(END,i) self.stock_check_var: List[IntVar] = [] self.stock_check: List[Checkbutton] = [] int_col = 0 tmp_row_idx = row_idx for stk in enumerate(self.stock_symbs): #if(int(stk[0])>30 and int_col==0): # int_col = 1 # row_idx = tmp_row_idx self.stock_check_var.append(IntVar()) cb = Checkbutton(bot_frame, text = stk[1], variable = self.stock_check_var[-1], \ onvalue = 1, offvalue = 0, width =12) cb.pack() if (stk[1] in self.popular_stocks): self.stock_check_var[-1].set(1) else: self.stock_check_var[-1].set(0) self.stock_check.append(cb) row_idx += 1 canvas.create_window(0, 0, anchor='nw', window=bot_frame) canvas.update_idletasks() canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scroll_y.set) canvas.pack(fill='y', expand=False, side=LEFT) scroll_y.pack(fill='y', side=LEFT, expand=False) self.sh_window.mainloop() def get_stock_symbols(self) -> None: url = 'https://www.nseindia.com/api/master-quote' url_oc = 'https://www.nseindia.com/' response = self.session.get(url_oc, headers=self.hdr, timeout=5) ck = response.cookies response = self.session.get(url, headers=self.hdr, timeout=5, cookies=ck) json_data = response.json() self.stock_symbs = list(json_data) def get_option_chain_data(self) -> None: if self.index_call: self.url = 'https://www.nseindia.com/api/option-chain-indices?symbol=' + self.stock_symb else: self.url = 'https://www.nseindia.com/api/option-chain-equities?symbol=' + self.stock_symb try: self.response = self.session.get(self.url, headers=self.hdr, timeout=5, cookies=self.cookies) if self.response.status_code == 401: self.session.close() self.session = requests.Session() request = self.session.get(self.url_oc, headers=self.hdr, timeout=5) self.cookies = dict(request.cookies) self.response = self.session.get(self.url, headers=self.hdr, timeout=5, cookies=self.cookies) print("reset cookies") except Exception as err: print(self.response) print(err, "5") #self.make_intial_nse_connection() self.sh_window.after((10 * 1000), self.main_recursive) return #try: # self.session.close() # self.session = requests.Session() # request = self.session.get(self.url_oc, headers=self.hdr, timeout=5) # self.cookies = dict(request.cookies) # self.response = self.session.get(self.url,headers=self.hdr,timeout=5,cookies=self.cookies) # print("reset cookies") #except Exception as err: # print(request) # print(response) # print(err, "5") # return def get_expiry_dates(self) -> Tuple: if self.index_call: self.stock_symb = 'NIFTY' else: self.stock_symb = 'INFY' self.get_option_chain_data() json_data = self.response.json() self.expiry_dates: List = [] self.expiry_dates = json_data['records']['expiryDates'] def draw_plots(self): symbb = "BANKNIFTY" self.plot_keys = ['PCR OTM', 'LTP'] mrk_type = ['-ro', '--gs'] #self.plot_keys = ['PCR OTM'] idx: Int = -1 plt.clf() maxx = 0.0 minn = 10000.0 for key in enumerate(self.plot_keys): idx = -1 try: idx = self.nb_names.index(key[1]) except: pass if (idx != -1): xx = self.NB_DF[idx].loc[self.NB_DF[idx]['SYMB'] == symbb] y_data = (xx[xx.columns[3:]].values) y_dat = (y_data[0].tolist()) y_dat.reverse() x_data = range(len(y_dat)) if (minn > min(y_dat)): minn = min(y_dat) if (maxx < max(y_dat)): maxx = max(y_dat) if self.index_call: #self.graph_index.set_ydata(y_dat) #self.graph_index.set_xdata(x_data) plt.plot(x_data, y_dat, mrk_type[key[0]], label=key[1], markersize=1) plt.legend() plt.xlim([0, 1.1 * len(y_dat)]) plt.ylim([.9 * minn, 1.1 * maxx]) plt.pause(.0001) plt.show(block=False) strr = datetime.today().strftime('%Y-%m-%d') plt.title(symbb + "--->" + strr) plt.savefig(strr + '.pdf', dpi=300) def append_df_with_OC(self): self.diff_otm: List = [] self.atms: List = [] self.pcr: List = [] self.pcr_otm: List = [] self.pcr_far_otm: List = [] self.live_prices: List[float] = [] self.DIFF_otm: List[float] = [] self.call_sum_otm: List[float] = [] self.put_sum_otm: List[float] = [] self.call_sum_far_otm: List[float] = [] self.put_sum_far_otm: List[float] = [] for stk in enumerate(self.SYMBS): self.stock_symb = stk[1] self.get_option_chain_data() if self.response is not None: try: json_data = self.response.json() except: json_data = {} return #print(stk) #quote = nse.get_quote(stk) #print(quote['data'][0]['lastPrice']) #print(json_data['records']['data']) #try: # self.live_prices.append(float(quote['data'][0]['lastPrice'].replace(',',''))) #except: # self.live_prices.append('null') if self.index_call: match_date = self.date_combo_box.get() else: match_date = self.date_combo_box_stock.get() my_atm: float = 0.0 strike_prices: List[float] = [data['strikePrice'] for data in json_data['records']['data'] \ if (str(data['expiryDate']).lower() == str(match_date).lower())] ce_values: List[dict] = [data['CE'] for data in json_data['records']['data'] \ if "CE" in data and (str(data['expiryDate'].lower()) == str(match_date.lower()))] pe_values: List[dict] = [data['PE'] for data in json_data['records']['data'] \ if "PE" in data and (str(data['expiryDate'].lower()) == str(match_date.lower()))] ce_data: pd.DataFrame = pd.DataFrame(ce_values) pe_data: pd.DataFrame = pd.DataFrame(pe_values) #print(list(ce_data.columns)) curr_price = ce_data['underlyingValue'][0] if (self.first_run): self.first_run_live_price.append(curr_price) try: diff = [abs(x - curr_price) for x in strike_prices] min_pos = diff.index(min(diff)) my_atm = strike_prices[min_pos] self.atms.append(my_atm) except: self.atms.append('null') self.live_prices.append(curr_price / self.first_run_live_price[stk[0]]) ce_data_otm: pd.DataFrame = ce_data[min_pos:min_pos + 4] pe_data_otm: pd.DataFrame = pe_data[min_pos - 2:min_pos + 2] ce_data_far_otm: pd.DataFrame = ce_data[min_pos + 4:min_pos + 8] pe_data_far_otm: pd.DataFrame = pe_data[min_pos - 7:min_pos - 3] call_sum_otm = ce_data_otm['openInterest'].sum() put_sum_otm = pe_data_otm['openInterest'].sum() diff_otm = (ce_data_otm['changeinOpenInterest'].sum() - pe_data_otm['changeinOpenInterest'].sum() ) / ce_data_otm['changeinOpenInterest'].sum() if (call_sum_otm == 0.): call_sum_otm = 0.001 if (put_sum_otm == 0.): put_sum_otm = 0.001 call_sum_far_otm = ce_data_far_otm['openInterest'].sum() put_sum_far_otm = pe_data_far_otm['openInterest'].sum() if (call_sum_far_otm == 0.): call_sum_far_otm = 0.001 if (put_sum_far_otm == 0.): put_sum_far_otm = 0.001 diff_far_otm = call_sum_far_otm - put_sum_far_otm if (ce_data['openInterest'].sum() != 0): pcr_ratio = float(pe_data['openInterest'].sum()) / float( ce_data['openInterest'].sum()) else: pcr_ratio = float(pe_data['openInterest'].sum()) / .001 self.pcr.append(pcr_ratio) self.call_sum_otm.append(call_sum_otm) self.put_sum_otm.append(put_sum_otm) self.call_sum_far_otm.append(call_sum_far_otm) self.put_sum_far_otm.append(put_sum_far_otm) self.pcr_otm.append(put_sum_otm / call_sum_otm) self.pcr_far_otm.append(put_sum_far_otm / call_sum_far_otm) self.diff_otm.append(diff_otm) self.live_price_normalized = list( map(mul, self.pcr_otm, self.live_prices)) #self.live_price_normalized = self.live_prices if (self.index_call): self.df_INDEX['SYMB'] = self.SYMBS self.df_INDEX['ATM'] = self.atms self.df_INDEX['CONST PRICE'] = self.first_run_live_price self.dict_dfs_INDEX['PCR'].insert(0, self.col_time, self.pcr) self.dict_dfs_INDEX['PCR'][self.col_time] = self.dict_dfs_INDEX[ 'PCR'][self.col_time].round(3) self.dict_dfs_INDEX['CE-OTM'].insert(0, self.col_time, self.call_sum_otm) self.dict_dfs_INDEX['PE-OTM'].insert(0, self.col_time, self.put_sum_otm) self.dict_dfs_INDEX['CE-FAR_OTM'].insert(0, self.col_time, self.call_sum_far_otm) self.dict_dfs_INDEX['PE-FAR_OTM'].insert(0, self.col_time, self.put_sum_far_otm) self.dict_dfs_INDEX['LTP'].insert(0, self.col_time, self.live_price_normalized) self.dict_dfs_INDEX['LTP'][self.col_time] = self.dict_dfs_INDEX[ 'LTP'][self.col_time].round(3) self.dict_dfs_INDEX['PCR OTM'].insert(0, self.col_time, self.pcr_otm) self.dict_dfs_INDEX['PCR OTM'][ self.col_time] = self.dict_dfs_INDEX['PCR OTM'][ self.col_time].round(3) self.dict_dfs_INDEX['PCR FAR OTM'].insert(0, self.col_time, self.pcr_far_otm) self.dict_dfs_INDEX['PCR FAR OTM'][ self.col_time] = self.dict_dfs_INDEX['PCR FAR OTM'][ self.col_time].round(3) self.dict_dfs_INDEX['DIFF OTM'].insert(0, self.col_time, self.diff_otm) self.dict_dfs_INDEX['DIFF OTM'][ self.col_time] = self.dict_dfs_INDEX['DIFF OTM'][ self.col_time].round(3) self.dict_dfs_INDEX['DIFF OTM'][ self.col_time] = self.dict_dfs_INDEX['DIFF OTM'][ self.col_time].round(3) return self.df_INDEX, self.dict_dfs_INDEX else: self.df_STOCK['SYMB'] = self.SYMBS self.df_STOCK['ATM'] = self.atms self.df_STOCK['CONST PRICE'] = self.first_run_live_price self.dict_dfs_STOCK['PCR'].insert(0, self.col_time, self.pcr) self.dict_dfs_STOCK['PCR'][self.col_time] = self.dict_dfs_STOCK[ 'PCR'][self.col_time].round(3) self.dict_dfs_STOCK['CE-OTM'].insert(0, self.col_time, self.call_sum_otm) self.dict_dfs_STOCK['PE-OTM'].insert(0, self.col_time, self.put_sum_otm) self.dict_dfs_STOCK['CE-FAR_OTM'].insert(0, self.col_time, self.call_sum_far_otm) self.dict_dfs_STOCK['PE-FAR_OTM'].insert(0, self.col_time, self.put_sum_far_otm) self.dict_dfs_STOCK['LTP'].insert(0, self.col_time, self.live_price_normalized) self.dict_dfs_STOCK['LTP'][self.col_time] = self.dict_dfs_INDEX[ 'LTP'][self.col_time].round(3) self.dict_dfs_STOCK['PCR OTM'].insert(0, self.col_time, self.pcr_otm) self.dict_dfs_STOCK['PCR OTM'][ self.col_time] = self.dict_dfs_STOCK['PCR OTM'][ self.col_time].round(3) self.dict_dfs_STOCK['PCR FAR OTM'].insert(0, self.col_time, self.pcr_far_otm) self.dict_dfs_STOCK['PCR FAR OTM'][ self.col_time] = self.dict_dfs_STOCK['PCR FAR OTM'][ self.col_time].round(3) self.dict_dfs_STOCK['DIFF OTM'].insert(0, self.col_time, self.diff_otm) self.dict_dfs_STOCK['DIFF OTM'][ self.col_time] = self.dict_dfs_STOCK['DIFF OTM'][ self.col_time].round(3) return self.df_STOCK, self.dict_dfs_STOCK
def studentregistration(): removeallwidget() mainheading() btn = Button(root, text="Back", bd=5, font=("Ariel", 10), command=back1) btn.grid(row=3, column=0) lab = Label(root, text="New Student Registration", font=("Ariel", 20, "bold")) lab.grid(row=4, column=4) lab8 = Label(root, text="Admission Type", font=("Ariel", 20)) lab8.grid(row=5, column=3) admissiontypeentry = Combobox(root, values=["Entrance", "Direct"], textvar=admissiontypeentryv, state="readonly") admissiontypeentry.grid(row=5, column=5) admissiontypeentry.bind("<<ComboboxSelected>>", conditional) lab1 = Label(root, text="Full Name", font=("Ariel", 20)) lab1.grid(row=8, column=3) nameentry = Entry(root, textvar=nameentryv, border=10) nameentry.grid(row=8, column=5) lab2 = Label(root, text="Father's Name", font=("Ariel", 20)) lab2.grid(row=9, column=3) fnameentry = Entry(root, textvar=fnameentryv, border=10) fnameentry.grid(row=9, column=5) lab3 = Label(root, text="Mother's Name", font=("Ariel", 20)) lab3.grid(row=10, column=3) mnameentry = Entry(root, textvar=mnameentryv, border=10) mnameentry.grid(row=10, column=5) lab4 = Label(root, text="Date Of Birth", font=("Ariel", 20)) lab4.grid(row=11, column=3) global dobentry dobentry = DateEntry(root, background="blue", border=10, date_pattern="YYYY-MM-DD", state="readonly") dobentry.grid(row=11, column=5) lab5 = Label(root, text="Qualification", font=("Ariel", 20)) lab5.grid(row=12, column=3) qualificationentry = Combobox(root, values=["10th", "12th"], textvar=qualificationentryv, state="readonly") qualificationentry.grid(row=12, column=5) lab6 = Label(root, text="Mobile Number", font=("Ariel", 20)) lab6.grid(row=13, column=3) mobilenumber = Entry(root, textvar=mobilenumberv) mobilenumber.grid(row=13, column=5) mobilenumber.configure(validate="key", validatecommand=(callback, "%P")) lab7 = Label(root, text="Email ID", font=("Ariel", 20)) lab7.grid(row=14, column=3) emailid = Entry(root, textvar=emailidv) emailid.grid(row=14, column=5) lab8 = Label(root, text="Address", font=("Ariel", 20)) lab8.grid(row=15, column=3) global addressentry addressentry = Text(root, border=10, insertwidth=1, width=50, height=5, wrap=WORD) addressentry.grid(row=15, column=5) btn1 = Button(root, text="Submit", bd=10, font=("Ariel", 20, "bold"), command=registeredstdata) btn1.grid(row=17, column=4)
class bilgi_islem(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.initUI(parent) def initUI(self, parent): self.frame1 = LabelFrame(self, text="HASTA BİLGİLERİ", fg="black", font="serif 15 bold") self.frame1.grid(row=0, column=0, padx=20, pady=20) self.bir = StringVar() self.tcno = Label(self.frame1, text="T.C. Kimlik No", fg="black", font="serif 10 bold") self.tcno.grid(row=0, column=0, padx=20, pady=20, sticky="W") self.tcnoo = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.bir) self.tcnoo.grid(row=0, column=1, padx=20) self.tcnooo = Button(self.frame1, text="BUL", bg="green", fg="black", font="serif 10 bold", command=self.hastabilgi) self.tcnooo.grid(row=0, column=2, padx=(0,20), pady=20, sticky="W") self.iki = StringVar() self.hastaad = Label(self.frame1, text="Ad - Soyad", fg="black", font="serif 10 bold") self.hastaad.grid(row=1, column=0, padx=20, sticky="W") self.hastaadd = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.iki) self.hastaadd.grid(row=1, column=1) self.uc = StringVar() self.hastayas = Label(self.frame1, text="Yaş", fg="black", font="serif 10 bold") self.hastayas.grid(row=2, column=0, pady=20, padx=20, sticky="W") self.hastayass = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.uc) self.hastayass.grid(row=2, column=1) self.cinsiyet = IntVar() self.cinsiyet.set(1) self.hastacinsiyet = Label(self.frame1, text="Cinsiyet", fg="black", font="serif 10 bold") self.hastacinsiyet.grid(row=3, column=0, padx=20, sticky="W") self.hastacinsiyeterkek = Radiobutton(self.frame1, text="Erkek", font="serif 10 bold", variable=self.cinsiyet, value=1) self.hastacinsiyeterkek.place(x=200, y=150) self.hastacinsiyetkadın = Radiobutton(self.frame1, text="Kadın", font="serif 10 bold", variable=self.cinsiyet, value=2) self.hastacinsiyetkadın.place(x=300, y=150) self.dort = StringVar() self.hastaadres = Label(self.frame1, text="Adres", fg="black", font="serif 10 bold") self.hastaadres.grid(row=4, column=0, pady=20, padx=20, sticky="W") self.hastaadress = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.dort) self.hastaadress.grid(row=4, column=1) self.hizmet = StringVar() self.yapilanhizmet = Label(self.frame1, text="Yapılan Hizmet", fg="black", font="serif 10 bold") self.yapilanhizmet.grid(row=5, column=0, padx=20, sticky="W") self.yapilanhizmett = Combobox(self.frame1, width=27, textvariable=self.hizmet, font="serif 10 bold", justify="center") self.yapilanhizmett['values'] = ( "Acil Yardım Uygulamaları", "Ambulans Hizmeti", "Apse Boşaltma", "Diğer", "Dikiş (Sütur) Atma", "Enjeksiyon", "Evde Hasta Bakım Hizmetleri", "Hemoglobin Ölçümü", "Kulak Yıkama", "Nasır Alma", "Pansuman ve Küçük Cerrahi Müdahale", "Serum Takma ve Takibi", "Sonda Takma", "Tırnak Çekme" "Tansiyon Takibi", "Yanık Bakımı", "Yatak Yarası Bakımı", ) self.yapilanhizmett.grid(row=5, column=1) self.bes = StringVar() self.tarih = Label(self.frame1, text="Tarih (gg.aa.yyyy)", fg="black", font="serif 10 bold") self.tarih.grid(row=6, column=0, pady=20, padx=20, sticky="W") self.tarihh = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.bes) self.tarihh.grid(row=6, column=1) self.frame2 = LabelFrame(self, text="FİYATLANDIRMA", fg="black", font="serif 15 bold") self.frame2.grid(row=0, column=1) self.alti = StringVar() self.kullanilanmalzeme = Label(self.frame2, text="Kullanılan Malzeme", fg="black", font="serif 10 bold") self.kullanilanmalzeme.grid(row=0, column=0, padx=20, pady=20, sticky="W") self.kullanilanmalzemee = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.alti) self.kullanilanmalzemee.grid(row=0, column=1, padx=20) self.yedi = StringVar() self.yedi.set(0) self.malzemeadet = Label(self.frame2, text="Kullanılan Malzeme Adeti", fg="black", font="serif 10 bold") self.malzemeadet.grid(row=1, column=0, padx=20, sticky="W") self.malzemeadett = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.yedi) self.malzemeadett.grid(row=1, column=1) self.sekiz = StringVar() self.sekiz.set(0) self.malzemefiyat = Label(self.frame2, text="Kullanılan Malzeme Birim Fiyatı", fg="black", font="serif 10 bold") self.malzemefiyat.grid(row=2, column=0, pady=20, padx=20, sticky="W") self.malzemefiyatt = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.sekiz) self.malzemefiyatt.grid(row=2, column=1) self.dokuz = StringVar() self.dokuz.set(0) self.alinanucret = Label(self.frame2, text="Hastadan Alınan Ücret", fg="black", font="serif 10 bold") self.alinanucret.grid(row=3, column=0, padx=20, sticky="W") self.alinanucrett = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.dokuz) self.alinanucrett.grid(row=3, column=1) self.maliyetmalzeme = IntVar() self.maliyetmalzeme.set(0) self.malzememaliyet = Label(self.frame2, text="Kullanılan Malzeme Maliyeti", fg="black", font="serif 10 bold") self.malzememaliyet.grid(row=4, column=0, pady=20, padx=20, sticky="W") self.malzememaliyett = Entry(self.frame2, text="", width=30, font="serif 10 bold", state="disabled", textvariable=self.maliyetmalzeme, justify="center") self.malzememaliyett.grid(row=4, column=1) self.frame3 = LabelFrame(self, text="ÖZET", fg="black", font="serif 15 bold") self.frame3.grid(row=0, column=3, padx=20) self.on = StringVar() self.hemsireadi = Label(self.frame3, text="Hemşire Adı", fg="black", font="serif 10 bold") self.hemsireadi.grid(row=0, column=0, padx=20, pady=20, sticky="W") self.hemsireadi = Entry(self.frame3, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.on) self.hemsireadi.grid(row=0, column=1, padx=20) self.kaydetbuton = Button(self.frame3, text="KAYDET", bg="green", fg="black", width=25, font="serif 10 bold", command=self.kaydet) self.kaydetbuton.grid(row=2, column=0, padx=20) self.temizlebuton = Button(self.frame3, text="TEMİZLE", bg="red", fg="black", width=25, font="serif 10 bold", command=self.temizle) self.temizlebuton.grid(row=2, column=1) self.mesajkutusu1 = StringVar() self.mesaj1 = Entry(self.frame3, text="", width=60, font="serif 10 bold", state="disabled", textvariable=self.mesajkutusu1, justify="center") self.mesaj1.grid(row=3, column=0, columnspan=2, padx=20, pady=20) self.mesaj2 = Label(self.frame3, text="") self.mesaj2.grid(row=4, column=0, columnspan=2, padx=20, pady=(0,20)) self.grid() pass def hastabilgi(self): cursor.execute("SELECT * FROM bilgiislemtablo WHERE tcno=?",(self.tcnoo.get(),)) data = cursor.fetchall() if data: for i in data: self.iki.set(i[1]) self.uc.set(i[2]) if(i[3] == "Kadın"): self.cinsiyet.set(2) else: self.cinsiyet.set(1) self.dort.set(i[4]) self.hizmet.set(i[5]) self.bes.set(i[6]) self.alti.set(i[7]) self.yedi.set(i[8]) self.sekiz.set(i[9]) self.dokuz.set(i[10]) self.maliyetmalzeme.set(i[11]) self.on.set(i[13]) else: self.after(2000, self.after_method) self.mesaj2.config(text="Hasta Bilgisi Yok", bg="red", fg="black", font="serif 10 bold", width=25, height=2) pass def kaydet(self): tc = self.tcnoo.get() adsoyad = self.hastaadd.get() yas = self.hastayass.get() hastacinsiyet = self.cinsiyet.get() adres = self.hastaadress.get() hizmet = self.yapilanhizmett.get() tarih = self.tarihh.get() malzeme = self.kullanilanmalzemee.get() adet = self.malzemeadett.get() fiyat = self.malzemefiyatt.get() ucret = self.alinanucrett.get() hemsiread = self.hemsireadi.get() maliyet = int(adet) * int(fiyat) kasa = int(ucret) - int(maliyet) if(hastacinsiyet == 1): hastacinsiyet = "Erkek" if(hastacinsiyet == 2): hastacinsiyet = "Kadın" if((not tc) or (not adsoyad) or (not yas) or (not hastacinsiyet) or (not adres) or (not hizmet) or (not tarih) or (not malzeme) or (not hemsiread)): self.after(2000, self.after_method) self.mesaj2.config(text="Bazı Bilgiler Eksik", bg="red", fg="black", font="serif 10 bold", width=25, height=2) else: cursor.execute("Insert Into bilgiislemtablo (tcno,ad_soyad,yas,cinsiyet,adres,yapilanhizmet,tarih,kullanilanmalzeme,malzemeadet,malzemefiyat,alinanucret,malzememaliyet,kasa,hemsireadi) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)",(tc,adsoyad,yas,hastacinsiyet,adres,hizmet,tarih,malzeme,adet,fiyat,ucret,maliyet,kasa,hemsiread)) con.commit() self.maliyetmalzeme.set(maliyet) self.mesajkutusu1.set("Malzeme Maliyeti: {0}, Kasa: {1}".format(maliyet,kasa)) self.after(2000, self.after_method) self.mesaj2.config(text="İşlem Kayıt Edildi", bg="green", fg="black", font="serif 10 bold", width=25, height=2) pass def after_method(self): self.mesaj2.config(text="",bg="#f0f0f0") pass def temizle(self): self.bir.set("") self.iki.set("") self.uc.set("") self.dort.set("") self.bes.set("") self.alti.set("") self.yedi.set(0) self.sekiz.set(0) self.dokuz.set(0) self.on.set("") self.cinsiyet.set(value=1) self.hizmet.set("") self.maliyetmalzeme.set(0) self.mesajkutusu1.set("") pass
def __init__(self, guiListData, guiConfigName): self.listData = guiListData self.configName = guiConfigName self.prgList = self.listData["Programs"] self.configList = list(self.listData["Configurations"].keys()) self.exitCode = ECODE_SUCCESS self.msgboxFlag = 1 if self.configName == "": self.configName = self.select_network_config() self.window = Tk() self.window.title(shAppTitle) self.window.minsize(width=400, height=50) self.window.iconbitmap(shAppIcon) #- put window into screen center self.x = (self.window.winfo_screenwidth() - self.window.winfo_reqwidth()) / 2 self.y = (self.window.winfo_screenheight() - self.window.winfo_reqheight()) / 2 self.window.wm_geometry("+%d+%d" % (self.x, self.y)) self.window.protocol('WM_DELETE_WINDOW', self.cmd_cancel) self.checkAll = IntVar() #--- Panel Buttons self.frameButtons = Frame(self.window) self.frameButtons.pack(side=BOTTOM, expand=YES, fill=BOTH) self.lblFake = Label(self.frameButtons, width=4) self.lblFake.pack(side=RIGHT) self.buttonCancel = Button(self.frameButtons, text="Cancel", width=10, command=self.cmd_cancel) self.buttonCancel.pack(side=RIGHT, padx=5, pady=5) self.buttonRun = Button(self.frameButtons, text="Run", width=10, command=self.cmd_run) self.buttonRun.pack(side=RIGHT, padx=5, pady=5) #---Panel PrgList self.framePrgList = LabelFrame(self.window, bd=4, relief=RIDGE, text="Select programs to run:") self.framePrgList.pack(side=TOP, expand=YES, fill=BOTH) lbl = Label(self.framePrgList, bd=4, relief=RAISED) chk = Checkbutton(lbl, text="All", variable=self.checkAll, command=self.cmd_process_checkAll) chk.pack(side=LEFT, anchor="w", padx=20) lbl.pack(side=TOP, anchor="w", fill=X) lbl2 = Label(lbl, bd=4, relief=SUNKEN) lbl2.pack(anchor="w", fill=BOTH) lblinfo = Label(lbl2, text="Configuration: ") lblinfo.pack(side=LEFT, anchor="w", padx=5, fill=BOTH) self.combo1 = Combobox(lbl2) self.combo1["values"] = self.configList self.combo1.set(self.configName) self.combo1.pack(side=LEFT, anchor="w") self.combo1.bind('<<ComboboxSelected>>', self.cmd_combo1_selection_changed) self.generate_programs_panel()
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.
lb5 = Label(root, text="City",font="30") e5 = Entry(root,width=30,textvariable=sub) lb6 = Label(root, text="Country",font="30") e6 = Entry(root,width=30,textvariable=g) lb.place(x=150,y=250) lb1.place(x=150,y=300) lb2.place(x=150,y=350) lb3.place(x=150,y=400) lb4.place(x=150,y=450) lb5.place(x=150,y=500) lb6.place(x=150,y=550) e.place(x=430,y=250) e1.place(x=430,y=300) e2.place(x=430,y=350) e3.place(x=430,y=400) e4.place(x=430,y=450) e5.place(x=430,y=500) e6.place(x=430,y=550) v=["Department","Salary_sab","Country"] combo=Combobox(root,values=v,width=15) combo.place(x=450,y=750) button=Button(root,text="Group display",command=print_me) button.place(x=600,y=750) B = Button(root, text ="create", command = create) ins = Button(root, text ="Insert", command = Insert) dis = Button(root, text ="Display", command = Display) B.place(x=150,y=750) ins.place(x=220,y=750) dis.place(x=320,y=750) print(sname.get()) root.mainloop()
class shStartUpGUI: def __init__(self, guiListData, guiConfigName): self.listData = guiListData self.configName = guiConfigName self.prgList = self.listData["Programs"] self.configList = list(self.listData["Configurations"].keys()) self.exitCode = ECODE_SUCCESS self.msgboxFlag = 1 if self.configName == "": self.configName = self.select_network_config() self.window = Tk() self.window.title(shAppTitle) self.window.minsize(width=400, height=50) self.window.iconbitmap(shAppIcon) #- put window into screen center self.x = (self.window.winfo_screenwidth() - self.window.winfo_reqwidth()) / 2 self.y = (self.window.winfo_screenheight() - self.window.winfo_reqheight()) / 2 self.window.wm_geometry("+%d+%d" % (self.x, self.y)) self.window.protocol('WM_DELETE_WINDOW', self.cmd_cancel) self.checkAll = IntVar() #--- Panel Buttons self.frameButtons = Frame(self.window) self.frameButtons.pack(side=BOTTOM, expand=YES, fill=BOTH) self.lblFake = Label(self.frameButtons, width=4) self.lblFake.pack(side=RIGHT) self.buttonCancel = Button(self.frameButtons, text="Cancel", width=10, command=self.cmd_cancel) self.buttonCancel.pack(side=RIGHT, padx=5, pady=5) self.buttonRun = Button(self.frameButtons, text="Run", width=10, command=self.cmd_run) self.buttonRun.pack(side=RIGHT, padx=5, pady=5) #---Panel PrgList self.framePrgList = LabelFrame(self.window, bd=4, relief=RIDGE, text="Select programs to run:") self.framePrgList.pack(side=TOP, expand=YES, fill=BOTH) lbl = Label(self.framePrgList, bd=4, relief=RAISED) chk = Checkbutton(lbl, text="All", variable=self.checkAll, command=self.cmd_process_checkAll) chk.pack(side=LEFT, anchor="w", padx=20) lbl.pack(side=TOP, anchor="w", fill=X) lbl2 = Label(lbl, bd=4, relief=SUNKEN) lbl2.pack(anchor="w", fill=BOTH) lblinfo = Label(lbl2, text="Configuration: ") lblinfo.pack(side=LEFT, anchor="w", padx=5, fill=BOTH) self.combo1 = Combobox(lbl2) self.combo1["values"] = self.configList self.combo1.set(self.configName) self.combo1.pack(side=LEFT, anchor="w") self.combo1.bind('<<ComboboxSelected>>', self.cmd_combo1_selection_changed) self.generate_programs_panel() def generate_programs_panel(self): if self.configName not in self.configList: self.exitCode = ECODE_CONFIGURATION_NOT_FOUND ecode_str[ECODE_CONFIGURATION_NOT_FOUND] += self.configName self.window.withdraw() return self.configRecord = self.listData["Configurations"][self.configName] self.lblPrgList = Label(self.framePrgList) self.lblPrgList.pack(side=TOP, anchor="w", fill=BOTH) self.checks = [] self.checkAll.set(0) for prg in self.configRecord: var = IntVar() var.set(prg["Checked"]) prgRecord = self.get_program_record(prg["Program"]) if not prgRecord: self.exitCode = ECODE_PROGRAM_RECORD_NOT_FOUND ecode_str[ECODE_PROGRAM_RECORD_NOT_FOUND] += prg["Program"] self.window.withdraw() return chk2 = Checkbutton(self.lblPrgList, text=prgRecord["DisplayName"], variable=var, command=self.cmd_clear_checkAll) self.checks.append(var) chk2.pack(side=TOP, anchor="w", padx=25) def select_network_config(self): config = "Default" strNetworks = subprocess.check_output( ["netsh", "wlan", "show", "networks"]) if type(strNetworks) == bytes: strNetworks = strNetworks.decode('ascii', errors='ignore') netProfiles = self.listData["NetProfiles"] for rec in netProfiles: if rec["Network"] in strNetworks: config = rec["Configuration"] break return config def get_program_record(self, prgID): record = None for rec in self.prgList: if rec["Program"] == prgID: record = rec break return record def cmd_cancel(self): self.exitCode = ECODE_OPERATION_CANCELLED self.window.destroy() def cmd_run(self): self.exitCode = ECODE_SUCCESS var = 0 for rec in self.configRecord: prgRecord = self.get_program_record(rec["Program"]) if self.checks[var].get(): try: subprocess.Popen(prgRecord["Command"], shell=True) except: self.exitCode = ECODE_ERROR_RUNNING_PROGRAM ecode_str[ ECODE_ERROR_RUNNING_PROGRAM] += "\n" + rec["Command"] var += 1 time.sleep(0.2) self.window.destroy() def cmd_clear_checkAll(self): self.checkAll.set(0) def cmd_process_checkAll(self): for chk_val in self.checks: chk_val.set(1 if self.checkAll.get() else 0) def cmd_combo1_selection_changed(self, param): self.lblPrgList.destroy() self.configName = self.combo1.get() self.generate_programs_panel() def main_cycle(self): if self.exitCode > ECODE_SUCCESS: return self.exitCode = ECODE_UNKNOWN self.window.mainloop() self.msgboxFlag = 0
def tambahData(): top = Toplevel() top.title("Form Tambah Data") d_pad = LabelFrame(top, padx=30, pady=30) d_pad.grid(row=1, column=0) d_frame = LabelFrame(d_pad, text="Tambah Data", padx=30, pady=30) d_frame.grid(row=1, column=0) Label(d_frame, text="Nama :", anchor="w", width=15).grid(row=0, column=0) nama = Entry(d_frame, borderwidth=5) nama.grid(row=0, column=1, sticky="W") Label(d_frame, text="NIM :", anchor="w", width=15).grid(row=1, column=0) nim = Entry(d_frame, borderwidth=5) nim.grid(row=1, column=1, sticky="W") Label(d_frame, text="Jenis Kelamin :", anchor="w", width=15).grid(row=2, column=0) #Radio Button jk = StringVar() jk.set("Laki-Laki") r1 = Radiobutton(d_frame, text="Laki-Laki", value="Laki-Laki", variable=jk) r2 = Radiobutton(d_frame, text="Perempuan", value="Perempuan", variable=jk) r1.grid(row=2, column=1, sticky="W") r2.grid(row=3, column=1, sticky="W") #ambil dengan i.get() Label(d_frame, text="Fakultas :", anchor="w", width=15).grid(row=4, column=0) #ComboBox fa = StringVar() datafak = ("FIP", "FPIPS", "FPBS", "FPSD", "FPMIPA", "FPTK", "FPOK", "FPEB", "K.D CIBIRU", "K.D SUMEDANG", "K.D TASIKMALAYA", "K.D PURWAKARTA", "K.D SERANG") cb = Combobox(d_frame, values=datafak) cb.set("Pilih Fakultas") cb.grid(row=4, column=1) Label(d_frame, text="Keaktifan :", anchor="w", width=15).grid(row=5, column=0) #CheckBox chkValue1 = BooleanVar() k1 = Checkbutton(d_frame, text="UKM", var=chkValue1, onvalue=1, offvalue=0) k1.grid(row=5, column=1, sticky="W") chkValue2 = BooleanVar() k2 = Checkbutton(d_frame, text="BEM", var=chkValue2, onvalue=1, offvalue=0) k2.grid(row=6, column=1, sticky="W") chkValue3 = BooleanVar() k3 = Checkbutton(d_frame, text="Paguyuban", var=chkValue3, onvalue=1, offvalue=0) k3.grid(row=7, column=1, sticky="W") def validasi(): if (nama.get() != "" and nim.get() != "" and cb.get() != "Pilih Fakultas"): save() else: messagebox.showinfo('Mohon Maaf', 'Data Belum Terisi Dengan Benar') def save(): datamhs.append( Mahasiswa(nama.get(), nim.get(), jk.get(), cb.get(), chkValue1.get(), chkValue2.get(), chkValue3.get())) messagebox.showinfo('Selamat', 'Data Berhasil Tersimpan!') top.destroy() b_save = Button(d_frame, text="Simpan", command=validasi) b_save.grid(row=8, column=1, sticky="W")
name_lbl.place(x=150, y=230) name_ent = Entry(form, width=15, font=('Arial', 14, '')) name_ent.place(x=350, y=230) address_lbl = Label(form, text='ADDRESS', font=('Arial', 18, 'bold'), bg='skyblue') address_lbl.place(x=150, y=320) address_ent = Entry(form, width=15, font=('Arial', 15, '')) address_ent.place(x=350, y=320) gen_lbl = Label(form, text='GENDER', font=('Arial', 18, 'bold'), bg='skyblue') gen_lbl.place(x=150, y=390) gen_ent = Combobox(form, width=20, font=('', 10, 'bold'), values=['MALE', 'FEMALE', 'OTHER']) gen_ent.place(x=350, y=390) gen_ent.set('Select Option') save_btn = Button(form, command=lambda: reg(), width=10, text='SAVE', font=('', 22, 'bold', 'underline'), bd=15, bg='skyblue') save_btn.place(x=300, y=470) frm = Frame(form, bg='Skyblue') frm.place(relx=.40, rely=.15, width=800, height=500)
def __init__(self): super().__init__() self.segments = None self.wm_title(__doc__) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label='Open EDI', command=self.open_edi) self.filemenu.add_command(label='Open XML', command=self.open_xml) self.menubar.add_cascade(label="File", menu=self.filemenu) self.config(menu=self.menubar) self.lbl_message = Label(self, text='Message') self.lbl_message.grid(row=0, column=0) self.cb_message = Combobox(self, values=list(MD)) self.cb_message.bind('<<ComboboxSelected>>', self.select_message) self.cb_message.grid(row=1, column=0) self.lbl_segment = Label(self, text='Segment') self.lbl_segment.grid(row=0, column=1) self.cb_segment = Combobox(self, values=list(SD)) self.cb_segment.bind('<<ComboboxSelected>>', self.select_segment) self.cb_segment.grid(row=1, column=1) self.lbl_code = Label(self, text='Code') self.lbl_code.grid(row=0, column=2) self.cb_code = Combobox(self, values=list(ED)) self.cb_code.bind('<<ComboboxSelected>>', self.select_code) self.cb_code.grid(row=1, column=2) self.lbl_formats = Label(self, text='Formats') self.lbl_formats.grid(row=0, column=3, sticky=W) self.formats = Frame(self) self.formats.grid(row=1, column=3) self.var_edi = IntVar() self.chk_edi = Checkbutton(self.formats, text='EDI', variable=self.var_edi, command=self.switch_edi) self.chk_edi.pack(side=LEFT) self.var_segments = IntVar() self.chk_segments = Checkbutton(self.formats, text='Segments', variable=self.var_segments, command=self.switch_segments) self.chk_segments.pack(side=LEFT) self.var_xml = IntVar() self.chk_xml = Checkbutton(self.formats, text='XML', variable=self.var_xml, command=self.switch_xml) self.chk_xml.pack(side=LEFT) self.var_report = IntVar() self.chk_report = Checkbutton(self.formats, text='Report', variable=self.var_report, command=self.switch_report) self.chk_report.pack(side=LEFT) self.editor_message = Editor(self) self.editor_segment = Editor(self) self.editor_code = Editor(self) self.editor_edi = Editor(self) self.editor_edi.sc_text.bind('<KeyRelease>', self.edit_edifact) self.editor_edi.title('EDI') self.editor_segments = Editor(self) self.editor_segments.sc_text.bind('<KeyRelease>', self.edit_segments) self.editor_segments.title('Segments') self.editor_xml = Editor(self) self.editor_xml.sc_text.bind('<KeyRelease>', self.edit_xml) self.editor_xml.title('XML') self.editor_report = Editor(self) self.editor_report.title('Report') self.mainloop()
class AddProducts: def __init__(self, service, top_level): self.service = service self.top_level = top_level # Gui elements self.name_entry = None self.shops_combo = None self.category_combo = None self.search_button = None self.listbox = None # Last searched products list self.products_found = None # List self.products_found_positions = None # Dictionary self.existing = None # Set self.init_gui() def init_gui(self): self.top_level.geometry("600x750") self.name_entry = Entry(self.top_level) self.name_entry.grid(row=0, column=0, columnspan=2, sticky=W + E) self.name_entry.insert(0, 'Product name') self.name_entry.bind("<FocusIn>", lambda args: self.name_entry.delete('0', 'end')) # shop_choices = ['Emag', 'Altex', 'Media Galaxy'] shop_choices = ['Emag'] self.shops_combo = Combobox(self.top_level, values=shop_choices) self.shops_combo.grid(row=1, column=0, sticky=W + E) self.shops_combo.current(0) # Make it configurable from config file category_choices = [ 'Laptops', 'Phones', 'Tablets', 'Tvs', 'Portable speakers', 'Headphones', 'Consoles' ] self.category_combo = Combobox(self.top_level, values=category_choices) self.category_combo.grid(row=1, column=1, sticky=W + E) self.category_combo.current(0) # Search bu self.search_button = Button(self.top_level, text='Search', command=self.on_search_event) self.search_button.grid(row=2, column=0, columnspan=2, sticky=W + E + S + N) # Frame to encapsulate the listbox and scrollbar frame = Frame(self.top_level, bd=2, relief=SUNKEN) scrollbar = Scrollbar(frame) scrollbar.pack(side=RIGHT, fill=Y) self.listbox = Listbox(frame, bd=0, yscrollcommand=scrollbar.set) self.listbox.bind('<Double-Button-1>', self.on_product_inspect) self.listbox.bind('<Return>', self.on_product_inspect) self.listbox.pack(fill=BOTH, expand=1) frame.grid(row=3, column=0, columnspan=2, sticky=W + E + N + S) scrollbar.config(command=self.listbox.yview) for x in range(3): Grid.rowconfigure(self.top_level, x, pad=10) Grid.rowconfigure(self.top_level, 3, weight=1) for x in range(2): Grid.columnconfigure(self.top_level, x, weight=1) def on_product_inspect(self, event): w = event.widget index = int(w.curselection()[0]) new_win = Toplevel(self.top_level) ex = ExamineNewProduct(self.service, self.products_found[index], new_win) self.service.add_observer(ex, Events.NEW_P) new_win.protocol("WM_DELETE_WINDOW", lambda: self.destroy_examination(ex, new_win)) def destroy_examination(self, ex, new_win): self.service.remove_observer(ex, Events.NEW_P) new_win.destroy() def on_search_event(self): self.products_found = self.service.search_products( self.name_entry.get(), self.category_combo.get(), 'Emag') if self.products_found is None: return self.listbox.delete(0, 'end') self.products_found_positions = {} self.existing = set() for index, product in enumerate(self.products_found): self.listbox.insert(END, product.title) self.products_found_positions[product.id] = index if self.service.product_already_exists(product.id): self.listbox.itemconfig(index, foreground='orange') self.existing.add(product.id) def update(self, data, event): if event == Events.NEW_P: id = data if self.products_found_positions is not None and id in self.products_found_positions: index = self.products_found_positions[id] self.listbox.itemconfig(index, foreground='orange')
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 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 manualattendance(): #root=tk.Tk() remove_widgets_train() def date_func(ent): return ent.get_date() def clear(): entry1.delete(0, 'end') entry2.delete(0, 'end') combo.delete(0, 'end') res = "" def manual_update(): a = int(entry1.get()) b = entry2.get() c = str(date_func(ent)) m = 0 d = combo.get() print(a, b, c, d) for x in col.find(): print("going into loop") if (x["id"] == a): if (x["date"] == c): print("going into main condition") z = x["presence"] myquery = {"presence": z} newvalues = {"$set": {"presence": d}} col.update_one(myquery, newvalues) print(z) m = 1 else: print("on that date employee update is not possible") else: print("no id found") if (m == 1): messagebox.showinfo("updated", "record sucessfully updated") def show(): try: df = pd.DataFrame(col.find()) a = str(ent.get_date()) mylist = df[df.apply( lambda row: row.astype(str).str.contains(a).any(), axis=1)][['id', 'name', 'date', 'presence']] print(mylist) #results['T'] = mylist frame = Frame(root, bd=2, relief=SUNKEN) results = Scrollbar(frame) T = Text(frame, height=50, width=80) results.pack(side=RIGHT, fill=Y) T.pack(side=RIGHT, fill=Y) results.config(command=T.yview) T.config(yscrollcommand=results.set) T.insert(END, mylist) exitb = Button(frame, text="close", command=frame.destroy).pack() frame.pack() except: #results['T'] = 'There was a problem retrieving that information' T.insert(END, 'There was a problem retrieving that information') def insert(): a = int(entry1.get()) b = entry2.get() c = str(date_func(ent)) d = combo.get() col.insert_one({"id": a, "name": b, "date": c, "presence": d}) #results.config(text="record inserted successfully") messagebox.showinfo("INSERTION", "Record Successfully Inserted") #root.geometry("650x650") #root.title("Manual Attendance") #root.configure(background="white") global label1 global label2 global label3 global entry1 global entry2 global button1 global button2 global button3 global button4 global button5 global button6 global ent global combo global button7 label1 = Label(root, text="EmployeeID", font=("arialblack", 15, 'italic')) label1.place(x=20, y=20) entry1 = Entry(root, font=('arial', 12)) entry1.place(x=170, y=20) label2 = Label(root, text="EmployeeName", font=("arialblack", 15, 'italic')) label2.place(x=20, y=70) entry2 = Entry(root, font=('arial', 12)) entry2.place(x=170, y=70) label3 = Label(root, text="Attendance", font=("arialblack", 15, 'italic')) label3.place(x=20, y=120) button1 = Button(root, text="update", width=20, height=2, command=manual_update) button1.place(x=20, y=350) button2 = Button(root, text="Exit", command=root.destroy, width=20, height=2) button2.place(x=20, y=400) button3 = Button(root, text="Clear", command=clear, width=20, height=2) button3.place(x=20, y=450) button4 = Button(root, text="Insert", command=insert, width=20, height=2) button4.place(x=20, y=500) v = ['Present', 'Absent', 'Leave', 'Half Day'] combo = Combobox(root, values=v, font=("arial", 11, 'italic')) combo.place(x=170, y=120) button5 = Button(root, text="Show Database", command=show, width=15, height=2) button5.place(x=20, y=270) ent = DateEntry(root, width=15, height=2, bg="blue", fg="red", borderwidth=2, font=("aialblack", 11, 'bold')) ent.place(x=170, y=210) button6 = Button(root, text="Click Date", command=date_func(ent), width=15, height=2, font=("arialblack", 10, 'bold')) button6.place(x=20, y=200) button7 = Button(root, text="Back", width=10, fg="black", bg="orange", height=1, font=('times', 15, ' bold '), command=remove_widgets_manual) button7.place(x=1150, y=10)
class GUI(Tk): def __init__(self): super().__init__() self.segments = None self.wm_title(__doc__) self.menubar = Menu(self) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label='Open EDI', command=self.open_edi) self.filemenu.add_command(label='Open XML', command=self.open_xml) self.menubar.add_cascade(label="File", menu=self.filemenu) self.config(menu=self.menubar) self.lbl_message = Label(self, text='Message') self.lbl_message.grid(row=0, column=0) self.cb_message = Combobox(self, values=list(MD)) self.cb_message.bind('<<ComboboxSelected>>', self.select_message) self.cb_message.grid(row=1, column=0) self.lbl_segment = Label(self, text='Segment') self.lbl_segment.grid(row=0, column=1) self.cb_segment = Combobox(self, values=list(SD)) self.cb_segment.bind('<<ComboboxSelected>>', self.select_segment) self.cb_segment.grid(row=1, column=1) self.lbl_code = Label(self, text='Code') self.lbl_code.grid(row=0, column=2) self.cb_code = Combobox(self, values=list(ED)) self.cb_code.bind('<<ComboboxSelected>>', self.select_code) self.cb_code.grid(row=1, column=2) self.lbl_formats = Label(self, text='Formats') self.lbl_formats.grid(row=0, column=3, sticky=W) self.formats = Frame(self) self.formats.grid(row=1, column=3) self.var_edi = IntVar() self.chk_edi = Checkbutton(self.formats, text='EDI', variable=self.var_edi, command=self.switch_edi) self.chk_edi.pack(side=LEFT) self.var_segments = IntVar() self.chk_segments = Checkbutton(self.formats, text='Segments', variable=self.var_segments, command=self.switch_segments) self.chk_segments.pack(side=LEFT) self.var_xml = IntVar() self.chk_xml = Checkbutton(self.formats, text='XML', variable=self.var_xml, command=self.switch_xml) self.chk_xml.pack(side=LEFT) self.var_report = IntVar() self.chk_report = Checkbutton(self.formats, text='Report', variable=self.var_report, command=self.switch_report) self.chk_report.pack(side=LEFT) self.editor_message = Editor(self) self.editor_segment = Editor(self) self.editor_code = Editor(self) self.editor_edi = Editor(self) self.editor_edi.sc_text.bind('<KeyRelease>', self.edit_edifact) self.editor_edi.title('EDI') self.editor_segments = Editor(self) self.editor_segments.sc_text.bind('<KeyRelease>', self.edit_segments) self.editor_segments.title('Segments') self.editor_xml = Editor(self) self.editor_xml.sc_text.bind('<KeyRelease>', self.edit_xml) self.editor_xml.title('XML') self.editor_report = Editor(self) self.editor_report.title('Report') self.mainloop() def switch_edi(self, event=None): if self.var_edi.get(): self.editor_edi.deiconify() else: self.editor_edi.withdraw() def switch_segments(self, event=None): if self.var_segments.get(): self.editor_segments.deiconify() else: self.editor_segments.withdraw() def switch_xml(self, event=None): if self.var_xml.get(): self.editor_xml.deiconify() else: self.editor_xml.withdraw() def switch_report(self, event=None): if self.var_report.get(): self.editor_report.deiconify() else: self.editor_report.withdraw() def select_message(self, event=None): msg = self.cb_message.get() self.editor_message.deiconify() if msg in ED['0065']['table']: self.editor_message.title(ED['0065']['table'][msg]['name']) else: self.editor_message.title(f'MISSING {msg}') self.editor_message.text = MD[msg]['description'] def select_segment(self, event=None): seg = self.cb_segment.get() self.editor_segment.deiconify() self.editor_segment.title(f'{SD[seg]["name"]}') self.editor_segment.text = pprint.pformat(SD[seg]['table'], width=200) def select_code(self, event=None): code = self.cb_code.get() self.editor_code.deiconify() self.editor_code.title(f'{ED[code]["name"]}') if 'table' in ED[code]: self.editor_code.text = pprint.pformat(ED[code]['table']) else: self.editor_code.text = '' def report(self): self.editor_report.text = report(self.segments, SD, ED) def edit_xml(self, event=None): try: self.segments = parse_xml( ElementTree.fromstring(self.editor_xml.text)) except Exception as err: showerror('Edit XML Error', err) return self.editor_edi.text = make_edi(self.segments, with_newline=True).decode('utf8') self.editor_segments.text = pprint.pformat(self.segments) self.report() def edit_segments(self, event=None): try: self.segments = literal_eval(self.editor_segments.text) except Exception as err: showerror('Edit Segments Error', err) return self.editor_edi.text = make_edi(self.segments, with_newline=True).decode('utf8') self.editor_xml.text = pretty_xml(make_edi_xml(self.segments, SD, ED)) self.report() def edit_edifact(self, event=None): try: self.segments = parse_edi(self.editor_edi.text.encode('utf8')) except Exception as err: showerror('Edit EDI Error', err) return self.editor_segments.text = pprint.pformat(self.segments) self.editor_xml.text = pretty_xml(make_edi_xml(self.segments, SD, ED)) self.report() def reload(self): if self.var_segments.get(): self.editor_segments.deiconify() if self.var_edi.get(): self.editor_edi.deiconify() if self.var_xml.get(): self.editor_xml.deiconify() if self.var_report.get(): self.editor_report.deiconify() message = [ element[1][0] for segment, element in self.segments if segment == 'UNH' ] if self.segments else None if message: self.cb_message.set(message) self.select_message() self.editor_edi.text = make_edi(self.segments, with_newline=True).decode('utf8') self.editor_segments.text = pprint.pformat(self.segments) self.editor_xml.text = pretty_xml(make_edi_xml(self.segments, SD, ED)) def open_edi(self): file = askopenfilename(title='Open EDI') if not file: return try: self.segments = parse_edi(open(file, 'rb').read()) except Exception as err: showerror('Open EDI Failed', err) return self.wm_title(file) self.reload() self.report() self.var_edi.set(True) self.switch_edi() def open_xml(self): file = askopenfilename(title='Open XML') if not file: return try: self.segments = parse_xml(ElementTree.parse(file).getroot()) except Exception as err: showerror('Open XML Failed', err) self.wm_title(file) self.reload() self.report() self.var_xml.set(True) self.switch_xml()
for txt in textUser[ 'users']: #создали цикл, который будет работать построчно inputValue = txt['name'], # print(inputValue) nameTitle = Label(tab1, text='ФИО пациента:', background="#eee", justify=LEFT, font=("Arial Bold", 10), padx=10, pady=5) nameTitle.grid(sticky=W, column=0, row=0) # выпадающий список начало combo = Combobox(tab1, font=("Arial", 10), width=36, state="readonly") combo['values'] = inputValue combo.current(0) # установите вариант по умолчанию combo.grid(column=0, row=1, padx=10, pady=0) # выпадающий список конец idTitle = Label(tab1, text='Индивидуальный номер:', background="#eee", font=("Arial Bold", 10), padx=10, pady=5) idTitle.grid(sticky=W, column=0, row=2) idImg = Label(tab1, text='img', background="#eee") idImg.grid(column=1, row=2)
window.title("Добро пожаловать в приложение PythonRu") window.geometry('400x250') # Название lbl1 = Label(window, text="Название события:", padx=10) lbl1.place(x=0, y=0, width=140) txt = Entry(window) txt.place(x=140, y=0, width=100) # Выбор дня lbl2 = Label( window, text="Выбери день:", ) lbl2.place(x=0, y=25, width=140) combo = Combobox(window) combo['values'] = ('пн', 'вт', 'ср', 'чт', 'пт', "сб", 'вс') combo.current(0) combo.place(x=140, y=25, width=100) # Выбор времени lbl3 = Label(window, text="Выбери время:") lbl3.place(x=0, y=50, width=140) time1 = Entry(window) time1.place(x=140, y=52, width=27, height=20) time2 = Entry(window) time2.place(x=170, y=52, width=27, height=20) # Чекбокс на запись в файл chk_state = BooleanVar()
class DatabaseJoinDialog(TkSimpleDialog.TkSimpleDialog): """ Dialog box to choose a food name and family """ def __init__(self, parent, configApp, databaseManager, dbNameMaster, title=None): self.configApp = configApp self.databaseManager = databaseManager self.dbNameMaster = dbNameMaster self.dbName = "" self.delaymsTooltips = int( self.configApp.get('Limits', 'delaymsTooltips')) super(DatabaseJoinDialog, self).__init__(parent, title) self.dbNameResult = "" self.isUpdate = False def body(self, master): """ Body content of this dialog """ tkinter.Label(master, text=_("Please choose secondary database") + " :").pack(side=tkinter.TOP) listOtherDatabase = [ databaseName for databaseName in self.databaseManager.getListDatabaseInDir() if databaseName != self.dbNameMaster ] self.secondaryDatabaseCombobox = Combobox(master, exportselection=0, state="readonly", values=listOtherDatabase) self.secondaryDatabaseCombobox.current(0) self.secondaryDatabaseCombobox.pack(side=tkinter.TOP) tkinter.Label(master, text=_("Enter a result database name") + " :").pack(side=tkinter.TOP) self.dbNameResultVar = tkinter.StringVar() dbNameEntry = tkinter.Entry(master, textvariable=self.dbNameResultVar) dbNameEntry.pack(side=tkinter.TOP) # V0.45 : Add or update radio buttons frame operationTypeFrame = tkinter.Frame(master) operationTypeFrame.pack(side=tkinter.TOP) self.operationTypeVar = tkinter.StringVar() tkinter.Radiobutton(operationTypeFrame, text=_("Add only"), variable=self.operationTypeVar, value="Add").pack(side=tkinter.LEFT) tkinter.Radiobutton(operationTypeFrame, text=_("Update and add"), variable=self.operationTypeVar, value="Update").pack(side=tkinter.LEFT) self.operationTypeVar.set("Add") dbNameEntry.focus_set() return dbNameEntry # initial focus def validate(self): """ Check Data entered by user if OK return True """ isOK = False try: self.dbNameResult = self.dbNameResultVar.get().lower().strip() if self.dbNameResult == "": raise ValueError(_("Please give a name for your new database")) if not self.dbNameResult.isalnum(): raise ValueError(_("Invalid database name")) # Check if database exists if self.databaseManager.existsDatabase(self.dbNameResult): raise ValueError( _("this database already exists") + " : " + self.dbNameResult) self.isUpdate = self.operationTypeVar.get() == "Update" isOK = True except ValueError as exc: self.bell() messagebox.showwarning(_("Bad input"), message=_("Error") + " : " + str(exc) + " !") return isOK def apply(self): self.setResult([ self.secondaryDatabaseCombobox.get(), self.dbNameResult, self.isUpdate ])
def initUI(self, parent): self.frame1 = LabelFrame(self, text="HASTA BİLGİLERİ", fg="black", font="serif 15 bold") self.frame1.grid(row=0, column=0, padx=20, pady=20) self.bir = StringVar() self.tcno = Label(self.frame1, text="T.C. Kimlik No", fg="black", font="serif 10 bold") self.tcno.grid(row=0, column=0, padx=20, pady=20, sticky="W") self.tcnoo = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.bir) self.tcnoo.grid(row=0, column=1, padx=20) self.tcnooo = Button(self.frame1, text="BUL", bg="green", fg="black", font="serif 10 bold", command=self.hastabilgi) self.tcnooo.grid(row=0, column=2, padx=(0,20), pady=20, sticky="W") self.iki = StringVar() self.hastaad = Label(self.frame1, text="Ad - Soyad", fg="black", font="serif 10 bold") self.hastaad.grid(row=1, column=0, padx=20, sticky="W") self.hastaadd = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.iki) self.hastaadd.grid(row=1, column=1) self.uc = StringVar() self.hastayas = Label(self.frame1, text="Yaş", fg="black", font="serif 10 bold") self.hastayas.grid(row=2, column=0, pady=20, padx=20, sticky="W") self.hastayass = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.uc) self.hastayass.grid(row=2, column=1) self.cinsiyet = IntVar() self.cinsiyet.set(1) self.hastacinsiyet = Label(self.frame1, text="Cinsiyet", fg="black", font="serif 10 bold") self.hastacinsiyet.grid(row=3, column=0, padx=20, sticky="W") self.hastacinsiyeterkek = Radiobutton(self.frame1, text="Erkek", font="serif 10 bold", variable=self.cinsiyet, value=1) self.hastacinsiyeterkek.place(x=200, y=150) self.hastacinsiyetkadın = Radiobutton(self.frame1, text="Kadın", font="serif 10 bold", variable=self.cinsiyet, value=2) self.hastacinsiyetkadın.place(x=300, y=150) self.dort = StringVar() self.hastaadres = Label(self.frame1, text="Adres", fg="black", font="serif 10 bold") self.hastaadres.grid(row=4, column=0, pady=20, padx=20, sticky="W") self.hastaadress = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.dort) self.hastaadress.grid(row=4, column=1) self.hizmet = StringVar() self.yapilanhizmet = Label(self.frame1, text="Yapılan Hizmet", fg="black", font="serif 10 bold") self.yapilanhizmet.grid(row=5, column=0, padx=20, sticky="W") self.yapilanhizmett = Combobox(self.frame1, width=27, textvariable=self.hizmet, font="serif 10 bold", justify="center") self.yapilanhizmett['values'] = ( "Acil Yardım Uygulamaları", "Ambulans Hizmeti", "Apse Boşaltma", "Diğer", "Dikiş (Sütur) Atma", "Enjeksiyon", "Evde Hasta Bakım Hizmetleri", "Hemoglobin Ölçümü", "Kulak Yıkama", "Nasır Alma", "Pansuman ve Küçük Cerrahi Müdahale", "Serum Takma ve Takibi", "Sonda Takma", "Tırnak Çekme" "Tansiyon Takibi", "Yanık Bakımı", "Yatak Yarası Bakımı", ) self.yapilanhizmett.grid(row=5, column=1) self.bes = StringVar() self.tarih = Label(self.frame1, text="Tarih (gg.aa.yyyy)", fg="black", font="serif 10 bold") self.tarih.grid(row=6, column=0, pady=20, padx=20, sticky="W") self.tarihh = Entry(self.frame1, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.bes) self.tarihh.grid(row=6, column=1) self.frame2 = LabelFrame(self, text="FİYATLANDIRMA", fg="black", font="serif 15 bold") self.frame2.grid(row=0, column=1) self.alti = StringVar() self.kullanilanmalzeme = Label(self.frame2, text="Kullanılan Malzeme", fg="black", font="serif 10 bold") self.kullanilanmalzeme.grid(row=0, column=0, padx=20, pady=20, sticky="W") self.kullanilanmalzemee = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.alti) self.kullanilanmalzemee.grid(row=0, column=1, padx=20) self.yedi = StringVar() self.yedi.set(0) self.malzemeadet = Label(self.frame2, text="Kullanılan Malzeme Adeti", fg="black", font="serif 10 bold") self.malzemeadet.grid(row=1, column=0, padx=20, sticky="W") self.malzemeadett = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.yedi) self.malzemeadett.grid(row=1, column=1) self.sekiz = StringVar() self.sekiz.set(0) self.malzemefiyat = Label(self.frame2, text="Kullanılan Malzeme Birim Fiyatı", fg="black", font="serif 10 bold") self.malzemefiyat.grid(row=2, column=0, pady=20, padx=20, sticky="W") self.malzemefiyatt = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.sekiz) self.malzemefiyatt.grid(row=2, column=1) self.dokuz = StringVar() self.dokuz.set(0) self.alinanucret = Label(self.frame2, text="Hastadan Alınan Ücret", fg="black", font="serif 10 bold") self.alinanucret.grid(row=3, column=0, padx=20, sticky="W") self.alinanucrett = Entry(self.frame2, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.dokuz) self.alinanucrett.grid(row=3, column=1) self.maliyetmalzeme = IntVar() self.maliyetmalzeme.set(0) self.malzememaliyet = Label(self.frame2, text="Kullanılan Malzeme Maliyeti", fg="black", font="serif 10 bold") self.malzememaliyet.grid(row=4, column=0, pady=20, padx=20, sticky="W") self.malzememaliyett = Entry(self.frame2, text="", width=30, font="serif 10 bold", state="disabled", textvariable=self.maliyetmalzeme, justify="center") self.malzememaliyett.grid(row=4, column=1) self.frame3 = LabelFrame(self, text="ÖZET", fg="black", font="serif 15 bold") self.frame3.grid(row=0, column=3, padx=20) self.on = StringVar() self.hemsireadi = Label(self.frame3, text="Hemşire Adı", fg="black", font="serif 10 bold") self.hemsireadi.grid(row=0, column=0, padx=20, pady=20, sticky="W") self.hemsireadi = Entry(self.frame3, text="", width=30, font="serif 10 bold", justify="center", textvariable=self.on) self.hemsireadi.grid(row=0, column=1, padx=20) self.kaydetbuton = Button(self.frame3, text="KAYDET", bg="green", fg="black", width=25, font="serif 10 bold", command=self.kaydet) self.kaydetbuton.grid(row=2, column=0, padx=20) self.temizlebuton = Button(self.frame3, text="TEMİZLE", bg="red", fg="black", width=25, font="serif 10 bold", command=self.temizle) self.temizlebuton.grid(row=2, column=1) self.mesajkutusu1 = StringVar() self.mesaj1 = Entry(self.frame3, text="", width=60, font="serif 10 bold", state="disabled", textvariable=self.mesajkutusu1, justify="center") self.mesaj1.grid(row=3, column=0, columnspan=2, padx=20, pady=20) self.mesaj2 = Label(self.frame3, text="") self.mesaj2.grid(row=4, column=0, columnspan=2, padx=20, pady=(0,20)) self.grid() pass
camera_radiobutton.bind_all('<KeyPress-2>',source_select) video_radiobutton.bind_all('<KeyPress-3>',source_select) picture_radiobutton.place(x = 100,y = 400,anchor = "nw") camera_radiobutton.place(x = 200,y = 400,anchor = "nw") video_radiobutton.place(x = 300,y = 400,anchor = "nw") def openLabelFile(event): print(label_select.get()) global StringVar StringVar = label_select.get() labelwork(StringVar) global fileOpen fileOpen = open(label_file[StringVar],'a') label_var = tk.StringVar() label_select = Combobox(window,textvariable = label_var) label_select["value"] = ("真实人脸","姓名","身份证号","性别","年龄","民族","种族","口罩","帽子","眼镜","遮挡","光照","倾斜","伤痕","电话","受伤","饰品","人脸大小","模糊度","面部表情","人脸出处") label_select["state"] = "readonly" label_select.place(x = 110,y = 340,anchor = "nw") label_select.bind('<<ComboboxSelected>>',openLabelFile) def delete_img(event): print("delete image") global finish_flag if finish_flag: showinfo("Info","No Unlabeled Images") else: os.remove(image_file_path) if -1 == load_img():
def setup_main_window(self, window) -> None: self.sh_window: Tk = window self.sh_window.title('Option chain analyzer') window_width: int = self.sh_window.winfo_reqwidth() window_height: int = self.sh_window.winfo_reqheight() position_right: int = int(self.sh_window.winfo_screenwidth() / 2 - window_width / 2) position_down: int = int(self.sh_window.winfo_screenheight() / 2 - window_height / 2) #self.sh_window.geometry("1200x600+{}+{}".format(position_right, position_down)) self.sh_window.geometry("1200x600+300+200") #self.sh_window.geometry("+{}+{}".format(position_right, position_down)) self.sh_frame: Frame = Frame(self.sh_window) self.stock_frame: Frame = Frame(self.sh_window) top_frame: Frame = Frame(self.sh_window) top_frame.rowconfigure(0, weight=1) top_frame.columnconfigure(0, weight=1) top_frame.pack(anchor=S, expand=False, side=TOP) row_idx: int = 0 self.index_call = True self.get_expiry_dates() date_var: StringVar = StringVar() date_var.set(" ") lbl_exp_date: Label = Label(top_frame, text='Index Expiry', justify=LEFT, font=("TkDefaultFont", 10, "bold")) #lbl_exp_date.grid(row=row_idx,column=0,sticky=N+S+W) lbl_exp_date.pack(anchor=N, expand=False, side=LEFT) self.date_combo_box = Combobox(top_frame, width=10, textvariable=date_var) self.date_combo_box.pack(anchor=N, expand=False, side=LEFT) #self.date_combo_box.grid(row=row_idx, column=1, sticky=N + S + E + W) self.date_combo_box.bind('<<ComboboxSelected>>', self.set_expiry_date) self.date_combo_box['values'] = tuple(self.expiry_dates) self.date_combo_box.set(self.expiry_dates[0]) self.date_combo_box.configure(state='readonly') row_idx += 1 self.index_call = False self.get_expiry_dates() date_var_stock: StringVar = StringVar() date_var_stock.set(" ") lbl_exp_date_stock: Label = Label(top_frame, text='Stock Expiry', justify=LEFT, font=("TkDefaultFont", 10, "bold")) #lbl_exp_date_stock.grid(row=row_idx,column=0,sticky=N+S+W) lbl_exp_date_stock.pack(anchor=N, expand=False, side=LEFT) self.date_combo_box_stock = Combobox(top_frame, width=10, textvariable=date_var_stock) self.date_combo_box_stock.pack(anchor=N, expand=False, side=LEFT) #self.date_combo_box_stock.grid(row=row_idx, column=1, sticky=N + S + E + W) self.date_combo_box_stock.bind('<<ComboboxSelected>>', self.set_expiry_date) self.date_combo_box_stock['values'] = tuple(self.expiry_dates) self.date_combo_box_stock.set(self.expiry_dates[0]) self.date_combo_box_stock.configure(state='readonly') row_idx += 1 self.check_stocks_var = IntVar() self.check_stocks = Checkbutton(top_frame, text = "Stocks", variable = self.check_stocks_var, \ onvalue = 1, offvalue = 0, width = 10) #self.check_stocks.grid(row=row_idx, column=1, sticky=N + S + E + W) self.check_stocks.pack(anchor=N, expand=False, side=LEFT) self.check_stocks_var.set(0) row_idx += 1 self.check_index_var = IntVar() self.check_index = Checkbutton(top_frame, text = "Index", variable = self.check_index_var, \ onvalue = 1, offvalue = 0, width = 10) #self.check_index.grid(row=row_idx, column=1, sticky=N + S + E + W) self.check_index.pack(anchor=N, expand=False, side=LEFT) self.check_index_var.set(1) row_idx += 1 ref_intvl: Stringvar = StringVar() ref_intvl.set(" ") lbl_refresh_interval: Label = Label(top_frame, text='Interval (min)', justify=LEFT, font=("TkDefaultFont", 10, "bold")) #lbl_refresh_interval.grid(row=row_idx,column=0,sticky=N+S+W) lbl_refresh_interval.pack(anchor=N, expand=False, side=LEFT) self.ref_intvl_cbox: Combobox = Combobox(top_frame, width=10, textvariable=ref_intvl) #self.ref_intvl_cbox.grid(row=row_idx, column=1, sticky=N + S + E + W) self.ref_intvl_cbox.pack(anchor=N, expand=False, side=LEFT) self.ref_intvl_cbox.bind('<<ComboboxSelected>>', self.set_ref_intvl) self.ref_intvl_cbox['values'] = tuple(range(10, 600, 20)) self.ref_intvl_cbox.configure(state='readonly') row_idx += 1 self.start_button: Button = Button(top_frame, text='START', command=self.main_recursive, width=10) #self.start_button.grid(row=row_idx, column=1, sticky=N + S + E + W) self.start_button.pack(anchor=N, expand=True, side=TOP) row_idx += 1 canvas = tk.Canvas(self.sh_window) scroll_y = tk.Scrollbar(self.sh_window, orient="vertical", command=canvas.yview) bot_frame: Frame = Frame(canvas) #bot_frame = ScrollFrame(bot_frame) #bot_frame.rowconfigure(0, weight=1) #bot_frame.columnconfigure(0, weight=1) #bot_frame.grid(row=row_idx,column=0,sticky=N+S+W) #bot_frame = ScrollableFrame(self.sh_window) #bot_frame = ScrollFrame(self.sh_window) #bot_frame.rowconfigure(1, weight=1) #bot_frame.columnconfigure(0, weight=1) #bot_frame.pack(anchor=N, expand=False, side=LEFT) #bot_frame: Listbox = Listbox(self.sh_window) #bot_frame.pack(side=LEFT,fill='both') #vscrollbar = Scrollbar(self.sh_window) #vscrollbar.pack(side = LEFT, fill = 'both') #for i in range(10000): # bot_frame.insert(END,i) self.stock_check_var: List[IntVar] = [] self.stock_check: List[Checkbutton] = [] int_col = 0 tmp_row_idx = row_idx for stk in enumerate(self.stock_symbs): #if(int(stk[0])>30 and int_col==0): # int_col = 1 # row_idx = tmp_row_idx self.stock_check_var.append(IntVar()) cb = Checkbutton(bot_frame, text = stk[1], variable = self.stock_check_var[-1], \ onvalue = 1, offvalue = 0, width =12) cb.pack() if (stk[1] in self.popular_stocks): self.stock_check_var[-1].set(1) else: self.stock_check_var[-1].set(0) self.stock_check.append(cb) row_idx += 1 canvas.create_window(0, 0, anchor='nw', window=bot_frame) canvas.update_idletasks() canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scroll_y.set) canvas.pack(fill='y', expand=False, side=LEFT) scroll_y.pack(fill='y', side=LEFT, expand=False) self.sh_window.mainloop()
def labelwork(StringVar): if StringVar == "真实人脸": isTureFace_label = tk.Label(window,text = "Human") isTureFace_label.place(x = 40,y = 400,anchor = "nw") trueFace_var = tk.IntVar() #def Trueface_select(): # global _write1 # print(trueFace_var.get()) # _write1 = str(trueFace_var.get()) def trueFace_select(event): global _write1 print(trueFace_var.get() + int(event.char) - 1) _write1 = str(trueFace_var.get() + int(event.char) - 1) trueFace_radiobutton = tk.Radiobutton(window,text = "true face",variable = trueFace_var,value = 1) falseFace_radiobutton = tk.Radiobutton(window,text = "false face",variable = trueFace_var,value = 1) otherTypeFace_radiobutton = tk.Radiobutton(window,text = "other type face",variable = trueFace_var,value = 1) noFace_radiobutton = tk.Radiobutton(window,text = "no face",variable = trueFace_var,value = 1) trueFace_radiobutton.bind_all('<KeyPress-1>',trueFace_select) falseFace_radiobutton.bind_all('<KeyPress-2>',trueFace_select) otherTypeFace_radiobutton.bind_all('<KeyPress-3>',trueFace_select) noFace_radiobutton.bind_all('<KeyPress-4>',trueFace_select) trueFace_radiobutton.place(x = 100,y = 400,anchor = "nw") falseFace_radiobutton.place(x = 200,y = 400,anchor = "nw") otherTypeFace_radiobutton.place(x = 300,y= 400,anchor = "nw") noFace_radiobutton.place(x = 400,y = 400,anchor = "nw") elif StringVar == "姓名": name_label = tk.Label(window,text = "Name") name_label.place(x = 40,y = 400,anchor = "nw") nameEntry = tk.Entry(window,width=50) nameEntry.place(x=100,y=400,anchor="nw") def name_entry(event): global _write1 print(nameEntry.get()) _write1 = str(nameEntry.get()) #submit_name_button = tk.Button(window,text = "SubmitName") nameEntry.bind_all('<Return>',name_entry) #submit_name_button.place(x = 600,y = 400,anchor = "nw") elif StringVar == "身份证号": #身份证号 idNumber_label = tk.Label(window,text = "ID") idNumber_label.place(x = 40,y = 400,anchor = "nw") idNumberEntry = tk.Entry(window,width = 50) idNumberEntry.place(x = 100,y = 400,anchor = "nw") def id_entry(): global _write1 print(idNumberEntry.get()) _write = str(idNumberEntry.get()) #submit_idNumber_button = tk.Button(window,text = "SubmitID",command = id_entry) #submit_idNumber_button.place(x = 600,y = 400,anchor = "nw") idNumberEntry.bind_all('<Return>',id_entry) elif StringVar == "性别": gender_label = tk.Label(window,text="Gender") gender_label.place(x=40,y=400,anchor="nw") gender_var = tk.IntVar() def gender_select(event): global _write1 print(gender_var.get() + int(event.char) - 1) _write1 = str(gender_var.get() + int(event.char) - 1) male_radiobutton = tk.Radiobutton(window,text="Male",variable=gender_var,value = 1) female_radiobutton = tk.Radiobutton(window,text="Female",variable=gender_var,value = 1) male_radiobutton.bind_all('<KeyPress-1>',gender_select) female_radiobutton.bind_all('<KeyPress-2>',gender_select) male_radiobutton.place(x=100,y=400,anchor="nw") female_radiobutton.place(x=200,y=400,anchor="nw") elif StringVar == "年龄": #年龄 age_label = tk.Label(window,text="Age") age_label.place(x=40,y=400,anchor="nw") age_var = tk.IntVar() def age_select(event): global _write1 print(age_var.get() + int(event.char) - 1) _write1 = str(age_var.get() + int(event.char) - 1) less_fourteen_radiobutton=tk.Radiobutton(window,text="0-14",variable=age_var,value=1) fifteen_twentyfour__radiobutton=tk.Radiobutton(window,text="15-24",variable=age_var,value=1) twentyfive_sixty_radiobutton = tk.Radiobutton(window,text="25-60",variable=age_var,value=1) greater_sixty_radiobutton = tk.Radiobutton(window,text=">60",variable=age_var,value = 1) less_fourteen_radiobutton.bind_all('<KeyPress-1>',age_select) fifteen_twentyfour__radiobutton.bind_all('<KeyPress-2>',age_select) twentyfive_sixty_radiobutton.bind_all('<KeyPress-3>',age_select) greater_sixty_radiobutton.bind_all('<KeyPress-4>',age_select) less_fourteen_radiobutton.place(x=100,y=400,anchor="nw") fifteen_twentyfour__radiobutton.place(x=200,y=400,anchor="nw") twentyfive_sixty_radiobutton.place(x=300,y=400,anchor="nw") greater_sixty_radiobutton.place(x=400,y=400,anchor="nw") elif StringVar == "民族": #民族 nationality_label = tk.Label(window,text = "nationality") nationality_label.place(x = 40,y = 400,anchor = "nw") nationality_var = tk.StringVar() natioanality_select = Combobox(window,textvariable = nationality_var) natioanality_select['value'] = ("汉族","x族","y族") def storeNationality(event): global _write1 print(natioanality_select.get()) _write1 = str(natioanality_select.get()) natioanality_select.bind("<<ComboboxSelected>>",storeNationality) natioanality_select.place(x = 150,y = 400,anchor = "nw") elif StringVar == "种族": #种族 race_label = tk.Label(window,text = "Race") race_label.place(x = 40,y = 400,anchor = "nw") race_var = tk.IntVar() def race_select(event): global _write1 print(race_var.get() + int(event.char) - 1) _write1 = str(race_var.get() + int(event.char) - 1) yellow_radiobutton = tk.Radiobutton(window,text="yellow",variable=race_var,value=1) white_radiobutton = tk.Radiobutton(window,text="white",variable=race_var,value=1) black_radiobutton = tk.Radiobutton(window,text="black",variable=race_var,value=1) brown_radiobutton = tk.Radiobutton(window,text="brown",variable=race_var,value=1) yellow_radiobutton.bind_all('<KeyPress-1>',race_select) white_radiobutton.bind_all('<KeyPress-2>',race_select) black_radiobutton.bind_all('<KeyPress-3>',race_select) brown_radiobutton.bind_all('<KeyPress-4>',race_select) yellow_radiobutton.place(x = 100,y = 400,anchor = "nw") white_radiobutton.place(x = 200,y = 400,anchor = "nw") black_radiobutton.place(x = 300,y = 400,anchor = "nw") brown_radiobutton.place(x = 400,y = 400,anchor = "nw") elif StringVar == "口罩": #是否有面罩 mask_label = tk.Label(window,text="Mask") mask_label.place(x=40,y=400,anchor="nw") mask_var = tk.IntVar() def mask_select(event): global _write1 print(mask_var.get() + int(event.char) - 1) _write1 = str(mask_var.get() + int(event.char) - 1) not_wearing_mask_radiobutton = tk.Radiobutton(window,text="Not Wearing",variable=mask_var,value=1) wearing_mask_radiobutton = tk.Radiobutton(window,text="Wearing",variable=mask_var,value=1) not_wearing_mask_radiobutton.bind_all('<KeyPress-1>',mask_select) wearing_mask_radiobutton.bind_all('<KeyPress-2>',mask_select) not_wearing_mask_radiobutton.place(x=100,y=400,anchor="nw") wearing_mask_radiobutton.place(x=200,y=400,anchor="nw") elif StringVar == "帽子": #是否有帽子 hat_label = tk.Label(window,text="Hat") hat_label.place(x=40,y=400,anchor="nw") hat_var = tk.IntVar() def hat_select(event): global _write1 print(hat_var.get() + int(event.char) - 1) _write1 = str(hat_var.get() + int(event.char) - 1) not_wearing_hat_radiobutton = tk.Radiobutton(window,text="Not Wearing",variable=hat_var,value=1) wearing_hat_radiobutton = tk.Radiobutton(window,text="Wearing",variable=hat_var,value=1) not_wearing_hat_radiobutton.bind_all('<KeyPress-1>',hat_select) wearing_hat_radiobutton.bind_all('<KeyPress-2>',hat_select) not_wearing_hat_radiobutton.place(x=100,y=400,anchor="nw") wearing_hat_radiobutton.place(x=200,y=400,anchor="nw") elif StringVar == "眼镜": #是否有眼镜 glasses_label = tk.Label(window,text="Glasses") glasses_label.place(x=40,y=400,anchor="nw") glasses_var = tk.IntVar() def glasses_select(event): global _write1 print(glasses_var.get() + int(event.char) - 1) _write1 = str(glasses_var.get() + int(event.char) - 1) not_wearing_glasses_radiobutton = tk.Radiobutton(window,text="Not Wearing",variable=glasses_var,value=1) wearing_glasses_radiobutton = tk.Radiobutton(window,text="Wearing",variable=glasses_var,value=1) not_wearing_glasses_radiobutton.bind_all('<KeyPress-1>',glasses_select) wearing_glasses_radiobutton.bind_all('<KeyPress-2>',glasses_select) not_wearing_glasses_radiobutton.place(x=100,y=400,anchor="nw") wearing_glasses_radiobutton.place(x=200,y=400,anchor="nw") elif StringVar == "遮挡": #遮挡 occlusion_label = tk.Label(window,text = "Occlusion") occlusion_label.place(x = 40,y = 400,anchor = "nw") occlusion_var = tk.IntVar() def occlusion_select(event): global _write1 print(occlusion_var.get() + int(event.char) - 1) _write1 = str(occlusion_var.get() + int(event.char) - 1) no_occlusion_radiobutton = tk.Radiobutton(window,text="No occlusion",variable=occlusion_var,value=1) acceptable_radiobutton = tk.Radiobutton(window,text="Acceptable",variable=occlusion_var,value=1) reluctantly_accepted_radiobutton = tk.Radiobutton(window,text="Reluctantly accepted",variable=occlusion_var,value = 1) unuseful_radiobutton = tk.Radiobutton(window,text="Unuseful",variable=occlusion_var,value=1) no_occlusion_radiobutton.bind_all('<KeyPress-1>',occlusion_select) acceptable_radiobutton.bind_all('<KeyPress-2>',occlusion_select) reluctantly_accepted_radiobutton.bind_all('<KeyPress-3>',occlusion_select) unuseful_radiobutton.bind_all('<KeyPress-4>',occlusion_select) no_occlusion_radiobutton.place(x = 100, y = 400,anchor = "nw") acceptable_radiobutton.place(x = 200,y = 400,anchor = "nw") reluctantly_accepted_radiobutton.place(x = 300,y = 400,anchor = "nw") unuseful_radiobutton.place(x = 400,y = 400,anchor = "nw") elif StringVar == "光照": #光照 illumination_label = tk.Label(window,text = "Illumination") illumination_label.place(x = 40,y = 400,anchor = "nw") illumination_var = tk.IntVar() def illumination_select(event): global _write1 print(illumination_var.get() + int(event.char) - 1) _write1 = str(illumination_var.get() + int(event.char) - 1) nomalIllumination_radiobutton = tk.Radiobutton(window,text="Normal",variable=illumination_var,value=1) backlight_radiobutton = tk.Radiobutton(window,text="Backlight",variable=illumination_var,value=1) stronglight_radiobutton = tk.Radiobutton(window,text="Stronglight",variable=illumination_var,value=1) darklight_radiobutton = tk.Radiobutton(window,text="Darklight",variable=illumination_var,value=1) nomalIllumination_radiobutton.bind_all('<KeyPress-1>',illumination_select) backlight_radiobutton.bind_all('<KeyPress-2>',illumination_select) darklight_radiobutton.bind_all('<KeyPress-4>',illumination_select) stronglight_radiobutton.bind_all('<KeyPress-3>',illumination_select) nomalIllumination_radiobutton.place(x = 100,y = 400,anchor = "nw") backlight_radiobutton.place(x = 200,y = 400,anchor = "nw") stronglight_radiobutton.place(x = 300,y = 400,anchor = "nw") darklight_radiobutton.place(x = 400,y = 400,anchor = "nw") elif StringVar == "倾斜": #倾斜 slope_label = tk.Label(window,text = "Slope") slope_label.place(x = 40,y = 400,anchor = "nw") slope_var = tk.IntVar() def slope_select(event): global _write1 print(slope_var.get() + int(event.char) - 1) _write1 = str(slope_var.get() + int(event.char) - 1) normalSlope_radiobutton = tk.Radiobutton(window,text="Normal",variable=slope_var,value=1) leftLeaning_radiobutton = tk.Radiobutton(window,text="Left leaning",variable=slope_var,value=1) rightLeaning_radiobutton = tk.Radiobutton(window,text="Right leaning",variable=slope_var,value=1) rise_radiobutton = tk.Radiobutton(window,text="Rise",variable=slope_var,value=1) bowDown_radiobutton = tk.Radiobutton(window,text="Bow down",variable=slope_var,value=1) normalSlope_radiobutton.bind_all('<KeyPress-1>',slope_select) leftLeaning_radiobutton.bind_all('<KeyPress-2>',slope_select) rightLeaning_radiobutton.bind_all('<KeyPress-3>',slope_select) rise_radiobutton.bind_all('<KeyPress-4>',slope_select) bowDown_radiobutton.bind_all('<KeyPress-5>',slope_select) normalSlope_radiobutton.place(x = 100,y = 400,anchor = "nw") leftLeaning_radiobutton.place(x = 200,y = 400,anchor = "nw") rightLeaning_radiobutton.place(x = 300,y = 400,anchor = "nw") rise_radiobutton.place(x = 400,y = 400,anchor = "nw") bowDown_radiobutton.place(x = 500,y = 400,anchor = "nw") elif StringVar == "伤痕": #伤痕 脸上是否带有肉眼可见伤痕 scar_label = tk.Label(window,text = "Scar 脸上是否带有肉眼可见的伤痕") scar_label.place(x = 40,y = 370,anchor = "nw") scar_var = tk.IntVar() def scar_select(event): global _write1 print(scar_var.get() + int(event.char) - 1) _write1 = str(scar_var.get() + int(event.char) - 1) isScar_radiobutton = tk.Radiobutton(window,text="Yes",variable=scar_var,value=1) isNotScar_radiobutton = tk.Radiobutton(window,text="No",variable=scar_var,value=1) isScar_radiobutton.bind_all('<KeyPress-1>',scar_select) isNotScar_radiobutton.bind_all('<KeyPress-2>',scar_select) isScar_radiobutton.place(x = 100,y = 400,anchor = "nw") isNotScar_radiobutton.place(x = 200,y = 400,anchor = "nw") elif StringVar == "电话": #电话 是否处于当电话状态 phone_label = tk.Label(window,text = "Phone 是否处于打电话状态") phone_label.place(x = 40,y = 370,anchor = "nw") phone_var = tk.IntVar() def phone_select(event): global _write1 print(phone_var.get() + int(event.char) - 1) _write1 = str(phone_var.get() + int(event.char) - 1) isPhone_radiobutton = tk.Radiobutton(window,text="Yes",variable=phone_var,value=1) isNotPhone_radiobutton = tk.Radiobutton(window,text="No",variable=phone_var,value=1) isPhone_radiobutton.bind_all('<KeyPress-1>',phone_select) isNotPhone_radiobutton.bind_all('<KeyPress-2>',phone_select) isPhone_radiobutton.place(x = 100,y = 400,anchor = "nw") isNotPhone_radiobutton.place(x = 200,y = 400,anchor = "nw") elif StringVar == "受伤": #受伤 是否面部带伤,需要包扎绷带的严重伤 injured_label = tk.Label(window,text = "injured 是否面部带伤,需要包扎绷带的严重伤") injured_label.place(x = 40,y = 370,anchor = "nw") injured_var = tk.IntVar() def injured_select(event): global _write1 print(injured_var.get() + int(event.char) - 1) _write1 = str(injured_var.get() + int(event.char) - 1) isInjured_radiobutton = tk.Radiobutton(window,text="Yes",variable=injured_var,value=1) isNotInjured_radiobutton = tk.Radiobutton(window,text="No",variable=injured_var,value=1) isInjured_radiobutton.bind_all('<KeyPress-1>',injured_select) isNotInjured_radiobutton.bind_all('<KeyPress-2>',injured_select) isInjured_radiobutton.place(x = 100,y = 400,anchor = "nw") isNotInjured_radiobutton.place(x = 200,y = 400,anchor = "nw") elif StringVar == "饰品": #饰品 是否有鼻环唇环耳环等装饰物 accessory_label = tk.Label(window,text = "Accessory 是否有鼻环唇环耳环等装饰物") accessory_label.place(x = 40,y = 370,anchor = "nw") accessory_var = tk.IntVar() def accessory_select(event): global _write1 print(accessory_var.get() + int(event.char) - 1) _write1 = str(accessory_var.get() + int(event.char) - 1) isAccessory_radiobutton = tk.Radiobutton(window,text="Yes",variable=accessory_var,value=1) isNotAccessory_radiobutton = tk.Radiobutton(window,text="No",variable=accessory_var,value=1) isAccessory_radiobutton.bind_all('<KeyPress-1>',accessory_select) isNotAccessory_radiobutton.bind_all('<KeyPress-2>',accessory_select) isAccessory_radiobutton.place(x = 100,y = 400,anchor = "nw") isNotAccessory_radiobutton.place(x = 200,y = 400,anchor = "nw") elif StringVar =="人脸大小": #人脸大小 size 50以下的小人脸可用价值不大,一般较为模糊 faceSize_label = tk.Label(window,text = "Face size 50以下的小人脸可用价值不大,一般较为模糊") faceSize_label.place(x = 40,y = 370,anchor = "nw") faceSize_var = tk.IntVar() def faceSize_select(event): global _write1 print(faceSize_var.get() + int(event.char) - 1) _write1 = str(faceSize_var.get() + int(event.char) - 1) greater100_radiobutton = tk.Radiobutton(window,text=">100",variable=faceSize_var,value=1) smaller100greater50_radiobutton = tk.Radiobutton(window,text="<100&&>50",variable=faceSize_var,value=1) smaller50_radiobutton = tk.Radiobutton(window,text="<50",variable=faceSize_var,value=1) greater100_radiobutton.bind_all('<KeyPress-1>',faceSize_select) smaller100greater50_radiobutton.bind_all('<KeyPress-2>',faceSize_select) smaller50_radiobutton.bind_all('<KeyPress-3>',faceSize_select) greater100_radiobutton.place(x = 100,y = 400,anchor = "nw") smaller100greater50_radiobutton.place(x = 200,y = 400,anchor = "nw") smaller50_radiobutton.place(x = 300,y = 400,anchor = "nw") elif StringVar == "模糊度": #模糊度 blur_label = tk.Label(window,text = "Blur") blur_label.place(x = 40,y = 400,anchor = "nw") blur_var = tk.IntVar() def blur_select(event): global _write1 print(blur_var.get() + int(event.char) - 1) _write1 = str(blur_var.get() + int(event.char) - 1) clear_radiobutton = tk.Radiobutton(window,text="Clear",variable=blur_var,value=1) blurLowResolution_radiobutton = tk.Radiobutton(window,text="Blur low resolution",variable=blur_var,value=1) blurOutOfFocus_radiobutton = tk.Radiobutton(window,text="Blur out of focus",variable=blur_var,value=1) blurDistortion_radiobutton = tk.Radiobutton(window,text="Distortion blur",variable=blur_var,value=1) clear_radiobutton.bind_all('<KeyPress-1>',blur_select) blurLowResolution_radiobutton.bind_all('<KeyPress-2>',blur_select) blurOutOfFocus_radiobutton.bind_all('<KeyPress-3>',blur_select) blurDistortion_radiobutton.bind_all('<KeyPress-4>',blur_select) clear_radiobutton.place(x = 100,y = 400,anchor = "nw") blurLowResolution_radiobutton.place(x = 200,y = 400,anchor = "nw") blurOutOfFocus_radiobutton.place(x = 300,y = 400,anchor = "nw") blurDistortion_radiobutton.place(x = 400,y = 400,anchor = "nw") elif StringVar == "面部表情": #面部表情 expression_label = tk.Label(window,text = "Expression") expression_label.place(x = 40,y = 400,anchor = "nw") expression_var = tk.IntVar() def expression_select(event): global _write1 print(expression_var.get() + int(event.char) - 1) _write1 = str(expression_var.get() + int(event.char) - 1) happy_radiobutton = tk.Radiobutton(window,text="Happy",variable=expression_var,value=1) normalExpression_radiobutton = tk.Radiobutton(window,text="Normal",variable=expression_var,value=1) sad_radiobutton = tk.Radiobutton(window,text="Sad",variable=expression_var,value=1) surprise_radiobutton = tk.Radiobutton(window,text="Surprise",variable=expression_var,value=1) happy_radiobutton.bind_all('<KeyPress-1>',expression_select) normalExpression_radiobutton.bind_all('<KeyPress-2>',expression_select) sad_radiobutton.bind_all('<KeyPress-3>',expression_select) surprise_radiobutton.bind_all('<KeyPress-4>',expression_select) happy_radiobutton.place(x = 100,y = 400,anchor = "nw") normalExpression_radiobutton.place(x = 200,y = 400,anchor = "nw") sad_radiobutton.place(x = 300,y = 400,anchor = "nw") surprise_radiobutton.place(x = 400,y = 400,anchor = "nw") elif StringVar == "人脸出处": #人脸出处 source_label = tk.Label(window,text = "Source") source_label.place(x = 40,y = 400,anchor = "nw") source_var = tk.IntVar() def source_select(event): global _write1 print(source_var.get() + int(event.char) - 1) _write1 = str(source_var.get() + int(event.char) - 1) picture_radiobutton = tk.Radiobutton(window,text="Picture",variable=source_var,value=1) camera_radiobutton = tk.Radiobutton(window,text="Camera",variable=source_var,value=1) video_radiobutton = tk.Radiobutton(window,text="Video",variable = source_var,value=1) picture_radiobutton.bind_all('<KeyPress-1>',source_select) camera_radiobutton.bind_all('<KeyPress-2>',source_select) video_radiobutton.bind_all('<KeyPress-3>',source_select) picture_radiobutton.place(x = 100,y = 400,anchor = "nw") camera_radiobutton.place(x = 200,y = 400,anchor = "nw") video_radiobutton.place(x = 300,y = 400,anchor = "nw")
root.title('Intrusion Detection') root.config(background='light blue') label0 = Label(root, text="INTRUSION DETECTION SYSTEM", bg='light blue', font=('Times 23 bold')) label0.pack(side=TOP) label1 = Label(text="Potential Intruders", bg='light blue', font=('helvetica 15 bold')) label1.place(x=10, y=100) classes = ["person", "car", "bird"] combo1 = Combobox(root, values=classes, height=1, width=22) combo1.place(x=18, y=130) label2 = Label(text="Mode of operation", bg='light blue', font=('helvetica 15 bold')) label2.place(x=210, y=100) camera = ["webcam", "usb", "CCTV", "offline video"] combo2 = Combobox(root, values=camera, height=1, width=30) combo2.place(x=215, y=130) menu = Menu(root) root.config(menu=menu)
class PokerBot: def __init__(self): self.root = tk.Tk() self.combo = Combobox(self.root, width=120) self.window_info = get_window_info() self.white = np.array([255, 255, 255]) self.ranks = { '2': cv2.imread('ranks\\2.png', 0), '3': cv2.imread('ranks\\3.png', 0), '4': cv2.imread('ranks\\4.png', 0), '5': cv2.imread('ranks\\5.png', 0), '6': cv2.imread('ranks\\6.png', 0), '7': cv2.imread('ranks\\7.png', 0), '8': cv2.imread('ranks\\8.png', 0), '9': cv2.imread('ranks\\9.png', 0), 'T': cv2.imread('ranks\\T.png', 0), 'J': cv2.imread('ranks\\J.png', 0), 'Q': cv2.imread('ranks\\Q.png', 0), 'K': cv2.imread('ranks\\K.png', 0), 'A': cv2.imread('ranks\\A.png', 0), } self.suits = { 'h': np.array([163, 21, 21]), 's': np.array([0, 142, 80]), 'c': np.array([0, 0, 0]), 'd': np.array([35, 89, 189]), } self.check_stack = [0] def run(self): btn = tk.Button(self.root, text='Ok', command=lambda: self.poker_window()) keys = [] for key in get_window_info(): keys.append(key) self.combo['values'] = keys self.combo.pack(side='left') btn.pack(side='left') self.root.mainloop() def poker_window(self): wind = self.window_info[self.combo.get()] win32gui.MoveWindow(wind, 0, 0, 1280, 720, True) win32gui.SetForegroundWindow(wind) count_screen = 0 fastpoker = FastPoker(wind) while True: rect = win32gui.GetWindowRect(wind) screen = ImageGrab.grab((rect[0], rect[1], rect[2], rect[3])) screen_color = np.array(screen) # преобразование в чб screen_bw = np.array(screen.convert('L')) # серый screen_bw[screen_bw < 128] = 0 # чёрный screen_bw[screen_bw >= 128] = 255 # белый card1_rank_np = screen_bw[442:468, 455:485] card2_rank_np = screen_bw[442:468, 526:556] card1_suit_np = screen_color[454, 490] card2_suit_np = screen_color[454, 562] screen_stack_bw = np.array(screen.convert('L')) screen_stack_bw[screen_stack_bw < 128] = 0 screen_stack_bw[screen_stack_bw >= 128] = 255 # seat0 = screen_stack_bw[392:392 + 20, 15:15 + 130] # seat1 = screen_stack_bw[179:179 + 20, 15:15 + 130] # seat2 = screen_stack_bw[94:94 + 20, 415:415 + 130] # img = screen_stack_bw[527:527+20, 471:471 + 131] # contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) # symbols_hero = [] # for i, contour in enumerate(contours): # x, y, w, h = cv2.boundingRect(contour) # if hierarchy[0][i][3] == -1: # # cv2.rectangle(hero_chip, (x, y), (x + w, y + h), (100, 0, 0), 1) # symbols_hero.append([img[y:y + h, x:x + w], x]) # symbols_hero = sorted(symbols_hero, key=lambda sym: sym[1]) # cv2.imshow("screen", screen_stack_bw) card1_rank = self.get_rank(card1_rank_np) card2_rank = self.get_rank(card2_rank_np) card1_suit = self.get_suit(card1_suit_np) card2_suit = self.get_suit(card2_suit_np) btn_chip = [ screen_color[366, 774, 0], screen_color[207, 751, 0], screen_color[162, 402, 0], screen_color[207, 265, 0], screen_color[366, 246, 0], screen_color[455, 626, 0] ] if card1_rank and card2_rank and 231 in btn_chip: check_info = card1_rank + card2_rank + card1_suit + card2_suit + str( btn_chip.index(231)) if self.check_stack[-1] != check_info: self.check_stack.append(check_info) self.check_stack.pop(-2) hero_cards = [ Card(card1_rank, card1_suit), Card(card2_rank, card2_suit) ] fastpoker.hands.append({ 'hero cards': hero_cards, 'btn chip': int(btn_chip.index(231)) }) fastpoker.run_hand() if cv2.waitKey(1) == ord('w'): count_screen += 1 # h1 = str(count_screen) + '1.png' # h2 = str(count_screen) + '2.png' scr = str(count_screen) + 'screen.png' cv2.imwrite(scr, screen_stack_bw) cv2.imwrite(str(count_screen) + '0.png', seat0) cv2.imwrite(str(count_screen) + '1.png', seat1) cv2.imwrite(str(count_screen) + '2.png', seat1) # for i in range(0, len(symbols_hero)): # cv2.imwrite(str(i) + '.png', symbols_hero[i][0]) # cv2.imwrite(scr, hero_chip) # print(h1) # print(h2) def get_rank(self, card): """ получение карты из масссива :param card: массив numpy :return: string rank """ card_ranks = [rank for rank in self.ranks] accuracy = [ np.sum(value == card) / card.size for key, value in self.ranks.items() ] if max(accuracy) > 0.9: rank = card_ranks[accuracy.index(max(accuracy))] return rank def get_suit(self, card): """ получение масти из точки на экране :param card: [R G B] :return: string suit """ for suit, items in self.suits.items(): if np.all(card == items): return suit
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 addStudent(): global row global row2 book = xl.load_workbook( os.path.join("Database", "Students", "Attendence.xlsx")) sheet = book["January"] row = 1 while (True): if (sheet['A{0}'.format(row)].value == None): break row += 1 book2 = xl.load_workbook( os.path.join("Database", "teachers_and_students.xlsx")) sheet2 = book2.active row2 = 1 while (True): if (sheet2['A{0}'.format(row2)].value == None): break row2 += 1 global root_label global unique_ids_list f = open(unique_ids, "r") unique_ids_list = f.read().split() f.close() root = Toplevel() root.focus_set() root.title("Add Student") root.geometry("400x300+500+50") F0 = Frame(root) F0.pack() F5 = Frame(root) F5.pack() F1 = Frame(root) F1.pack() F2 = Frame(root) F2.pack() F3 = Frame(root) F3.pack() F4 = Frame(root) F4.pack(pady=5) classes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] root_label = Label(F0, text="Photo") root_label.pack(pady=5) Label(F5, text="AdmisionNo", width=15, height=2, font=('', 15)).pack(side="left", anchor=W, expand=YES, fill=BOTH, pady=1) E4 = Entry(F5, width=30) E4.pack(side="left", anchor=W, expand=YES, fill=X, pady=1) Label(F1, text="Name ", width=15, height=2, font=('', 15)).pack(side="left", anchor=W, expand=YES, fill=BOTH, pady=1) E1 = Entry(F1, width=30) E1.pack(side="left", anchor=W, expand=YES, fill=X, pady=1) Label(F2, text="Class ", width=15, height=2, font=('', 15)).pack(side="left", anchor=W, expand=YES, fill=BOTH, pady=1) E2 = Combobox(F2, values=classes, width=27) E2.pack(side="left", anchor=W, expand=YES, fill=X, pady=1) Label(F3, text="RollNo ", width=15, height=2, font=('', 15)).pack(side="left", anchor=W, expand=YES, fill=BOTH, pady=1) E3 = Entry(F3, width=30) E3.pack(side="left", anchor=W, expand=YES, fill=X, pady=1) def submit(): global list_images global student_image global row global row2 student_admno = E4.get() student_name = E1.get() student_class = E2.get() student_rollno = E3.get() if ((student_admno == '') or (not student_admno.isdigit()) or (student_name == '') or (student_class not in classes) or (len(student_rollno) < 1) or (len(student_rollno) > 2) or (len(list_images) != 50) or (not student_rollno.isdigit())): showerror("Error Submit", "Something is wrong in your inputs..!!!") root.focus_set() elif (student_admno in unique_ids_list): showerror("Error Submit", "A student in this admission number already exists") root.focus_set() elif (askyesno( "Confirm Submit", "Hope you have entered right datas.\nAre you sure to submit ?") ): global root_label root.lift() root_label.destroy() root_label = Label(F0, text="Photo") root_label.pack(pady=5) root.geometry("400x300+500+50") E1.delete(0, END) E2.delete(0, END) E3.delete(0, END) E4.delete(0, END) f = open(unique_ids, "a") f.write(student_admno + '\n') f.close() for sheet in book.worksheets: sheet['A{0}'.format(row)] = student_admno sheet['B{0}'.format(row)] = student_name book.save(os.path.join("Database", "Students", "Attendence.xlsx")) row += 1 sheet2['A{0}'.format(row2)].value = student_admno sheet2['B{0}'.format(row2)].value = student_name sheet2['C{0}'.format(row2)] = "Students" book2.save(os.path.join("Database", "teachers_and_students.xlsx")) row2 += 1 cv2.imwrite( os.path.join("Database", "Students", "Images", student_class, student_rollno + ".jpg"), student_image) trainer.train(list_images, int(student_admno)) else: root.focus_set() def setimage(image): global student_image student_image = cv2.flip(image, 1) cv2image = cv2.cvtColor(student_image, cv2.COLOR_BGR2RGBA) img2 = Image.fromarray(cv2image) img2 = img2.resize((300, 350), Image.ANTIALIAS) img2 = ImageTk.PhotoImage(img2) root.geometry("400x640+500+5") root_label.configure(image=img2) root_label.image = img2 def record(): global list_images list_images = [] if (askokcancel("WARNING", "Look at the camera\nand sit steady")): root.focus_set() count = 0 cam = cv2.VideoCapture(0) ret, t_img = cam.read() while (True): ret, img = cam.read() img = cv2.flip(img, 1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = detector.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) if (len(faces) == 1): count += 1 list_images.append(gray[y:y + h, x:x + w]) cv2.imshow("image", img) k = cv2.waitKey(100) & 0xff if (k == 27): break elif (count >= 50): break cam.release() cv2.destroyAllWindows() setimage(t_img) Button(F4, text="RECORD", width=10, height=2, command=record).pack(side=LEFT, pady=5, padx=5) Button(F4, text="CANCEL", width=10, height=2, command=root.destroy).pack(side=LEFT, pady=5, padx=5) Button(F4, text="SUBMIT", width=10, height=2, command=submit).pack(side=LEFT, pady=5, padx=5) root.bind("<Escape>", lambda e: root.destroy()) root.bind("<Return>", lambda e: submit()) root.mainloop()
def __init__(self, labels=None): labels = input('Enter field names: ').split() Combobox.__init__(self, labels)
btn_sn = Button(root, text='Добавить периферию', command=click) btn_sn.grid(column=1, row=4) # создаем текстовое поле для кожаного # поле ввода серийного номера user_text_sn = Entry(root, width=22) user_text_sn.grid(column=1, row=1) user_text_sn.focus() # поле ввода рабочего места user_text_rm = Entry(root, width=22) user_text_rm.grid(column=1, row=2) # выпадающий список и поломками breakdown_list = Combobox(root) breakdown_list['values'] = ('Укажите из списка', 'Микрофон', 'Левый наушник', 'Правый наушник', 'Повряждение кабеля') breakdown_list.current(0) breakdown_list.grid(column=1, row=3) # создаем cursor и connection которые уже есть в db_connection, # поэтому просто обращаемся к ним заренее импортировав cur = db_connection.cursor conn = db_connection.conn def insert_data(): cur.execute( "INSERT INTO defective_headset (serial_number, workplace, malfunction) VALUES (%s, %s, %s)", (user_text_sn.get(), user_text_rm.get(), breakdown_list.get()))
window = Tk() window.title("Witaj w aplikacji!") lbl = Label(window, text="Witaj Świecie!", font=("Arial Bold", 25), fg="blue") lbl.grid(column=0, row=0) txt = Entry(window, width=10, font=("Arial Bold", 25)) txt.grid(column=0, row=4) txt.focus() combo = Combobox(window) combo['values'] = (1, "Mleko", 3, "Jabłko", 5) combo.current(1) combo.grid(column=0, row=5) chk_state = BooleanVar() chk_state.set(True) chk = Checkbutton(window, text='Choose', var=chk_state) chk.grid(column=0, row=6)
city_button.place(x = 795, y = 170) def message_age(): age_buton = Button(window, text = "Save", command = edit_age, font="helvetica 12",background='green',foreground='white',borderwidth=6,width=12,height=1) age_buton.place(x = 1165, y = 720) # LABELS #CAR_CLASS class_label = Label(window, text = "CLASS", font="helvetica 12",borderwidth=6,width=12,height=1) class_label.place(x = 1165, y = 400) classes = ['A-Class', 'B-Class', 'C-Class', 'E-Class'] class_box = Combobox(window, values = classes) class_box.place(x = 1165, y = 430) class_button = Button(window, text = "Save", command = class_type, font="helvetica 12",borderwidth=6,width=12,height=1) class_button.place(x = 1165, y = 450) #VARIANT variant_label = Label(window, text = "VARIANT", font="helvetica 12",borderwidth=6,width=12,height=1) variant_label.place(x = 1165, y = 550) variants = ['A 180', 'A 200', 'B 180', 'C 180', 'C 200', 'C 220', 'E 180', 'E 200', 'E 220', 'E 250', 'E 300', 'E 350', 'Other'] variant_box = Combobox(window, values = variants)
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()
from tkinter.ttk import Combobox from tkinter.ttk import Checkbutton from tkinter.ttk import Radiobutton from tkinter import messagebox from tkinter import Menu from tkinter import ttk def clicked(): messagebox.showinfo('Заголовок', 'Текст') res = "Привет {}".format(txt.get()) lbl.configure(text=res) window = Tk() combo = Combobox(window) # chk = Checkbutton(window, text='Выбрать') # rad1 = Radiobutton(window,text='Первый', value=1) window.geometry('400x250') window.title("Добро пожаловать в приложение PythonRu") menu = Menu(window) new_item = Menu(menu) new_item.add_command(label='Новый') new_item.add_separator() new_item.add_command(label='Изменить') menu.add_cascade(label='Файл', menu=new_item) window.config(menu=menu) tab_control = ttk.Notebook(window)
def ventana(Fichero_Auditoria): # Validaciones iniciales prueba_bd = base_datos.prueba_conectividad() if prueba_bd["Conectividad"] == "KO": print("Conectividad con Base de Datos: " + prueba_bd["Error"]) else: # Creacion de ventana principal Continuar_Proceso = False root = tk.Tk() root.title("Automatización Auditorias EMR - Fichero: " + Fichero_Auditoria) width=870 height=840 screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) root.geometry(alignstr) root.resizable(width=False, height=False) # LabelFrame general ftl = tkFont.Font(family='Times', size=13) labelframe = tk.LabelFrame(root, text='Ingresar datos... ' + Fichero_Auditoria, font=ftl) labelframe.pack(expand='yes', fill='both') ft = tkFont.Font(family='Times', size=12) # Label frame Tecnologias a Implantar labelframeTI = tk.LabelFrame(labelframe, text='Tecnologías a Implantar', width=850, height=70, font=ftl) labelframeTI.grid(padx=3, pady=25) #TECNOLOGIAS A IMPLANTAR check_G900I = tk.IntVar() def GCheckBox_G900I_command(): if check_G900I.get(): print('Checkbox 1 selected') DTImplantar["DTI_G900"] = 1 print(DTImplantar) else: DTImplantar["DTI_G900"] = 0 GCheckBox_G900I = tk.Checkbutton(labelframeTI) GCheckBox_G900I["variable"] = check_G900I GCheckBox_G900I["font"] = ft GCheckBox_G900I["fg"] = "#333333" GCheckBox_G900I["justify"] = "center" GCheckBox_G900I["text"] = "G900" GCheckBox_G900I.place(x=10, y=10, width=70, height=25) GCheckBox_G900I["offvalue"] = "0" GCheckBox_G900I["onvalue"] = "1" GCheckBox_G900I["command"] = GCheckBox_G900I_command check_G1800I = tk.IntVar() def GCheckBox_G1800I_command(): if check_G1800I.get(): DTImplantar["DTI_G1800"] = 1 else: DTImplantar["DTI_G1800"] = 0 GCheckBox_G1800I = tk.Checkbutton(labelframeTI) GCheckBox_G1800I["variable"] = check_G1800I GCheckBox_G1800I["font"] = ft GCheckBox_G1800I["fg"] = "#333333" GCheckBox_G1800I["justify"] = "center" GCheckBox_G1800I["text"] = "G1800" GCheckBox_G1800I.place(x=90, y=10, width=70, height=25) GCheckBox_G1800I["offvalue"] = "0" GCheckBox_G1800I["onvalue"] = "1" GCheckBox_G1800I["command"] = GCheckBox_G1800I_command check_U900I = tk.IntVar() def GCheckBox_U900I_command(): if check_U900I.get(): DTImplantar["DTI_U900"] = 1 else: DTImplantar["DTI_U900"] = 0 GCheckBox_U900I = tk.Checkbutton(labelframeTI) GCheckBox_U900I["variable"] = check_U900I GCheckBox_U900I["font"] = ft GCheckBox_U900I["fg"] = "#333333" GCheckBox_U900I["justify"] = "center" GCheckBox_U900I["text"] = "U900" GCheckBox_U900I.place(x=160, y=10, width=70, height=25) GCheckBox_U900I["offvalue"] = "0" GCheckBox_U900I["onvalue"] = "1" GCheckBox_U900I["command"] = GCheckBox_U900I_command check_U2100I = tk.IntVar() def GCheckBox_U2100I_command(): if check_U2100I.get(): DTImplantar["DTI_U2100"] = 1 else: DTImplantar["DTI_U2100"] = 0 GCheckBox_U2100I = tk.Checkbutton(labelframeTI) GCheckBox_U2100I["variable"] = check_U2100I GCheckBox_U2100I["font"] = ft GCheckBox_U2100I["fg"] = "#333333" GCheckBox_U2100I["justify"] = "center" GCheckBox_U2100I["text"] = "U2100" GCheckBox_U2100I.place(x=240, y=10, width=70, height=25) GCheckBox_U2100I["offvalue"] = "0" GCheckBox_U2100I["onvalue"] = "1" GCheckBox_U2100I["command"] = GCheckBox_U2100I_command check_L800I = tk.IntVar() def GCheckBox_L800I_command(): if check_L800I.get(): DTImplantar["DTI_L800"] = 1 else: DTImplantar["DTI_L800"] = 0 GCheckBox_L800I = tk.Checkbutton(labelframeTI) GCheckBox_L800I["variable"] = check_L800I GCheckBox_L800I["font"] = ft GCheckBox_L800I["fg"] = "#333333" GCheckBox_L800I["justify"] = "center" GCheckBox_L800I["text"] = "L800" GCheckBox_L800I.place(x=320, y=10, width=70, height=25) GCheckBox_L800I["offvalue"] = "0" GCheckBox_L800I["onvalue"] = "1" GCheckBox_L800I["command"] = GCheckBox_L800I_command check_L1800I = tk.IntVar() def GCheckBox_L1800I_command(): if check_L1800I.get(): DTImplantar["DTI_L1800"] = 1 else: DTImplantar["DTI_L1800"] = 0 GCheckBox_L1800I = tk.Checkbutton(labelframeTI) GCheckBox_L1800I["variable"] = check_L1800I GCheckBox_L1800I["font"] = ft GCheckBox_L1800I["fg"] = "#333333" GCheckBox_L1800I["justify"] = "center" GCheckBox_L1800I["text"] = "L1800" GCheckBox_L1800I.place(x=400, y=10, width=70, height=25) GCheckBox_L1800I["offvalue"] = "0" GCheckBox_L1800I["onvalue"] = "1" GCheckBox_L1800I["command"] = GCheckBox_L1800I_command check_L2100I = tk.IntVar() def GCheckBox_L2100I_command(): if check_L2100I.get(): DTImplantar["DTI_L2100"] = 1 print(DTImplantar) else: DTImplantar["DTI_L2100"] = 0 GCheckBox_L2100I = tk.Checkbutton(labelframeTI) GCheckBox_L2100I["variable"] = check_L2100I GCheckBox_L2100I["font"] = ft GCheckBox_L2100I["fg"] = "#333333" GCheckBox_L2100I["justify"] = "center" GCheckBox_L2100I["text"] = "L2100" GCheckBox_L2100I.place(x=480, y=10, width=70, height=25) GCheckBox_L2100I["offvalue"] = "0" GCheckBox_L2100I["onvalue"] = "1" GCheckBox_L2100I["command"] = GCheckBox_L2100I_command check_L2600I = tk.IntVar() def GCheckBox_L2600I_command(): if check_L2600I.get(): DTImplantar["DTI_L2600"] = 1 else: DTImplantar["DTI_L2600"] = 0 GCheckBox_L2600I = tk.Checkbutton(labelframeTI) GCheckBox_L2600I["variable"] = check_L2600I GCheckBox_L2600I["font"] = ft GCheckBox_L2600I["fg"] = "#333333" GCheckBox_L2600I["justify"] = "center" GCheckBox_L2600I["text"] = "L2600" GCheckBox_L2600I.place(x=560, y=10, width=70, height=25) GCheckBox_L2600I["offvalue"] = "0" GCheckBox_L2600I["onvalue"] = "1" GCheckBox_L2600I["command"] = GCheckBox_L2600I_command check_5GI = tk.IntVar() def GCheckBox_5GI_command(): if check_5GI.get(): DTImplantar["DTI_5G"] = 1 else: DTImplantar["DTI_5G"] = 0 GCheckBox_5GI = tk.Checkbutton(labelframeTI) GCheckBox_5GI["variable"] = check_5GI GCheckBox_5GI["font"] = ft GCheckBox_5GI["fg"] = "#333333" GCheckBox_5GI["justify"] = "center" GCheckBox_5GI["text"] = "5G" GCheckBox_5GI.place(x=640, y=10, width=70, height=25) GCheckBox_5GI["offvalue"] = "0" GCheckBox_5GI["onvalue"] = "1" GCheckBox_5GI["command"] = GCheckBox_5GI_command # TECNOLOGIAS POSTERIORES labelframeTP = tk.LabelFrame(labelframe, text='Tecnologías Posteriores', width=850, height=70, font=ftl) labelframeTP.grid(padx=10, pady=2) # # ES TDT # labelframeTDT = tk.LabelFrame(labelframe, text='', width=50, height=70, font=ftl) # labelframeTDT.grid(padx=10, pady=3) check_G900P = tk.IntVar() def GCheckBox_G900P_command(): if check_G900P.get(): DTPosterior["DTP_G900"] = 1 else: DTPosterior["DTP_G900"] = 0 GCheckBox_G900P = tk.Checkbutton(labelframeTP) GCheckBox_G900P["variable"] = check_G900P GCheckBox_G900P["font"] = ft GCheckBox_G900P["fg"] = "#333333" GCheckBox_G900P["justify"] = "center" GCheckBox_G900P["text"] = "G900" GCheckBox_G900P.place(x=10, y=10, width=70, height=25) GCheckBox_G900P["offvalue"] = "0" GCheckBox_G900P["onvalue"] = "1" GCheckBox_G900P["command"] = GCheckBox_G900P_command check_G1800P = tk.IntVar() def GCheckBox_G1800P_command(): if check_G1800P.get(): DTPosterior["DTP_G1800"] = 1 else: DTPosterior["DTP_G1800"] = 0 GCheckBox_G1800P = tk.Checkbutton(labelframeTP) GCheckBox_G1800P["variable"] = check_G1800P GCheckBox_G1800P["font"] = ft GCheckBox_G1800P["fg"] = "#333333" GCheckBox_G1800P["justify"] = "center" GCheckBox_G1800P["text"] = "G1800" GCheckBox_G1800P.place(x=90, y=10, width=70, height=25) GCheckBox_G1800P["offvalue"] = "0" GCheckBox_G1800P["onvalue"] = "1" GCheckBox_G1800P["variable"] = "1" GCheckBox_G1800P["command"] = GCheckBox_G1800P_command check_U900P = tk.IntVar() def GCheckBox_U900P_command(): if check_U900P.get(): DTPosterior["DTP_U900"] = 1 else: DTPosterior["DTP_U900"] = 0 GCheckBox_U900P = tk.Checkbutton(labelframeTP) GCheckBox_U900P["variable"] = check_U900P GCheckBox_U900P["font"] = ft GCheckBox_U900P["fg"] = "#333333" GCheckBox_U900P["justify"] = "center" GCheckBox_U900P["text"] = "U900" GCheckBox_U900P.place(x=160, y=10, width=70, height=25) GCheckBox_U900P["offvalue"] = "0" GCheckBox_U900P["onvalue"] = "1" GCheckBox_U900P["command"] = GCheckBox_U900P_command check_U2100P = tk.IntVar() def GCheckBox_U2100P_command(): if check_U2100P.get(): DTPosterior["DTP_U2100"] = 1 else: DTPosterior["DTP_U2100"] = 0 GCheckBox_U2100P = tk.Checkbutton(labelframeTP) GCheckBox_U2100P["variable"] = check_U2100P GCheckBox_U2100P["font"] = ft GCheckBox_U2100P["fg"] = "#333333" GCheckBox_U2100P["justify"] = "center" GCheckBox_U2100P["text"] = "U2100" GCheckBox_U2100P.place(x=240, y=10, width=70, height=25) GCheckBox_U2100P["offvalue"] = "0" GCheckBox_U2100P["onvalue"] = "1" GCheckBox_U2100P["command"] = GCheckBox_U2100P_command check_L800P = tk.IntVar() def GCheckBox_L800P_command(): if check_L800P.get(): DTPosterior["DTP_L800"] = 1 else: DTPosterior["DTP_L800"] = 0 GCheckBox_L800P = tk.Checkbutton(labelframeTP) GCheckBox_L800P["variable"] = check_L800P GCheckBox_L800P["font"] = ft GCheckBox_L800P["fg"] = "#333333" GCheckBox_L800P["justify"] = "center" GCheckBox_L800P["text"] = "L800" GCheckBox_L800P.place(x=320, y=10, width=70, height=25) GCheckBox_L800P["offvalue"] = "0" GCheckBox_L800P["onvalue"] = "1" GCheckBox_L800P["command"] = GCheckBox_L800P_command check_L1800P = tk.IntVar() def GCheckBox_L1800P_command(): if check_L1800P.get(): DTPosterior["DTP_L1800"] = 1 else: DTPosterior["DTP_L1800"] = 0 GCheckBox_L1800P = tk.Checkbutton(labelframeTP) GCheckBox_L1800P["variable"] = check_L1800P GCheckBox_L1800P["font"] = ft GCheckBox_L1800P["fg"] = "#333333" GCheckBox_L1800P["justify"] = "center" GCheckBox_L1800P["text"] = "L1800" GCheckBox_L1800P.place(x=400, y=10, width=70, height=25) GCheckBox_L1800P["offvalue"] = "0" GCheckBox_L1800P["onvalue"] = "1" GCheckBox_L1800P["command"] = GCheckBox_L1800P_command check_L2100P = tk.IntVar() def GCheckBox_L2100P_command(): if check_L2100P.get(): DTPosterior["DTP_L2100"] = 1 else: DTPosterior["DTP_L2100"] = 0 GCheckBox_L2100P = tk.Checkbutton(labelframeTP) GCheckBox_L2100P["variable"] = check_L2100P GCheckBox_L2100P["font"] = ft GCheckBox_L2100P["fg"] = "#333333" GCheckBox_L2100P["justify"] = "center" GCheckBox_L2100P["text"] = "L2100" GCheckBox_L2100P.place(x=480, y=10, width=70, height=25) GCheckBox_L2100P["offvalue"] = "0" GCheckBox_L2100P["onvalue"] = "1" GCheckBox_L2100P["command"] = GCheckBox_L2100P_command check_L2600P = tk.IntVar() def GCheckBox_L2600P_command(): if check_L2600P.get(): DTPosterior["DTP_L2600"] = 1 else: DTPosterior["DTP_L2600"] = 0 GCheckBox_L2600P = tk.Checkbutton(labelframeTP) GCheckBox_L2600P["variable"] = check_L2600P GCheckBox_L2600P["font"] = ft GCheckBox_L2600P["fg"] = "#333333" GCheckBox_L2600P["justify"] = "center" GCheckBox_L2600P["text"] = "L2600" GCheckBox_L2600P.place(x=560, y=10, width=70, height=25) GCheckBox_L2600P["offvalue"] = "0" GCheckBox_L2600P["onvalue"] = "1" GCheckBox_L2600P["command"] = GCheckBox_L2600P_command check_5GP = tk.IntVar() def GCheckBox_5GP_command(): if check_5GP.get(): DTPosterior["DTP_5G"] = 1 print(DTPosterior) else: DTPosterior["DTP_5G"] = 0 GCheckBox_5GP = tk.Checkbutton(labelframeTP) GCheckBox_5GP["variable"] = check_5GP GCheckBox_5GP["font"] = ft GCheckBox_5GP["fg"] = "#333333" GCheckBox_5GP["justify"] = "center" GCheckBox_5GP["text"] = "5G" GCheckBox_5GP.place(x=640, y=10, width=70, height=25) GCheckBox_5GP["offvalue"] = "0" GCheckBox_5GP["onvalue"] = "1" GCheckBox_5GP["command"] = GCheckBox_5GP_command # EMPLAZAMIENTOS Y NUMERO DE SECTORES labelEmSe = tk.LabelFrame(labelframe, text='Emplazamiento Compartido - Número de sectores', width=850, height=70, font=ftl) labelEmSe.grid(padx=10, pady=3) GLabel_418=tk.Label(labelEmSe) GLabel_418["font"] = ft GLabel_418["fg"] = "#333333" GLabel_418["justify"] = "center" GLabel_418["text"] = "Emplazamiento Compartido:" GLabel_418.place(x=10,y=10,width=187,height=30) cmbEmplazamiento = Combobox(labelEmSe, width="10", values=("SI", "NO"), font = ft) cmbEmplazamiento.place(x=200, y=10, width=70, height=25) cmbEmplazamiento.current(0) GLabel_420=tk.Label(labelEmSe) GLabel_420["font"] = ft GLabel_420["fg"] = "#333333" GLabel_420["justify"] = "center" GLabel_420["text"] = "Número de Sectores:" GLabel_420.place(x=300,y=10,width=187,height=30) cmbSectores = Combobox(labelEmSe, width="10", values=("1", "2", "3", "4"), font = ft) cmbSectores.place(x=470, y=10, width=70, height=25) cmbSectores.current(0) # ANTENAS labelAntenas = tk.LabelFrame(labelframe, text='Antenas', width=850, height=170, font=ftl) labelAntenas.grid(padx=10, pady=3) GLabel_Antenas=tk.Label(labelAntenas, font = ftl, text="Antenas", justify = "center", bg="#FAF0E6") GLabel_Antenas.place(x=25,y=3,width=100,height=30) GLabel_Exteriores=tk.Label(labelAntenas, font = ftl, text="Exteriores", justify = "center") GLabel_Exteriores.place(x=25,y=23,width=150,height=30) GLabel_Interiores=tk.Label(labelAntenas, font = ftl, text="Interiores", justify = "center") GLabel_Interiores.place(x=25,y=43,width=150,height=30) GLabel_Azimut=tk.Label(labelAntenas, font = ftl, text="Azimut", justify = "center") GLabel_Azimut.place(x=25,y=63,width=150,height=30) GLabel_Modelo=tk.Label(labelAntenas, font = ftl, text="Modelo antena", justify = "center") GLabel_Modelo.place(x=25,y=63+25,width=150,height=30) GLabel_Altura=tk.Label(labelAntenas, font = ftl, text="Altura de antena", justify = "center") GLabel_Altura.place(x=25,y=63+25*2,width=150,height=30) GLabel_Sector1 = tk.Label(labelAntenas, font=ftl, text="Sector1", justify="center", bg="#FAF0E6") GLabel_Sector1.place(x=150, y=3, width=100, height=30) GLabel_Sector2 = tk.Label(labelAntenas, font=ftl, text="Sector2", justify="center", bg="#FAF0E6") GLabel_Sector2.place(x=150+130, y=3, width=100, height=30) GLabel_Sector3 = tk.Label(labelAntenas, font=ftl, text="Sector3", justify="center", bg="#FAF0E6") GLabel_Sector3.place(x=150+130*2, y=3, width=100, height=30) GLabel_Sector4 = tk.Label(labelAntenas, font=ftl, text="Sector4", justify="center", bg="#FAF0E6") GLabel_Sector4.place(x=150+130*3, y=3, width=100, height=30) ANEXS1 = tk.IntVar() def ANEXS1_command(): DAntenaExterior["Sector1"] = 1 if ANEXS1.get() else 0 GCheckBox_ANEXS1 = tk.Checkbutton(labelAntenas, variable=ANEXS1, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANEXS1.place(x=160, y=23, width=70, height=25) GCheckBox_ANEXS1["command"] = ANEXS1_command ANEXS2 = tk.IntVar() def ANEXS2_command(): DAntenaExterior["Sector2"] = 1 if ANEXS2.get() else 0 GCheckBox_ANEXS2 = tk.Checkbutton(labelAntenas, variable=ANEXS2, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANEXS2.place(x=160+130, y=23, width=70, height=25) GCheckBox_ANEXS2["command"] = ANEXS2_command ANEXS3 = tk.IntVar() def ANEXS3_command(): DAntenaExterior["Sector3"] = 1 if ANEXS3.get() else 0 GCheckBox_ANEXS3 = tk.Checkbutton(labelAntenas, variable=ANEXS3, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANEXS3.place(x=160+130*2, y=23, width=70, height=25) GCheckBox_ANEXS3["command"] = ANEXS3_command ANEXS4 = tk.IntVar() def ANEXS4_command(): DAntenaExterior["Sector4"] = 1 if ANEXS4.get() else 0 GCheckBox_ANEXS4 = tk.Checkbutton(labelAntenas, variable=ANEXS4, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANEXS4.place(x=160+130*3, y=23, width=70, height=25) GCheckBox_ANEXS4["command"] = ANEXS4_command ANINS1 = tk.IntVar() def ANINS1_command(): DAntenaInterior["Sector1"] = 1 if ANINS1.get() else 0 GCheckBox_ANINS1 = tk.Checkbutton(labelAntenas, variable=ANINS1, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANINS1.place(x=160, y=43, width=70, height=25) GCheckBox_ANINS1["command"] = ANINS1_command ANINS2 = tk.IntVar() def ANINS2_command(): DAntenaInterior["Sector2"] = 1 if ANINS2.get() else 0 GCheckBox_ANINS2 = tk.Checkbutton(labelAntenas, variable=ANINS2, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANINS2.place(x=160+130, y=43, width=70, height=25) GCheckBox_ANINS2["command"] = ANINS2_command ANINS3 = tk.IntVar() def ANINS3_command(): DAntenaInterior["Sector3"] = 1 if ANINS3.get() else 0 GCheckBox_ANINS3 = tk.Checkbutton(labelAntenas, variable=ANINS3, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANINS3.place(x=160+130*2, y=43, width=70, height=25) GCheckBox_ANINS3["command"] = ANINS3_command ANINS4 = tk.IntVar() def ANINS4_command(): DAntenaInterior["Sector4"] = 1 if ANINS4.get() else 0 GCheckBox_ANINS4 = tk.Checkbutton(labelAntenas, variable=ANINS4, font=ftl, offvalue="0", onvalue="1") GCheckBox_ANINS4.place(x=160+130*3, y=43, width=70, height=25) GCheckBox_ANINS4["command"] = ANINS4_command TxtAzimutS1 = tk.Entry(labelAntenas, text="", font=ftl) TxtAzimutS1.place(x=170, y=63, width=100, height=25) TxtAzimutS2 = tk.Entry(labelAntenas, text="", font=ftl) TxtAzimutS2.place(x=170+130, y=63, width=100, height=25) TxtAzimutS3 = tk.Entry(labelAntenas, text="", font=ftl) TxtAzimutS3.place(x=170+130*2, y=63, width=100, height=25) TxtAzimutS4 = tk.Entry(labelAntenas, text="", font=ftl) TxtAzimutS4.place(x=170+130*3, y=63, width=100, height=25) obtiene_antenas = base_datos.obtiene_antenas() if obtiene_antenas["Error"] == "": results_for_modeloantena = obtiene_antenas["Modelos_Antenas"] Continuar_Proceso = True else: results_for_modeloantena = [""] messagebox.showerror("Error", obtiene_antenas["Error"]) #Continuar_Proceso = False fts = tkFont.Font(family='Times', size=10) cmbANS1 = Combobox(labelAntenas, width="10", values=results_for_modeloantena, font=fts) cmbANS1.place(x=170, y=63+25, width=100, height=25) cmbANS1.current(0) cmbANS2 = Combobox(labelAntenas, width="10", values=results_for_modeloantena, font=fts) cmbANS2.place(x=170+130, y=63 + 25, width=100, height=25) cmbANS2.current(0) cmbANS3 = Combobox(labelAntenas, width="10", values=results_for_modeloantena, font=fts) cmbANS3.place(x=170+130*2, y=63 + 25, width=100, height=25) cmbANS3.current(0) cmbANS4 = Combobox(labelAntenas, width="10", values=results_for_modeloantena, font=fts) cmbANS4.place(x=170 + 130 * 3, y=63 + 25, width=100, height=25) cmbANS4.current(0) TxtAlturaS1 = tk.Entry(labelAntenas, text="", font=ftl) TxtAlturaS1.place(x=170, y=63+25*2, width=100, height=25) TxtAlturaS2 = tk.Entry(labelAntenas, text="", font=ftl) TxtAlturaS2.place(x=170+130, y=63 + 25 * 2, width=100, height=25) TxtAlturaS3 = tk.Entry(labelAntenas, text="", font=ftl) TxtAlturaS3.place(x=170 + 130*2, y=63 + 25 * 2, width=100, height=25) TxtAlturaS4 = tk.Entry(labelAntenas, text="", font=ftl) TxtAlturaS4.place(x=170 + 130*3, y=63 + 25 * 2, width=100, height=25) # TILTS labelTilts = tk.LabelFrame(labelframe, text='Tilts', width=850, height=300, font=ft) labelTilts.grid(padx=10, pady=3) GLabel_Tilts = tk.Label(labelTilts, font=ft, text="Tilts", justify="center", bg="#FAF0E6") GLabel_Tilts.place(x=25, y=3, width=100, height=30) TLabel_Sector1 = tk.Label(labelTilts, font=ftl, text="Sector1", justify="center", bg="#FAF0E6") TLabel_Sector1.place(x=150, y=3, width=100, height=30) TLabel_Sector2 = tk.Label(labelTilts, font=ftl, text="Sector2", justify="center", bg="#FAF0E6") TLabel_Sector2.place(x=150 + 130, y=3, width=100, height=30) TLabel_Sector3 = tk.Label(labelTilts, font=ftl, text="Sector3", justify="center", bg="#FAF0E6") TLabel_Sector3.place(x=150 + 130 * 2, y=3, width=100, height=30) TLabel_Sector4 = tk.Label(labelTilts, font=ftl, text="Sector4", justify="center", bg="#FAF0E6") TLabel_Sector4.place(x=150 + 130 * 3, y=3, width=100, height=30) GLabel_G900 = tk.Label(labelTilts, font=ft, text="G900", justify="center") GLabel_G900.place(x=25, y=3+25, width=150, height=30) GLabel_G1800 = tk.Label(labelTilts, font=ft, text="G1800", justify="center", bg="#FAF0E6") GLabel_G1800.place(x=25, y=3 + 25*2, width=150, height=30) GLabel_U900 = tk.Label(labelTilts, font=ft, text="U900", justify="center") GLabel_U900.place(x=25, y=3 + 25 * 3, width=150, height=30) GLabel_U2100 = tk.Label(labelTilts, font=ft, text="U2100", justify="center", bg="#FAF0E6") GLabel_U2100.place(x=25, y=3 + 25*4, width=150, height=30) GLabel_L800 = tk.Label(labelTilts, font=ft, text="L800", justify="center") GLabel_L800.place(x=25, y=3 + 25*5, width=150, height=30) GLabel_L1800 = tk.Label(labelTilts, font=ft, text="L1800", justify="center", bg="#FAF0E6") GLabel_L1800.place(x=25, y=3 + 25*6, width=150, height=30) GLabel_L2100 = tk.Label(labelTilts, font=ft, text="L2100", justify="center") GLabel_L2100.place(x=25, y=3 + 25*7, width=150, height=30) GLabel_L2600 = tk.Label(labelTilts, font=ft, text="L2600", justify="center", bg="#FAF0E6") GLabel_L2600.place(x=25, y=3 + 25*8, width=150, height=30) GLabel_5G = tk.Label(labelTilts, font=ft, text="5G", justify="center") GLabel_5G.place(x=25, y=3 + 25 * 9, width=150, height=30) TxtTG900S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTG900S1.place(x=170, y=3+25, width=100, height=25) TxtTG900S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTG900S2.place(x=170 + 130, y=3+25, width=100, height=25) TxtTG900S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTG900S3.place(x=170 + 130 * 2, y=3+25, width=100, height=25) TxtTG900S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTG900S4.place(x=170 + 130 * 3, y=3+25, width=100, height=25) TxtTG1800S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTG1800S1.place(x=170, y=3 + 25*2, width=100, height=25) TxtTG1800S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTG1800S2.place(x=170 + 130, y=3 + 25*2, width=100, height=25) TxtTG1800S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTG1800S3.place(x=170 + 130 * 2, y=3 + 25*2, width=100, height=25) TxtTG1800S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTG1800S4.place(x=170 + 130 * 3, y=3 + 25*2, width=100, height=25) TxtTU900S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTU900S1.place(x=170, y=3 + 25 * 3, width=100, height=25) TxtTU900S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTU900S2.place(x=170 + 130, y=3 + 25 * 3, width=100, height=25) TxtTU900S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTU900S3.place(x=170 + 130 * 2, y=3 + 25 * 3, width=100, height=25) TxtTU900S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTU900S4.place(x=170 + 130 * 3, y=3 + 25 * 3, width=100, height=25) TxtTU21001S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTU21001S1.place(x=170, y=3 + 25 * 4, width=100, height=25) TxtTU21001S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTU21001S2.place(x=170 + 130, y=3 + 25 * 4, width=100, height=25) TxtTU21001S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTU21001S3.place(x=170 + 130 * 2, y=3 + 25 * 4, width=100, height=25) TxtTU21001S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTU21001S4.place(x=170 + 130 * 3, y=3 + 25 * 4, width=100, height=25) TxtTL800S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTL800S1.place(x=170, y=3 + 25 * 5, width=100, height=25) TxtTL800S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTL800S2.place(x=170 + 130, y=3 + 25 * 5, width=100, height=25) TxtTL800S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTL800S3.place(x=170 + 130 * 2, y=3 + 25 * 5, width=100, height=25) TxtTL800S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTL800S4.place(x=170 + 130 * 3, y=3 + 25 * 5, width=100, height=25) TxtTL1800S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTL1800S1.place(x=170, y=3 + 25 * 6, width=100, height=25) TxtTL1800S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTL1800S2.place(x=170 + 130, y=3 + 25 * 6, width=100, height=25) TxtTL1800S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTL1800S3.place(x=170 + 130 * 2, y=3 + 25 * 6, width=100, height=25) TxtTL1800S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTL1800S4.place(x=170 + 130 * 3, y=3 + 25 * 6, width=100, height=25) TxtTL2100S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2100S1.place(x=170, y=3 + 25 * 7, width=100, height=25) TxtTL2100S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2100S2.place(x=170 + 130, y=3 + 25 * 7, width=100, height=25) TxtTL2100S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2100S3.place(x=170 + 130 * 2, y=3 + 25 * 7, width=100, height=25) TxtTL2100S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2100S4.place(x=170 + 130 * 3, y=3 + 25 * 7, width=100, height=25) TxtTL2600S1 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2600S1.place(x=170, y=3 + 25 * 8, width=100, height=25) TxtTL2600S2 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2600S2.place(x=170 + 130, y=3 + 25 * 8, width=100, height=25) TxtTL2600S3 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2600S3.place(x=170 + 130 * 2, y=3 + 25 * 8, width=100, height=25) TxtTL2600S4 = tk.Entry(labelTilts, text="", font=ftl) TxtTL2600S4.place(x=170 + 130 * 3, y=3 + 25 * 8, width=100, height=25) TxtT5GS1 = tk.Entry(labelTilts, text="", font=ftl) TxtT5GS1.place(x=170, y=3 + 25 * 9, width=100, height=25) TxtT5GS2 = tk.Entry(labelTilts, text="", font=ftl) TxtT5GS2.place(x=170 + 130, y=3 + 25 * 9, width=100, height=25) TxtT5GS3 = tk.Entry(labelTilts, text="", font=ftl) TxtT5GS3.place(x=170 + 130 * 2, y=3 + 25 * 9, width=100, height=25) TxtT5GS4 = tk.Entry(labelTilts, text="", font=ftl) TxtT5GS4.place(x=170 + 130 * 3, y=3 + 25 * 9, width=100, height=25) #BOTONES def asignar_valores(): DEmplazamientoSectores["Emplazamiento_Compartido"] = cmbEmplazamiento.get() DEmplazamientoSectores["Numero_Sectores"] = cmbSectores.get() DModeloAntena["Sector1"] = cmbANS1.get() DModeloAntena["Sector2"] = cmbANS2.get() DModeloAntena["Sector3"] = cmbANS3.get() DModeloAntena["Sector4"] = cmbANS4.get() DAzimut["Sector1"] = TxtAzimutS1.get() DAzimut["Sector2"] = TxtAzimutS2.get() DAzimut["Sector2"] = TxtAzimutS2.get() DAzimut["Sector2"] = TxtAzimutS2.get() DAlturaAntena["Sector1"] = TxtAlturaS1.get() DAlturaAntena["Sector2"] = TxtAlturaS2.get() DAlturaAntena["Sector3"] = TxtAlturaS3.get() DAlturaAntena["Sector4"] = TxtAlturaS4.get() DTiltsG900["Sector1"] = TxtTG900S1.get() DTiltsG900["Sector2"] = TxtTG900S2.get() DTiltsG900["Sector3"] = TxtTG900S3.get() DTiltsG900["Sector4"] = TxtTG900S4.get() DTiltsG1800["Sector1"] = TxtTG1800S1.get() DTiltsG1800["Sector2"] = TxtTG1800S2.get() DTiltsG1800["Sector3"] = TxtTG1800S3.get() DTiltsG1800["Sector4"] = TxtTG1800S4.get() DTiltsU900["Sector1"] = TxtTU900S1.get() DTiltsU900["Sector1"] = TxtTU900S2.get() DTiltsU900["Sector3"] = TxtTU900S3.get() DTiltsU900["Sector4"] = TxtTU900S4.get() DTiltsU2100["Sector1"] = TxtTU21001S1.get() DTiltsU2100["Sector2"] = TxtTU21001S2.get() DTiltsU2100["Sector3"] = TxtTU21001S3.get() DTiltsU2100["Sector4"] = TxtTU21001S4.get() DTiltsL800["Sector1"] = TxtTL800S1.get() DTiltsL800["Sector2"] = TxtTL800S2.get() DTiltsL800["Sector3"] = TxtTL800S3.get() DTiltsL800["Sector4"] = TxtTL800S4.get() DTiltsL1800["Sector1"] = TxtTL1800S1.get() DTiltsL1800["Sector2"] = TxtTL1800S2.get() DTiltsL1800["Sector3"] = TxtTL1800S3.get() DTiltsL1800["Sector4"] = TxtTL1800S4.get() DTiltsL2100["Sector1"] = TxtTL2100S1.get() DTiltsL2100["Sector2"] = TxtTL2100S2.get() DTiltsL2100["Sector3"] = TxtTL2100S3.get() DTiltsL2100["Sector4"] = TxtTL2100S4.get() DTiltsL2600["Sector1"] = TxtTL2600S1.get() DTiltsL2600["Sector2"] = TxtTL2600S2.get() DTiltsL2600["Sector3"] = TxtTL2600S3.get() DTiltsL2600["Sector4"] = TxtTL2600S4.get() DTiltsG5["Sector1"] = TxtT5GS1.get() DTiltsG5["Sector2"] = TxtT5GS2.get() DTiltsG5["Sector3"] = TxtT5GS3.get() DTiltsG5["Sector4"] = TxtT5GS4.get() def btnAceptar_command(): nonlocal Continuar_Proceso Continuar_Proceso = True asignar_valores() DatosVentana.append(DTImplantar) DatosVentana.append(DTPosterior) DatosVentana.append(DEmplazamientoSectores) DatosVentana.append(DAntenaExterior) DatosVentana.append(DAntenaInterior) DatosVentana.append(DAzimut) DatosVentana.append(DModeloAntena) DatosVentana.append(DAlturaAntena) DatosVentana.append(DTiltsG900) DatosVentana.append(DTiltsG1800) DatosVentana.append(DTiltsU900) DatosVentana.append(DTiltsU2100) DatosVentana.append(DTiltsL800) DatosVentana.append(DTiltsL1800) DatosVentana.append(DTiltsL2100) DatosVentana.append(DTiltsL2600) DatosVentana.append(DTiltsG5) root.destroy() def btnCancelar_command(): nonlocal Continuar_Proceso Continuar_Proceso = False root.destroy() btnAceptar = tk.Button(root, text="Aceptar", font=ftl, command=btnAceptar_command) btnAceptar.place(relx="0.3", rely="0.94") btnCancelar = tk.Button(root, text="Cancelar", font=ftl, command = btnCancelar_command) btnCancelar.place(relx="0.5", rely="0.94") # PROCESO PRINCIPAL root.mainloop() return Continuar_Proceso, DatosVentana
#coding=utf-8 from tkinter import * from tkinter.ttk import Combobox from tkinter import filedialog from tkinter import messagebox from ctypes import * import serial.tools.list_ports import threading from ymodem import YMODEM import os from time import sleep app = Tk() comportbox = Combobox(app, width=7, height=10) baudratebox = Combobox(app, width=8, height=10) red_canvas = Canvas(app, width=50, height=50, bg="red") green_canvas = Canvas(app, width=50, height=50, bg="green") progress_bar = Canvas(app, width=350, height=26, bg="white") fill_line = progress_bar.create_rectangle(2, 2, 0, 27, width=0, fill="green") ser = serial.Serial(bytesize=8, parity='N', stopbits=1, timeout=1, write_timeout=3) linsten_lock = threading.Lock() need_listen = 0 exit_listen = False def upgrade_callback(total_packets, file_size, file_name):
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)
# second row in frame height_label = Label(frame, text="Height:") height_label.grid(row=1, column=0, padx=5, pady=2) height_entry = Entry(frame) height_entry.grid(row=1, column=1, pady=2) height_label = Label(frame, text="cm") height_label.grid(row=1, column=2, padx=5, pady=2) # third row in frame gender_label = Label(frame, text="Gender:") gender_label.grid(row=2, column=0, padx=5, pady=2) gender_select = Combobox(frame, width=18, values=["Male", "Female"]) gender_select.grid(row=2, column=1, pady=2) age_label = Label(frame, text="Age:") age_label.grid(row=2, column=2, padx=5, pady=2) age_entry = Entry(frame, width=5) age_entry.grid(row=2, column=3, pady=2, padx=5) # calculate button calculate_button = Button(window, text="Calculate Your Ideal Body Mass Index", font=("arial", 12, "bold"), padx=28, command=calculate_func) calculate_button.grid(row=2, columnspan=4)