def single_digit_gui(self, suggested_digit, digit_box_xyxy): self.master.withdraw() self.newWindow = tk.Toplevel(self.master) # convert to cv2 format and draw digit and it's bbox bb_image_cv = np.array(self.bb_image_pil) bb_image_with_digit_cv = self.draw_digit_box(bb_image_cv, box_xyxy=digit_box_xyxy) # convert back to tkinter format bb_image_pil_with_digit = Image.fromarray( cv2.resize(bb_image_with_digit_cv, (0, 0), fx=2, fy=2), 'RGB') bb_image_tk_with_digit = ImageTk.PhotoImage( image=bb_image_pil_with_digit) # add widgets to window game_image_label = tk.Label(self.newWindow, borderwidth=2, relief="groove") text = "Enter the digit inside the red&yellow bounding box\n" + \ "if the digit is " + str(suggested_digit) + " you can press yes and continue\n" + \ "if you can't detect a digit, press the \"Not a digit\" button" tag_question_label = tk.Label(self.newWindow, text=text) tag_question_label.config(font=("Arial", 12)) tag_question_label.pack(pady=10) game_image_label.pack() digit_entered_str = tk.StringVar(self.newWindow, value=str(suggested_digit)) jersey_digit_entry = tk.Entry(self.newWindow, width=3, borderwidth=2, relief="groove", font=("Arial", 16), justify='center', textvariable=digit_entered_str) jersey_digit_entry.pack(pady=6) jersey_digit_entry.focus() digit_entered_str.trace( "w", lambda *args: character_limit(digit_entered_str)) buttons_frame = tk.LabelFrame(self.newWindow, borderwidth=0) buttons_frame.pack(pady=6) save_digit_button = tk.Button( buttons_frame, text="Save digit", command=lambda: self.exit_popup_window( DIGIT_TAGGED, jersey_digit_entry.get(), digit_box_xyxy)) not_digit_button = tk.Button( buttons_frame, text="Not a digit", command=lambda: self.exit_popup_window(NO_DIGIT)) save_digit_button.pack(side='right', padx=8) not_digit_button.pack(side='left', padx=8) game_image_label.configure(image=bb_image_tk_with_digit) game_image_label.image = bb_image_tk_with_digit self.newWindow.protocol( 'WM_DELETE_WINDOW', lambda: self.exit_popup_window(called_by=EXIT_POP_UP)) self.center(self.newWindow, win_size=(self.W, int((game_image_label.winfo_reqheight() + tag_question_label.winfo_reqheight() + buttons_frame.winfo_reqheight() + jersey_digit_entry.winfo_reqheight() + 42) * 1.1)))
def search(self): self.newWindow = tk.Toplevel(self.master) Search(self.newWindow)
def delete(self): self.newWindow = tk.Toplevel(self.master) Delete(self.newWindow)
def display(self): win2 = tk.Toplevel() win2.geometry('900x800+1010+268') win2.wm_title("2. Display") section01right_heading = tk.Label(win2, font=('arial', 16), text='Output Monitor').grid( column=1, row=0, sticky="EW") preview_text = tk.Label(win2, font=('arial', 16), text='Preview').grid(column=0, row=1, sticky="W") bt_preview = tk.Button(win2, padx=16, bd=2, text="Preview", fg="blue", command=self.preview).grid(row=2, column=0, pady=5, sticky="W") bt_livepreview = tk.Button(win2, padx=16, bd=2, textvariable=self.livepreview_text, fg="blue", command=self.preview_live).grid(row=2, column=1, pady=5, sticky="W") image_preview_text = tk.Label(win2, font=('arial', 12), text='Preview Image: ').grid(column=0, row=3, sticky="W") self.image_preview = ImageTk.PhotoImage( Image.open(self.current_image_path)) self.image_panel01 = tk.Label(win2, image=self.image_preview) self.image_panel01.grid(column=0, row=3, sticky="W") image_livepreview_text = tk.Label(win2, font=('arial', 12), text='Live-Preview Image: ').grid( column=1, row=3, sticky="W") self.image_livepreview = ImageTk.PhotoImage( Image.open(self.current_image_path)) self.image_panel02 = tk.Label(win2, image=self.image_livepreview) self.image_panel02.grid(column=1, row=3, sticky="W") bt_detection = tk.Button(win2, padx=16, bd=2, text="Detection", fg="green", command=self.detection).grid(row=4, column=0, pady=5, sticky="EW") bt_classification = tk.Button(win2, padx=16, bd=2, text="Classification", fg="green", command=self.classification).grid( row=4, column=1, pady=5, sticky="EW") bt_segmentation = tk.Button(win2, padx=16, bd=2, text="Segmentation", fg="green", command=self.segmentation).grid( row=4, column=2, pady=5, sticky="EW") self.image_detection = ImageTk.PhotoImage( Image.open(self.current_image_path)) self.image_panel06 = tk.Label(win2, image=self.image_detection) self.image_panel06.grid(column=0, row=5, sticky="W") detection_image_text = tk.Label(win2, font=('arial', 12), textvariable=self.detection_text).grid( column=0, row=6, sticky="EW") self.image_classification = ImageTk.PhotoImage( Image.open(self.current_image_path)) self.image_panel07 = tk.Label(win2, image=self.image_classification) self.image_panel07.grid(column=1, row=5, sticky="W") classification_image_text = tk.Label( win2, font=('arial', 12), textvariable=self.classification_text).grid(column=1, row=6, sticky="EW") self.image_segmentation = ImageTk.PhotoImage( Image.open(self.current_image_path)) self.image_panel08 = tk.Label(win2, image=self.image_segmentation) self.image_panel08.grid(column=2, row=5, sticky="W") segmentation_image_text = tk.Label( win2, font=('arial', 12), textvariable=self.segmentation_text).grid(column=2, row=6, sticky="EW")
s.set(self.value) s.pack() def update(self, value): self.value = float(value) self.tkim.paste(self.enhancer.enhance(self.value)) # # main if len(sys.argv) != 2: print("Usage: enhancer file") sys.exit(1) root = tkinter.Tk() im = Image.open(sys.argv[1]) im.thumbnail((200, 200)) Enhance(root, im, "Color", ImageEnhance.Color, 0.0, 4.0).pack() Enhance(tkinter.Toplevel(), im, "Sharpness", ImageEnhance.Sharpness, -2.0, 2.0).pack() Enhance(tkinter.Toplevel(), im, "Brightness", ImageEnhance.Brightness, -1.0, 3.0).pack() Enhance(tkinter.Toplevel(), im, "Contrast", ImageEnhance.Contrast, -1.0, 3.0).pack() root.mainloop()
def popup(self): child = tk.Toplevel() cal = Calendar(child, self.data)
def admin(self): self.adminWindow = tk.Toplevel(self.master) self.admin = Admin(self.adminWindow, self) return
def __init__(self, filename='temp.png', root=tkinter.Tk()): # 先存一張截圖 用來選取截圖區域 self.filename = filename im = pyautogui.screenshot() im.save(filename) im.close() # 創建tkinter主窗口 self.root = root # 指定主窗口位置與大小 root.geometry('200x100') # 不允許改變窗口大小 root.resizable(False, False) # 變量X和Y用來記錄鼠標左鍵按下的位置 self.X = tkinter.IntVar(value=0) self.Y = tkinter.IntVar(value=0) self.selectPosition = None # 屏幕尺寸 screenWidth, screenHeight = pyautogui.size() # 創建頂級組件容器 self.top = tkinter.Toplevel(root, width=screenWidth, height=screenHeight) self.canvas = tkinter.Canvas(self.top, bg='white', width=screenWidth, height=screenHeight) # 顯示全屏截圖,在全屏截圖上進行區域截圖 self.image = tkinter.PhotoImage(file=filename) self.canvas.create_image(screenWidth // 2, screenHeight // 2, image=self.image) # ---------------------------------------------------------------------------------------------- # 鼠標左鍵按下的位置 def onLeftButtonDown(event): self.X.set(event.x) self.Y.set(event.y) # 開始截圖 self.sel = True self.canvas.bind('<Button-1>', onLeftButtonDown) # ---------------------------------------------------------------------------------------------- # 鼠標左鍵移動,顯示選取的區域 def onLeftButtonMove(event): if not self.sel: return global lastDraw try: # 刪除剛畫完的圖形,要不然鼠標移動的時候是黑乎乎的一片矩形 self.canvas.delete(lastDraw) except Exception as e: pass lastDraw = self.canvas.create_rectangle(self.X.get(), self.Y.get(), event.x, event.y, outline='black') self.canvas.bind('<B1-Motion>', onLeftButtonMove) # ---------------------------------------------------------------------------------------------- # 獲取鼠標左鍵抬起的位置,保存區域截圖 def onLeftButtonUp(event): self.sel = False try: self.canvas.delete(lastDraw) except Exception as e: pass sleep(0.1) # 考慮鼠標左鍵從右下方按下而從左上方抬起的截圖 myleft, myright = sorted([self.X.get(), event.x]) mytop, mybottom = sorted([self.Y.get(), event.y]) self.selectPosition = (myleft, myright, mytop, mybottom) pic = ImageGrab.grab((myleft, mytop, myright, mybottom)) # 彈出保存截圖對話框 # self.fileName = tkinter.filedialog.asksaveasfilename( title='保存截图', filetypes=[('PNG files', '*.png')]) # if self.fileName: # pic.save(self.fileName + '.png') # 關閉當前窗口 # print(left, ' ', top,' ',right,' ',bottom) self.top.destroy() # 開始截圖 self.canvas.bind('<ButtonRelease-1>', onLeftButtonUp) self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)
def __init__(self): self._set_board_window = tkinter.Toplevel() self._set_board_window.resizable(width = False, height = False) self._row_var = tkinter.IntVar() self._col_var = tkinter.IntVar() size_label = tkinter.Label( master = self._set_board_window, text = 'Please set up the empty board', font = DEFAULT_FONT) size_label.grid( row = 0, column = 0, columnspan = 3, padx = 10, pady = 10, sticky = tkinter.W) row_label = tkinter.Label( master = self._set_board_window, text = 'Rows:', font = ('Arial', 10)) row_label.grid( row = 1, column = 0, padx = 10, pady = 10, sticky = tkinter.W) column_label = tkinter.Label( master = self._set_board_window, text = 'Columns:', font = ('Arial', 10)) column_label.grid( row = 3, column = 0, padx = 10, pady = 10, sticky = tkinter.W) turn_label = tkinter.Label( master = self._set_board_window, text = 'Starting Player:', font = ('Arial', 10)) turn_label.grid( row = 5, column = 0, padx = 10, pady = 10, sticky = tkinter.W) win_method_label = tkinter.Label( master = self._set_board_window, text = 'How to win:', font = ('Arial', 10)) win_method_label.grid( row = 6, column = 0, padx = 10, pady = 10, sticky = tkinter.W) button_frame = tkinter.Frame(master = self._set_board_window) button_frame.grid( row = 7, column = 0, columnspan = 4, padx = 10, pady = 10, sticky = tkinter.E + tkinter.S) ok_button = tkinter.Button( master = button_frame, text = 'Confirm', font = ('Arial', 15), command = self._on_ok_button, height = 1, width = 10) ok_button.grid(row = 7, column = 0, padx = 10, pady = 10, sticky = tkinter.W) back_button = tkinter.Button( master = button_frame, text = 'Cancel', font = ('Arial', 15), command = self._on_back_button, height = 1, width = 10) back_button.grid(row = 7, column = 2, padx = 10, pady = 10, sticky = tkinter.E) self._set_board_window.rowconfigure(0, weight = 1) self._set_board_window.rowconfigure(1, weight = 1) self._set_board_window.rowconfigure(2, weight = 1) self._set_board_window.rowconfigure(3, weight = 1) self._set_board_window.rowconfigure(4, weight = 1) self._set_board_window.rowconfigure(5, weight = 1) self._set_board_window.rowconfigure(6, weight = 1) self._set_board_window.rowconfigure(7, weight = 1) self._set_board_window.columnconfigure(0, weight = 1) self._set_board_window.columnconfigure(1, weight = 1, uniform = 'uni') self._set_board_window.columnconfigure(2, weight = 1, uniform = 'uni') self._set_board_window.columnconfigure(3, weight = 1, uniform = 'uni') self._ok_clicked = False self.create_row_col_options(1, self._row_var) self.create_row_col_options(3, self._col_var) self.create_starting_player_option() self.create_how_to_win_option()
def openOrderPanel(self): rootWindow = tk.Toplevel(self.master) orderPanel = DepthTape(rootWindow)
def openSettingsWindow(self): rootWindow = tk.Toplevel(self.master) settingsWindow = Settings(rootWindow, self, self.brokerPlugins)
def openChart(self): rootWindow = tk.Toplevel(self.master) chart = Chart(rootWindow)
def newWindow(self): ''' defines behaviour of new windows ''' self.newWindow = tk.Toplevel(self.master) self.app = BookWindow(self.newWindow)
def logs(self, cont, swd): if swd == "Aidat": ref = db.reference('odemeler') dat = ref.get() top = tk.Toplevel() e = 1 b = tk.Label(top, text="Villa No", borderwidth=2, relief="groove") d = tk.Label(top, text="Açıklama", borderwidth=2, relief="groove") l = tk.Label(top, text="Ödenen Ay", borderwidth=2, relief="groove") f = tk.Label(top, text="Odenen Tutar", borderwidth=2, relief="groove") g = tk.Label(top, text="Kalan Borç", borderwidth=2, relief="groove") b.grid(row=0, column=0) d.grid(row=0, column=1) l.grid(row=0, column=2) f.grid(row=0, column=3) g.grid(row=0, column=4) for i in dat: if dat[i]["tip"] == "Aidat": b = tk.Label(top, text=dat[i]["villa_no"], borderwidth=2, relief="groove") d = tk.Label(top, text=dat[i]["aciklama"], borderwidth=2, relief="groove") j = tk.Label(top, text=dat[i]["ode_ay"], borderwidth=2, relief="groove") f = tk.Label(top, text=dat[i]["tutar"], borderwidth=2, relief="groove") g = tk.Label(top, text="0", borderwidth=2, relief="groove") b.grid(row=e, column=0) d.grid(row=e, column=1) j.grid(row=e, column=2) f.grid(row=e, column=3) g.grid(row=e, column=4) print(i) e = e + 1 elif swd == "Bilgi": ref = db.reference('villalar') dat = ref.get() top = tk.Toplevel() e = 1 b = tk.Label(top, text="Villa No", borderwidth=2, relief="groove") d = tk.Label(top, text="Ad Soyad", borderwidth=2, relief="groove") l = tk.Label(top, text="Adres", borderwidth=2, relief="groove") f = tk.Label(top, text="Email", borderwidth=2, relief="groove") g = tk.Label(top, text="Telefon", borderwidth=2, relief="groove") b.grid(row=0, column=0) d.grid(row=0, column=1) l.grid(row=0, column=2) f.grid(row=0, column=3) g.grid(row=0, column=4) for i in dat: b = tk.Label(top, text=dat[i]["villa_no"], borderwidth=2, relief="groove") d = tk.Label(top, text=dat[i]["ad_soyad"], borderwidth=2, relief="groove") j = tk.Label(top, text=dat[i]["address"], borderwidth=2, relief="groove") f = tk.Label(top, text=dat[i]["email"], borderwidth=2, relief="groove") g = tk.Label(top, text=dat[i]["tel_no"], borderwidth=2, relief="groove") b.grid(row=e, column=0) d.grid(row=e, column=1) j.grid(row=e, column=2) f.grid(row=e, column=3) g.grid(row=e, column=4) print(i) e = e + 1 elif swd == "Odeme": ref = db.reference('odemeler') dat = ref.get() top = tk.Toplevel() e = 1 b = tk.Label(top, text="Villa No", borderwidth=2, relief="groove") d = tk.Label(top, text="Açıklama", borderwidth=2, relief="groove") l = tk.Label(top, text="Ödenen Ay", borderwidth=2, relief="groove") f = tk.Label(top, text="Odenen Tutar", borderwidth=2, relief="groove") g = tk.Label(top, text="Kalan Borç", borderwidth=2, relief="groove") b.grid(row=0, column=0) d.grid(row=0, column=1) l.grid(row=0, column=2) f.grid(row=0, column=3) g.grid(row=0, column=4) for i in dat: if dat[i]["tip"] == "Ekstra": b = tk.Label(top, text=dat[i]["villa_no"], borderwidth=2, relief="groove") d = tk.Label(top, text=dat[i]["aciklama"], borderwidth=2, relief="groove") j = tk.Label(top, text=dat[i]["ode_ay"], borderwidth=2, relief="groove") f = tk.Label(top, text=dat[i]["tutar"], borderwidth=2, relief="groove") g = tk.Label(top, text="0", borderwidth=2, relief="groove") b.grid(row=e, column=0) d.grid(row=e, column=1) j.grid(row=e, column=2) f.grid(row=e, column=3) g.grid(row=e, column=4) print(i) e = e + 1 elif swd == "Harcama": ref = db.reference('harcamalar') dat = ref.get() top = tk.Toplevel() e = 1 b = tk.Label(top, text="Açıklama", borderwidth=2, relief="groove") d = tk.Label(top, text="Tutar", borderwidth=2, relief="groove") b.grid(row=0, column=0) d.grid(row=0, column=1) for i in dat: b = tk.Label(top, text=dat[i]["aciklama"], borderwidth=2, relief="groove") d = tk.Label(top, text=dat[i]["tutar"], borderwidth=2, relief="groove") b.grid(row=e, column=0) d.grid(row=e, column=1) print(i) e = e + 1
def TaxistaInterfaz(): insertT = tk.Toplevel() # Declaracion de variables global varA, varI, enAreaT, enClaveT, enPlacaT, enEstado, enNomproT, enNomconT, enMarcaT, enModeloT, enTelproT, enTelconT, enCorreoproT, enCorreoconT, enObservacionesT enAreaT = tk.StringVar() enClaveT = tk.StringVar() enPlacaT = tk.StringVar() enEstado = tk.StringVar() enNomproT = tk.StringVar() enNomconT = tk.StringVar() enMarcaT = tk.StringVar() enModeloT = tk.StringVar() enTelproT = tk.StringVar() enTelconT = tk.StringVar() enCorreoproT = tk.StringVar() enCorreoconT = tk.StringVar() enObservacionesT = tk.StringVar() # Configuracion de la pantalla insertT.title('Insertar datos de Taxistas') insertT.geometry('1200x1400') insertT.configure(bg='#17202A') #Style styleT = ttk.Style(insertT) styleT.theme_use('alt') styleT.configure("TCombobox", background='#566573', fieldbackground='#566573', selectbackground='#566573') styleT.map('TCombobox', fieldbackground=[('readonly', '#566573')]) insertT.option_add('*TCombobox*Listbox.background', '#566573') # Label tk.Label(insertT, background='#566573', text='Area').place(x=10, y=20, width=100, height=20) tk.Label(insertT, background='#566573', text='Clave').place(x=10, y=80, width=100, height=20) tk.Label(insertT, background='#566573', text='Placa').place(x=10, y=140, width=100, height=20) tk.Label(insertT, background='#566573', text='Estado').place(x=10, y=200, width=200, height=20) # Checklist tk.Label(insertT, background='#566573', text='Nombre del propietario').place(x=10, y=260, width=200, height=20) tk.Label(insertT, background='#566573', text='Nombre del conductor').place(x=10, y=320, width=200, height=20) tk.Label(insertT, background='#566573', text='Marca del radio').place(x=600, y=20, width=200, height=20) tk.Label(insertT, background='#566573', text='Modelo del radio').place(x=600, y=80, width=200, height=20) tk.Label(insertT, background='#566573', text='Telefono del propietario').place(x=600, y=140, width=200, height=20) tk.Label(insertT, background='#566573', text='Telefono del conductor').place(x=600, y=200, width=250, height=20) tk.Label(insertT, background='#566573', text='Correo electronico del propietario').place(x=600, y=260, width=250, height=20) tk.Label(insertT, background='#566573', text='Correo electronico del conductor').place(x=600, y=320, width=250, height=20) tk.Label(insertT, background='#566573', text='Observaciones').place(x=600, y=380, width=200, height=20) # Entry tk.Entry(insertT, background='#566573', textvariable=enAreaT).place(x=50, y=50, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enClaveT).place(x=50, y=110, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enPlacaT).place(x=50, y=170, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enNomproT).place(x=50, y=290, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enNomconT).place(x=50, y=350, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enMarcaT).place(x=650, y=50, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enModeloT).place(x=650, y=110, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enTelproT).place(x=650, y=170, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enTelconT).place(x=650, y=230, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enCorreoproT).place(x=650, y=290, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enCorreoconT).place(x=650, y=350, width=400, height=20) tk.Entry(insertT, background='#566573', textvariable=enObservacionesT).place(x=650, y=410, width=400, height=20) # Combobox Combobox(insertT, textvariable=enEstado, values=('Activo', 'Inactivo'), state="readonly").place(x=50, y=230, width=400, height=20) # Botones tk.Button(insertT, background='#566573', activeforeground='#2C3E50', cursor="hand2", text='Ingresar', command=Taxi.Insertar_DatosT).place(x=300, y=550, width=200, height=40) tk.Button(insertT, background='#566573', activeforeground='#2C3E50', cursor="hand2", text='Limpiar', command=Taxi.Limpiar_EntryT).place(x=550, y=550, width=200, height=40) tk.Button(insertT, background='#566573', activeforeground='#2C3E50', cursor="hand2", text='Regresar', command=insertT.destroy).place(x=800, y=550, width=200, height=40)
def RegistroUsuario(): # Creación de la ventana en tamaño completo ventanaReg = tkinter.Toplevel() ventanaReg.title("Registro de Usuario") # Título de la ventana ventanaReg.geometry( "800x600+280+50" ) # Paso como valor en ancho y alto al método "geometry" ventanaReg.config(bg="#0c3a56") ventanaReg.resizable(0, 0) # Marco para el Registro marco_R = Frame(ventanaReg, bg="light grey") marco_R.place(x=160, y=80, width=480, height=380) # Etiquetas etiqueta_TipoUsuario = Label(marco_R, text="Tipo de usuario", font=("Calibri light", 14, "bold"), fg="black", bg="light gray") etiqueta_TipoUsuario.place(x=70, y=30) etiqueta_Password = Label(marco_R, text="Nombre de usuario", font=("Calibri light", 14, "bold"), fg="black", bg="light gray") etiqueta_Password.place(x=70, y=120) etiqueta_Nombre = Label(marco_R, text="Contraseña", font=("Calibri light", 14, "bold"), fg="black", bg="light gray") etiqueta_Nombre.place(x=70, y=210) # Campos de texto combo_TipoUsuario = ttk.Combobox(ventanaReg, state="readonly") combo_TipoUsuario.place(x=230, y=150, width=350, height=35) combo_TipoUsuario['values'] = ('root', 'admin', 'assistent') cajaTexto_Password = tkinter.Entry(marco_R, font=("Calibri light", 13), bg="white") cajaTexto_Password.place(x=70, y=157, width=350, height=35) cajaTexto_Nombre = tkinter.Entry(marco_R, font=("Calibri light", 13), bg="white") cajaTexto_Nombre.place(x=70, y=247, width=350, height=35) def FunR(): Nombre = cajaTexto_Nombre.get() Password = cajaTexto_Password.get() TipoU = combo_TipoUsuario.get() #persona.CreateUser(Nombre, Password, TipoU) if (combo_TipoUsuario.get() == TipoU and cajaTexto_Password.get() == Password and cajaTexto_Nombre.get() == Nombre): messagebox.showinfo("Aviso", "Usuario Registrado") boton_Reg = tkinter.Button(ventanaReg, text="Regístrarse", command=FunR, fg="white", bg="#722f37", font=("Monospaced", 12), activeforeground="grey", cursor="hand2", relief="flat", overrelief="flat") boton_Reg.place(x=350, y=490) ventanaReg.mainloop()
def getSample(): ## Global variables global continueTest global loadingScreen global stopCounter global plotScreen ## Always make sure this is true at this point continueTest = True ## Loading screen code for the GUI getData.config( state="disabled" ) ## Disable the getData button, so that only one data acquisition can occur at the same time loadingScreen = tk.Toplevel(root) loadingScreen.geometry('300x200') tk.Label(loadingScreen, text="Recieving Data", width="40", height="5", font=(16)).pack() pb = ttk.Progressbar(loadingScreen, length=200, mode='determinate') pb.pack() pb.start(25) stop = tk.Button(loadingScreen, text="Stop Data Collection", command=stopTest, font=(16)) stop.pack() ## If we exit the while loop, check if it because time is over or because continueTest == False, if it is false go to newTest if continueTest == False and stopCounter == 0: stopCounter += 1 print("test stopped 1") newTest() print("Turn pump off") GPIO.output(vacuum_pump, GPIO.LOW) ## If we exit the while loop, check if it because time is over or because continueTest == False, if it is false go to newTest if continueTest == False and stopCounter == 0: stopCounter += 1 print("test stopped 2") newTest() # Begin data collection dataVector1, dataVector2, dataVector3, dataVector4, timeVector = exposeAndCollectData( ) combinedVector = np.column_stack( (timeVector, dataVector1, dataVector2, dataVector3, dataVector4)) # This section of code is used for generating the output file name. The file name will contain date/time of test, as well as concentration values present during test current_time = datetime.datetime.now() year = current_time.year month = current_time.month day = current_time.day createFolders(year, month, day) hour = current_time.hour minute = current_time.minute fileName = str(year) + '-' + str(month) + '-' + str(day) + '_' + str( hour) + ':' + str(minute) ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'XKYJAE_POS37' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'MFBRAQ_POS90' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'SGHKNG_POS20' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'IPCQZE_POS60' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'MCQYFF_POS30' + '.csv', combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'PDJLTR_POS56' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'hamed' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'ERCNSM_POS52' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'bl' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## np.savetxt(r'/home/pi/Documents/Tests/' + str(year) + '/' + str(month) + '/' + str(day) + '/' + str(fileName) + 'LDWXJF_POS10' + '.csv', ## combinedVector, fmt='%.10f', delimiter=',') ## Run vacuum pump for duration of pumping_time to pull sampling air into sensing chamber print("Turn pump on") GPIO.output(vacuum_pump, GPIO.HIGH) pumping_time_counter = 0 stopCounter = 0 ## Sleep second by second, the while loop makes sure to check if the user pressed stop every time its executed ## while (continueTest == True) and (pumping_time_counter < pumping_time): ## time.sleep(1) ## pumping_time_counter = pumping_time_counter + 1 time.sleep(pumping_time) GPIO.output(solenoid, GPIO.HIGH) time.sleep(pumping_time) ## while (continueTest == True) and (pumping_time_counter < pumping_time): ## time.sleep(1) ## pumping_time_counter = pumping_time_counter + 1 GPIO.output(solenoid, GPIO.LOW) GPIO.output(vacuum_pump, GPIO.LOW) # Perform on-line prediction based on 1NN classifier #filepath = '/home/pi/Documents/' #x_train = np.transpose( genfromtxt(filepath + 'train.csv', delimiter=',') ) ## x_test = dataVector1 ## print(len(x_test)) #Y_train = genfromtxt(filepath + 'targets_train_binary.csv', delimiter=',') # Downsampling parameters #desiredTimeBetweenSamples = 1 #timeBetweenSamples = 0.1 #samplingRatio = math.floor(desiredTimeBetweenSamples/timeBetweenSamples) #### Moving average filter (filters noise) #samples = 5 #smoothedData = np.zeros(( len(x_test),1 )) #for j in range(samples, len(x_test)-samples): #sum = 0 #for k in range(-1*samples, samples+1): #sum = sum + x_test[j+k] #smoothedData[j][0] = sum/(2*samples+1) #for j in range(smoothedData.shape[0]): #if smoothedData[j][0] == 0: #smoothedData[j][0] = x_test[j] ## Downsample #downsampledData = np.zeros((1,1)) #for j in range(smoothedData.shape[0]): #if (j%samplingRatio == 0): #if(j == 0): #downsampledData[0][0] = np.array([[smoothedData[j,0]]]) #else: #downsampledData = np.vstack((downsampledData,np.array([[smoothedData[j,0]]]))) # Convert from voltage to fractional change in conductance #for j in range(downsampledData.shape[0]): #V = downsampledData[j][0] #downsampledData[j][0] = V/(R*(V0-V)) #x_test = downsampledData #post_p = True #x_train, x_test = data_representation( x_train, x_test, prep = 4, rep = 'DWT' ) #if post_p == True: #x_train, x_test = featureProcessing(x_train, x_test) #### Fit 1NN classifier based on previously collected data #clf = KNeighborsClassifier(n_neighbors = 1, algorithm = 'brute') #clf.fit(x_train, Y_train) ### Predict label of new test #y_pred = clf.predict(x_test) #if y_pred == 0: #print("Sample predicted as being methane") #elif y_pred == 1: #print("Sample predicted as being natural gas") #else: #print("Classifier error, please check") #if continueTest == False and stopCounter == 0: #stopCounter += 1 #print("test stopped 3") #newTest() ### plot new test ## plotScreen = tk.Toplevel(root) ## plotScreen.geometry('300x200') ## closeButton = tk.Button(plotScreen, text="Close", command=closePlotScreen, font=(16)) ## closeButton.pack() ## ## tk.Label(plotScreen, text="Data plot", width="40", height="5", font=(16)).pack() ## fig = Figure(figsize=(5,5), dpi=100) ## a = fig.add_subplot(111) ## a.plot(x_test) ## ## canvas = FigureCanvasTkAgg(fig, master = plotScreen) ## canvas.get_tk_widget().pack() ## canvas.draw() stopTest()
def CalibrationWindow(): #Open Main Calibration window self.newwindow = tk.Toplevel(self.root) self.app = MainCalibration(self.newwindow)
def special(self): self.sinputWindow = tk.Toplevel(self.master) self.specialInput = Special(self.sinputWindow, self) return
def callback(): def hi(): print("Byee") exit(0) win = tk.Toplevel() #win.configure(bg='#036CB5') lod = Image.open("second.jpg") lod=lod.resize((1400,1000),Image.ANTIALIAS) render = ImageTk.PhotoImage(lod) imag = Label(win, image=render) imag.image = render imag.place(x=0, y=0) menubar = Menu(win) menubar.add_command(label="Exit",font = ('Courier', 14), command=hi) menubar.add_command(label="Compare",font = ('Courier', 14), command=b.comp) menubar.add_command(label="Graph",font = ('Courier', 14), command=g.am) win.config(menu=menubar) def tr(): s = tk.Scrollbar(win) T1 = tkinter.Text(win, height=150, width=100, font=("Courier", 14)) T1.focus_set() s.pack(side=tk.RIGHT, fill=tk.Y) T1.pack(fill=tk.Y) s.config(command=T1.yview) T1.config(yscrollcommand=s.set) file = open("tweeti.txt") data = file.read() file.close() T1.insert(tk.END,data) T1.config(state=DISABLED) ip=T.get("1.0","end-1c") B1 = tkinter.Button(win, text ="Submit", command=tr) B1.place(x = 5, y = 5, height=20, width=80) ltext = Label(win, text=ip) #tkinter.Tk() - TO CREATE NEW WINDOW ckey="42at9XEBHtZED548WGDuLymLx" csecret="cFkCeXVpxAAnJKtgca8ZnQCBLwZQKQlAmVV0ejvD9ECs9wauKs" atoken="725996785559293952-FYFy8coPR9D2oJcLXN3vYz9gRp5sDcy" asecret="p9A2fUJVFmIfUTTmku4Otn117agDrJvHK6s6cHywuRLUQ" try: class listener(StreamListener): def on_data(self, data): all_data = json.loads(data) tweet = all_data["text"] char_list = [tweet[j] for j in range(len(tweet)) if ord(tweet[j]) in range(65536)] tweet='' for j in char_list: tweet=tweet+j sentiment_value, confidence = s.sentiment(tweet) if confidence*100 >= 80: output = open("tweeti.txt","a") op = open("value.txt","a") op.write(sentiment_value) op.write('\n') output.write(sentiment_value) output.write('\n') output.write(tweet) output.write('\n\n') output.close() op.close() return(True) def on_error(self, status): print(status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=[ip]) except: return(True)
def settings(self): win = tk.Toplevel() win.geometry('900x200+1010+35') win.wm_title("Settings") settings01left_heading = tk.Label(win, font=('arial', 16), text='Settings').grid(column=0, row=0, sticky="W") model_text = tk.Label(win, font=('arial', 10), text='Model Classification: ').grid(column=0, row=1, sticky="W") model = ["model_leaf_01.xml"] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.current(0) self.model_input.grid(row=1, column=1, pady=5) model_text = tk.Label(win, font=('arial', 10), text='Model Detection: ').grid(column=0, row=2, sticky="W") model = [""] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.grid(row=2, column=1, pady=5) model_text = tk.Label(win, font=('arial', 10), text='Model Segmentation: ').grid(column=0, row=3, sticky="W") model = ["model_leaf_segmentation_01.xml"] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.current(0) self.model_input.grid(row=3, column=1, pady=5) device_text = tk.Label(win, font=('arial', 10), text='Device: ').grid(column=0, row=4, sticky="W") device = ["MYRIAD", "CPU"] self.device_input = ttk.Combobox(win, values=device, width=30, font=('arial', 10)) self.device_input.current(0) self.device_input.grid(row=4, column=1, pady=5) device_output = self.device_input.get() imagesize_text = tk.Label(win, font=('arial', 10), text='Image Size: ').grid(column=0, row=5, sticky="W") imagesize = ["224x224"] imagesize_input = ttk.Combobox(win, values=imagesize, width=30, font=('arial', 10)) imagesize_input.current(0) imagesize_input.grid(column=1, row=5, pady=5) settings01right_heading = tk.Label(win, font=('arial', 16), text='Upload').grid(column=2, row=0, sticky="W") model_text = tk.Label(win, font=('arial', 10), text='Provider: ').grid(column=2, row=1, sticky="W") model = ["", "OneDrive", "Dropbox"] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.current(0) self.model_input.grid(row=1, column=3, pady=5) model_text = tk.Label(win, font=('arial', 10), text='Url: ').grid(column=2, row=2, sticky="W") model = [""] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.current(0) self.model_input.grid(row=2, column=3, pady=5) model_text = tk.Label(win, font=('arial', 10), text='Key: ').grid(column=2, row=3, sticky="W") model = [""] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.current(0) self.model_input.grid(row=3, column=3, pady=5) model_text = tk.Label(win, font=('arial', 10), text='Project: ').grid(column=2, row=4, sticky="W") model = [""] self.model_input = ttk.Combobox(win, values=model, width=30, font=('arial', 10)) self.model_input.current(0) self.model_input.grid(row=4, column=3, pady=5)
def __init__(self, cfg, gui=None): self.cfg = cfg if gui is None: self.standalone_run = True else: self.gui = gui self.standalone_run = False self.machine_api = self.cfg.machine_api if self.standalone_run: self.root = tkinter.Tk(className="EDITOR") self.root.geometry("+%d+%d" % (self.root.winfo_screenwidth() * 0.1, self.root.winfo_screenheight() * 0.1)) else: # As sub window in DragonPy Emulator self.root = tkinter.Toplevel(self.gui.root) self.root.geometry("+%d+%d" % ( self.gui.root.winfo_rootx() + self.gui.root.winfo_width(), self.gui.root.winfo_y() # FIXME: Different on linux. )) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.base_title = "%s - BASIC Editor" % self.cfg.MACHINE_NAME self.root.title(self.base_title) self.text = ScrolledText(master=self.root, height=30, width=80) self.text.config( background="#ffffff", foreground="#000000", highlightthickness=0, font=('courier', 11), ) self.text.grid(row=0, column=0, sticky=tkinter.NSEW) self.highlighting = TkTextHighlighting(self) self.highlight_currentline = TkTextHighlightCurrentLine(self) #self.auto_shift = True # use invert shift for letters? self.menubar = tkinter.Menu(self.root) filemenu = tkinter.Menu(self.menubar, tearoff=0) filemenu.add_command(label="Load", command=self.command_load_file) filemenu.add_command(label="Save", command=self.command_save_file) if self.standalone_run: filemenu.add_command(label="Exit", command=self.root.quit) self.menubar.add_cascade(label="File", menu=filemenu) editmenu = tkinter.Menu(self.menubar, tearoff=0) editmenu.add_command(label="renum", command=self.renumber_listing) editmenu.add_command(label="reformat", command=self.reformat_listing) editmenu.add_command(label="display tokens", command=self.debug_display_tokens) self.menubar.add_cascade(label="tools", menu=editmenu) # help menu helpmenu = tkinter.Menu(self.menubar, tearoff=0) # helpmenu.add_command(label="help", command=self.menu_event_help) # helpmenu.add_command(label="about", command=self.menu_event_about) self.menubar.add_cascade(label="help", menu=helpmenu) # startup directory for file open/save self.current_dir = os.path.abspath( os.path.join( os.path.dirname(dragonlib.__file__), "..", "BASIC examples", )) self.set_status_bar( ) # Create widget, add bindings and after_idle() update self.text.bind("<Key>", self.event_text_key) # self.text.bind("<space>", self.event_syntax_check) # display the menu self.root.config(menu=self.menubar) self.root.update()
def basic_statistics(df_var, root, save=False): """ Автор: Анатолий Лернер Цель: Формурует, сохраняет и илюстрирует отчёт основные статистики Вход: dataframe, флаг: нужно ли спасти Выход: Нет (новое окно и спасённый файл) """ # dataframe с основной статистикой da_var = df_var.describe(include='all') da_var = da_var.round(2) # describe не обязательно возвращает таблицу с 11'Ю столбцами. Чтоб # обеспечить постояннный размер мы соеденяем его. full_index = [ 'count', 'unique', 'top', 'freq', 'mean', 'std', 'min', '25%', '50%', '75%', 'max'] dm_var = pd.DataFrame(np.NaN, index=full_index, columns=df_var.columns) dm_var.update(da_var) da_var = dm_var.fillna('-') # создаём dataframe для загаловков dh_var = pd.DataFrame({'Prop': X_STATLIST}) # уничтожаем индексы da da_var.reset_index(drop=True, inplace=True) # совмещаем таблицы da_var = pd.concat([dh_var, da_var], axis=1, sort=False) if save: TAG_DICT.update({'Prop': X_STATISTICS}) da_var.columns = [TAG_DICT[x] for x in da_var.columns] del TAG_DICT['Prop'] filename = ANALYSIS_NAMES[0] da_var.to_excel('./Output/' + filename + EXP_FORMAT, index=False) return None # создаём окно и фокусируем его analysis_box = tk.Toplevel() analysis_box.grab_set() analysis_box.focus_set() # размер и название окна analysis_box.title(ANALYSIS_NAMES[0]) analysis_box.geometry("770x370") analysis_box.resizable(False, False) # устанавливаем грид for x_var in range(37): analysis_box.grid_rowconfigure(x_var, minsize=10) analysis_box.rowconfigure(x_var, weight=1) for x_var in range(77): analysis_box.grid_columnconfigure(x_var, minsize=10) analysis_box.columnconfigure(x_var, weight=1) # устанавливаем групповые коробки tk.LabelFrame( analysis_box, text=E_GB_NAME).grid( column=1, row=1, columnspan=75, rowspan=35, sticky='NSEW') col_names = (list(da_var.columns)) analysis_tree = ttk.Treeview( analysis_box, columns=col_names, show="headings", height=3, padding=0, selectmode='none') analysis_tree_ys = ttk.Scrollbar( analysis_box, orient="vertical", command=analysis_tree.yview) analysis_tree_xs = ttk.Scrollbar( analysis_box, orient="horizontal", command=analysis_tree.xview) analysis_tree.configure( yscrollcommand=analysis_tree_ys.set, xscrollcommand=analysis_tree_xs.set) analysis_tree.grid( column=2, row=4, columnspan=71, rowspan=29, sticky='NSEW') analysis_tree_xs.grid( column=2, row=33, columnspan=71, rowspan=2, sticky='NSEW') analysis_tree_ys.grid( column=73, row=4, columnspan=2, rowspan=29, sticky='NSEW') # временно добавляем элемент TAG_DICT.update({'Prop': X_STATISTICS}) # форматируем столбцы for x_var in col_names: analysis_tree.heading(x_var, text=TAG_DICT[x_var]) analysis_tree.column( x_var, width=50 + fnt.Font().measure( TAG_DICT[x_var]), stretch=True, anchor='w' if x_var == 'Prop' else 'e') del TAG_DICT['Prop'] # построчно добовляем ряды в таблицу for x_var in range(da_var.shape[0]): lst = list(da_var.iloc[x_var]) analysis_tree.insert('', 'end', values=lst, tags=str(x_var % 2)) analysis_tree.tag_configure("0", background=W_TREE_ROWCOLOR) # главное окно ждёт наше окно root.wait_window(analysis_box) return None
def OnUploadPress(self): self.CheckIfOnline() if not self.isOnline: return self.statusText.set('Uploading...') self.statusLabel.update_idletasks() dbxDuplicatesList = ['', ''] self.dbxUploadReady = True self.dbxUploadOrNots = [False, False] if self.CheckIfFileExistsDbx(self.csvDbxSave): dbxDuplicatesList[0] = self.csvDbxSave self.dbxUploadReady = False self.dbxUploadOrNots[0] = False self.radioButtons1Var.set(False) else: self.dbxUploadOrNots[0] = True self.radioButtons1Var.set(True) if self.CheckIfFileExistsDbx(self.xlsxDbxSave): dbxDuplicatesList[1] = self.xlsxDbxSave self.dbxUploadReady = False self.dbxUploadOrNots[1] = False self.radioButtons2Var.set(False) else: self.dbxUploadOrNots[1] = True self.radioButtons2Var.set(True) def Upload(): if self.dbxUploadOrNots[0]: with open(path.join(self.savePath, 'Log.csv'), 'rb') as f: self.dbx.files_upload(f.read(), self.csvDbxSave, mode=dropbox.files.WriteMode.overwrite) if self.dbxUploadOrNots[1]: with open(path.join(self.savePath, 'Log.csv'), 'rb') as f: self.dbx.files_upload(f.read(), self.xlsxDbxSave, mode=dropbox.files.WriteMode.overwrite) self.UpdateStatus() def FillCsvColumn(col): tk.Label(f1, text=dbxDuplicatesList[0], relief=tk.RIDGE).grid(row=0, column=col, padx=7, pady=7) tk.Radiobutton(f1, text="Don't Upload", variable=self.radioButtons1Var, value=False).grid(row=1, column=col, pady=7, padx=15, sticky='w') tk.Radiobutton(f1, text="Overwrite", variable=self.radioButtons1Var, value=True).grid(row=2, column=col, pady=7, padx=15, sticky='w') def FillXlsxColumn(col): tk.Label(f1, text=dbxDuplicatesList[1], relief=tk.RIDGE).grid(row=0, column=col, padx=7, pady=7) tk.Radiobutton(f1, text="Don't Upload", variable=self.radioButtons2Var, value=False).grid(row=1, column=col, pady=7, padx=15, sticky='w') tk.Radiobutton(f1, text="Overwrite", variable=self.radioButtons2Var, value=True).grid(row=2, column=col, pady=7, padx=15, sticky='w') def OKButton(): t.destroy() self.dbxUploadReady = True self.dbxUploadOrNots[0] = self.radioButtons1Var.get() self.dbxUploadOrNots[1] = self.radioButtons2Var.get() Upload() def CancelButton(): self.dbxUploadReady = False t.destroy() self.UpdateStatus() if self.dbxUploadOrNots[0] and self.dbxUploadOrNots[1]: Upload() else: t = tk.Toplevel(self.root) t.wm_title('File/s already exists!') tk.Label(t, text='File/s already exists!').grid(row=0, column=0, pady=7, padx=10) f1 = tk.Label(t) f1.grid(row=1, column=0) f2 = tk.Label(t) f2.grid(row=2, column=0) tk.Button(f2, text='Cancel', command=CancelButton).grid(row=0, column=0, padx=10, pady=7) tk.Button(f2, text='OK', command=OKButton).grid(row=0, column=1, padx=10, pady=7) if not True in self.dbxUploadOrNots: FillCsvColumn(0) FillXlsxColumn(1) elif self.dbxUploadOrNots[0] == False: FillCsvColumn(0) elif self.dbxUploadOrNots[1] == False: FillXlsxColumn(0)
def addadvd(self): self.newWindow = tk.Toplevel(self.master) AddDVD(self.newWindow)
def talk(): newroot = tkinter.Toplevel()
def modify(self): self.newWindow = tk.Toplevel(self.master) Modify(self.newWindow)
def open_html(z): path = "images/" + str(df_html['name'][z]).strip() +".png" # code block to restrict multiple windows from opening # if the root is none a new page is created else old page is destroyed and a new page is created global root if root is None: root = tk.Toplevel() else: try: root.destroy() except: pass root = tk.Toplevel() # new frame frame = ScrollableFrame(root) # scrollable frame is made out of normal frame tag_label_name = tk.Label(root, text = df_html['name'][z]+" tag", font=("Calibri", 23, "bold"), fg="#17609a", bd=5).pack(pady=10) tag_label = tk.Label(frame.scrollable_frame, text= "Tag: ", font = "Verdana 13 bold", fg="#17609a", bd=5) tag_label.pack(anchor="w", pady=10, padx =10) tag = str(df_html['tag'][z]) height = 1 width = len(tag) + 1 tag_textbox = tk.Text(frame.scrollable_frame, height=height, bd=1, width=width, font = "Courier 9 bold") tag_textbox.pack(anchor="w", padx=15) tag_textbox.insert(tk.END, tag) tag_textbox.configure(state="disabled") desp_label = tk.Label(frame.scrollable_frame, text= "Definition: ", font = "Verdana 13 bold", fg="#17609a", bd=5) desp_label.pack(anchor="w", padx =10, pady=10) # code block for controlling height and width of the textbox max_width = 76 # max width for text, used to prevent text from going out of frame desp_text = df_html['desp'][z] en = str(desp_text).split("\n") # to detect end of the line height = len(en) width = len(max(en, key=len)) + 1 if width> max_width: width = max_width for l in en: width_l = len(l) if width_l > max_width: height += 1 desp_textbox = tk.Text(frame.scrollable_frame, height=height+1, bd=1, width=width, font = "Courier 9 bold") desp_textbox.pack(anchor="w", fill="x", padx=15) desp_textbox.insert(tk.END, desp_text) desp_textbox.configure(state="disabled") frame.pack() examaple_label = tk.Label(frame.scrollable_frame, text= "Example: ", font = "Verdana 13 bold", fg="#17609a", bd=5) examaple_label.pack(anchor="w", pady=10, padx =10) code = str(df_html['example_input'][z]) #variable to store example c1 = code.split("\t") c1 = " ".join(c1) height = len(c1.split("\n")) width = len(max(c1.split("\n"), key=len))+1 if width > max_width: width = max_width for l in c1.split("\n"): width_l = len(l) if width_l > max_width: height += 1 example_textbox = tk.Text(frame.scrollable_frame, height=height+1, bd=1, width=width, font = "Courier 9 bold") example_textbox.pack( anchor="w", padx=15) example_textbox.insert(tk.END, code) example_textbox.configure(state="disabled") output_label = tk.Label(frame.scrollable_frame, text= "Output: ", font = "Verdana 10 bold", fg="#17609a", bd=5) output_label.pack(anchor="w", pady=10, padx =10) # HTML cant be rendered in the tkinter frame # To show example output for each tag, images of the html pages # are taken and displayed under ouput heading pic = Image.open(path) # output picture stored in "images/" folder width, height = pic.size canvas = tk.Canvas(frame.scrollable_frame, width = width, height = height) canvas.pack() img = ImageTk.PhotoImage(pic) canvas.create_image(5, 10, anchor=tk.NW, image=img) # dummy label to introduce padding at the end of the frame padding = ttk.Label(frame.scrollable_frame) padding.pack() # close function and escape keybinding for the frame def close(event): root.destroy() root.bind("<Escape>", close) root.focus_force() root.resizable(width=False, height=False) try: root.mainloop() root.title("Html references") except: pass
def set_variables(root,UI_var_dict): import tkinter as tk from tkinter import messagebox import pickle import os direc = UI_var_dict['directory'] #Obtain directory in which images are stored if not os.path.exists(direc + '/DataFiles'): os.mkdir(direc + '/DataFiles') #Create base directory to store the data files def set_var(): # Set the variables in the UI variables dictionary UI_var_dict['scale_factor'] = str(scale.get()) #scalefactor for the dataset UI_var_dict['subregion_radius'] = str(radius.get()) # subregion radius for the analysis UI_var_dict['threads'] = str(threads.get()) # # of threads to use UI_var_dict['subregion_shape'] = str(shape.get()) # subergion shape to use UI_var_dict['analysis_type'] = str(Type.get()) # small strain, large strain, or discontinuous strain pixelLen = pix.get() try: pixelLen = float(pixelLen) UI_var_dict['pixelLen'] = str(pixelLen) #pixels per mm setvar.destroy() with open(UI_var_dict['directory'] + '/DataFiles/UI_variables.pickle','wb') as handle: pickle.dump(UI_var_dict, handle, protocol = pickle.HIGHEST_PROTOCOL) #Store dictionary variables in file except ValueError: # If user doesn't input a number messagebox.showwarning('Error','Please enter numeric for Pixels/mm') return #Create window and set up labels for the different user input options setvar = tk.Toplevel(root) tk.Label(setvar,text = 'Pixels/mm').grid(row=0) tk.Label(setvar,text = 'Scale Factor').grid(row=1) tk.Label(setvar,text = 'Subregion radius').grid(row=2) tk.Label(setvar,text = 'Threads').grid(row=3) tk.Label(setvar,text = 'Subregion shape').grid(row=4) tk.Label(setvar,text = 'Analysis type').grid(row=5) #Entry widget for inputting pixels/mm in the images pix = tk.Entry(setvar) pix.insert(1, float(UI_var_dict['pixelLen'])) pix.grid(row = 0, column = 1) #Slider widget for inputting the scalefactor to be used scale = tk.Scale(setvar, from_ = 1, to=6, tickinterval=1, orient = tk.HORIZONTAL) scale.set(int(UI_var_dict['scale_factor'])) scale.grid(row = 1, column = 1, columnspan = 2) #Slider widget for inputting the subset radius radius = tk.Scale(setvar, from_ = 5, to=50, tickinterval=10, orient = tk.HORIZONTAL) radius.set(int(UI_var_dict['subregion_radius'])) radius.grid(row = 2, column = 1, columnspan = 2) #Slider widget for inputting the number of threads to use in computations threads = tk.Scale(setvar, from_ = 1, to=8, tickinterval=2, orient = tk.HORIZONTAL) threads.set(int(UI_var_dict['threads'])) threads.grid(row = 3, column = 1, columnspan = 2) #Select subregion shape - Circle or Square shape = tk.StringVar() shape.set(UI_var_dict['subregion_shape']) tk.Radiobutton(setvar, text = 'Circle', variable = shape, value ='circle').grid(row = 4, column = 1) tk.Radiobutton(setvar, text = 'Square', variable = shape, value ='square').grid(row = 4, column = 2) #Select analysis type - Large or Small strain Type = tk.StringVar() Type.set(UI_var_dict['analysis_type']) tk.Radiobutton(setvar, text = 'Large strain', variable = Type, value ='large').grid(row = 5, column = 1) tk.Radiobutton(setvar, text = 'Small strain', variable = Type, value ='small').grid(row = 5, column = 2) #Button to complete user input done = tk.Button(setvar,text = 'Done', command = set_var) done.grid(row = 6, column = 1, columnspan = 2)
def VVI_window(upper_tk=None): global root_VVI global lrlLabel global urlLabel global vaLabel global vpwLabel global vsLabel global vrpLabel global rsLabel global connectLable index = 0 try: with open("parameterVVI.txt", "r") as parameterFile: read = parameterFile.readlines() except FileNotFoundError: with open("parameterVVI.txt", "w") as parameterFile: while (index < 7): parameterFile.write("N/A\n") index += 1 index = 0 with open("parameterVVI.txt", "r") as parameterFile: read = parameterFile.readlines() #if upper_tk == None: # root_AOO = tk.Tk() #else: root_VVI = tk.Toplevel() root_VVI.title('VVI') root_VVI.geometry('500x500') label = tk.Label(root_VVI, text="Current Mode: VVI", font=("Times New Roman", 14)).place(x=10, y=10) label = tk.Label(root_VVI, text="Lower Rate Limit (ppm):", font=("Times New Roman", 14)).place(x=10, y=80) label = tk.Label(root_VVI, text="Upper Rate Limit (ppm):", font=("Times New Roman", 14)).place(x=10, y=120) label = tk.Label(root_VVI, text="Ventricular Amplitude (V):", font=("Times New Roman", 14)).place(x=10, y=160) label = tk.Label(root_VVI, text="Ventricular Pulse Width (ms):", font=("Times New Roman", 14)).place(x=10, y=200) label = tk.Label(root_VVI, text="Ventricular Sensitivity (V):", font=("Times New Roman", 14)).place(x=10, y=240) label = tk.Label(root_VVI, text="Ventricular Refractory Period (ms):", font=("Times New Roman", 14)).place(x=10, y=280) label = tk.Label(root_VVI, text="Rate Smoothing (%):", font=("Times New Roman", 14)).place(x=10, y=320) connectLable = tk.StringVar() if checkConnect() == 6: connectLable.set("No Pacemaker Connected") label = tk.Label(root_VVI, textvariable=connectLable, font=("Times New Roman", 14), fg="red").place(x=10, y=40) else: connectLable.set("Pacemaker is Connected") label = tk.Label(root_VVI, textvariable=connectLable, font=("Times New Roman", 14), fg="green").place(x=10, y=40) lrlLabel = tk.StringVar() lrlLabel.set(read[0].strip("\n")) #lrlValue is input from user label = tk.Label(root_VVI, textvariable=lrlLabel, font=("Times New Roman", 14)).place(x=320, y=80) urlLabel = tk.StringVar() urlLabel.set(read[1].strip("\n")) #urlValue is input from user label = tk.Label(root_VVI, textvariable=urlLabel, font=("Times New Roman", 14)).place(x=320, y=120) vaLabel = tk.StringVar() vaLabel.set(read[2].strip("\n")) #aaValue is input from user label = tk.Label(root_VVI, textvariable=vaLabel, font=("Times New Roman", 14)).place(x=320, y=160) vpwLabel = tk.StringVar() vpwLabel.set(read[3].strip("\n")) #apwValue is input from user label = tk.Label(root_VVI, textvariable=vpwLabel, font=("Times New Roman", 14)).place(x=320, y=200) vsLabel = tk.StringVar() vsLabel.set(read[4].strip("\n")) #apwValue is input from user label = tk.Label(root_VVI, textvariable=vsLabel, font=("Times New Roman", 14)).place(x=320, y=240) vrpLabel = tk.StringVar() vrpLabel.set(read[5].strip("\n")) #apwValue is input from user label = tk.Label(root_VVI, textvariable=vrpLabel, font=("Times New Roman", 14)).place(x=320, y=280) rsLabel = tk.StringVar() rsLabel.set(read[6].strip("\n")) #apwValue is input from user label = tk.Label(root_VVI, textvariable=rsLabel, font=("Times New Roman", 14)).place(x=320, y=320) #modeWindowButton = tk.Button(root_VVI, text = "Change Mode", command = lambda:[root_VVI.destroy()], width = 13).place(x = 300, y = 10) paraWindowButton = tk.Button(root_VVI, text="Change Parameter", command=VVI_ParameterWindow, width=20, height=2).place(x=200, y=400)