class TopWindow: """ Show the time, number of unfounded bombs, and restart the game """ def __init__(self, window, nr_bombs): self.w = window self.temp = 0 self.is_started = False self.nr_bombs = nr_bombs self.l1 = Label(window, text='00:00') self.l1.grid(row=0, column=2) self.b1 = Button(window, text='Restart', command=self.restart) self.b1.grid(row=0, column=4, columnspan=2, pady=5) self.l2 = Label(window, text=self.nr_bombs) self.l2.grid(row=0, column=7) def start(self): self.temp += 1 stopwatch_time = datetime.utcfromtimestamp(self.temp).strftime('%M:%S') self.l1.config(text=stopwatch_time) self.l1.after(1000, self.start) def restart(self): self.w.destroy() os.startfile("main.pyw") def minus_bomb(self): self.nr_bombs -= 1 self.l2.config(text=self.nr_bombs) def plus_bomb(self): self.nr_bombs += 1 self.l2.config(text=self.nr_bombs)
def AutoRegisterClass_handler(self,Class_Tuple,Class_Info): Waitwindow = tix.Toplevel() Waitwindow.title("자동 신청 - %s"%(Class_Info[3])) Waitwindow.resizable(0,0) self.AutoRegisterEnabled = True Waitwindow.protocol("WM_DELETE_WINDOW",lambda:self.OnAutoWindowClose(Waitwindow)) Label(Waitwindow,text="강좌이름").grid(row=0,column=0) Label(Waitwindow,text=Class_Info[3]).grid(row=0,column=1) Label(Waitwindow,text="현재 보인아이 시간").grid(row=1,column=0) literal = "%d:%d:%d"%(datetime.datetime.now().hour, datetime.datetime.now().minute, datetime.datetime.now().second) clocklabel = Label(Waitwindow, text=literal) clocklabel.grid(row=1, column=1) clocklabel.after(500, lambda: self.UpdateBoiniClock(clocklabel)) Label(Waitwindow, text="자동신청 시간").grid(row=2,column=0) Label(Waitwindow, text="%s"%(time.strftime("%H:%M:%S",time.localtime(self.AutoRegisterTime.get())))).grid(row=2, column=1) Label(Waitwindow, text="상태").grid(row=3, column=0) statuslabel = Label(Waitwindow,text="대기중",fg="green") statuslabel.grid(row=3,column=1) Label(Waitwindow, text="기기등록 확인").grid(row=4,column=0) Label(Waitwindow, textvariable=self.checkincrement).grid(row=4,column=1) textframe = Frame(Waitwindow) textframe.grid(row=5,rowspan=3,column=0,columnspan=2) infotext = Text(textframe, borderwidth=1, relief=SUNKEN) infotext.pack(side=LEFT,expand=YES,fill=BOTH) infotext.insert(END, "자동신청이 이 강좌에 한해 활성화되었습니다. 취소하려면 이 창을 끄면 됩니다.\n") infotext.insert(END, str(Class_Tuple)+"\n") infotext.config(state=DISABLED) textscroll = Scrollbar(textframe,command=infotext.yview) textscroll.pack(side=RIGHT,fill=Y) infotext.config(yscrollcommand=textscroll.set) self.devicecheckcount.set(0) root.after(500,lambda: self.CheckAutoRegister(Waitwindow,statuslabel,infotext, Class_Tuple))
def check_login(self): u_verify = self.username.get() #gets p_verify = self.password.get() #input verif = db_stuf login_user = verif.Login(u_verify, p_verify) self.username_entry.delete(0, END) self.password_entry.delete(0, END) if bool(login_user.login_user()) == True: # self.master.quit() self.master.destroy() def cur_usr(): return u_verify second.starter(usr=cur_usr()) else: lbl2 = Label(self.login, text="Erro, tente novamente", font=("Arial", 10)) lbl2.pack(side="bottom") lbl2.after(900, lbl2.destroy)
class MirrorGreeting(AbstractWidget): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) self.userName = '' self.configuration = {} self.window = False self.greetingDisplay = False def set_user_name(self, name): """Set up the user name from configuration""" self.userName = name def mount_widget(self, configuration): """ add text to display """ self.greetingDisplay = Label(self, fg=configuration['text-color'], bg=configuration['background-color'], font=(configuration['font'], configuration['medium_text_size'])) self.update_display() self.greetingDisplay.pack() def get_greeting_text(self): """ get greeting text depending on the time of the day """ if time.strftime('%p') == 'AM': return 'Good morning %s !' % self.userName return 'Hello %s !' % self.userName def update_display(self): """ recursive function to display the updated greetings """ if isinstance(self.greetingDisplay, Label): self.greetingDisplay.config(text=self.get_greeting_text()) self.greetingDisplay.after(1000, self.update_display)
class GUI: def __init__(self, master): self.master = master master.title("DOK Status") self.label = Label(master, text="DOK Status", bg="red") # Red = Disconnected color self.label.pack() def update_background_color(self): response = requests.get(URL) soup = BeautifulSoup(response.text, 'html.parser') # Check if the string 'Sorry. You are not using Tor.' exists on check.torproject.org not_using_tor_client = soup.findAll( text=compile('Sorry. You are not using Tor.')) # If it does exist, it means that the tor client isn't being used on the router # which means the DoK is disconnected. if not_using_tor_client: color = "red" # Color the background red if the DoK is disconnected. else: color = "green" # Color the background green if the DoK is connected. self.label.configure(bg=color) # Repeat this function every 1,000 milliseconds (1 second) self.label.after(1000, self.update_background_color)
def __init__(self, master=None, title="Error", message="Bad User name or Password\nplease try again!", delai=1250, typ="error"): from tkinter import Label, Tk, PanedWindow from winsound import MessageBeep as snd lst = dict( (("error", 10), ("info", 60), ("warning", 23), ("message", 75))) if master == None: master = Tk() master.title(title) frm = PanedWindow(master) frm.pack() lbl = Label(frm, text=message, width=24) lbl.pack() lbl.focus() if master.title() == title: lbl.after(delai, master.destroy) else: frm.after(delai, frm.destroy) try: snd(lst[typ]) except: print("the arg '", typ, "' must be 'error','info','warning',or 'message'") frm.mainloop()
class CommonFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg='#0077e6') self.createHeading() self.createFooter() self.tick() #common heading def createHeading(self): heading_label = Label(self, text='Spear Phishing Tool', font=('orbitron', 45, 'bold'), fg='white', bg='#0077e6') heading_label.pack(pady=25) def createFooter(self): #bottom frame for time and python logo bottom_frame = Frame(self, relief='raised', borderwidth=3) bottom_frame.pack(fill='x', side='bottom') #python develop sentence python_dev_label = Label(bottom_frame, text='Developed with: ', font=('orbitron', 12, 'bold')) python_dev_label.place(relx=0) #python symbol python_image = PhotoImage(file='images/python.png') python_label = Label(bottom_frame, image=python_image) python_label.place(relx=0.11) python_label.image = python_image self.time_label = Label(bottom_frame, font=('orbitron-Bold', 12)) self.time_label.pack(side='right') #time bar at the bottom def tick(self): current_time = strftime('%I:%M %p').lstrip('0').replace(' 0', ' ') self.time_label.config(text=current_time) self.time_label.after(200, self.tick) #frame for buttons def createButtonFrame(self): self.button_frame = Frame(self, bg='#80c1ff') self.button_frame.pack(fill='both', expand=True) # make sure button frame exists def getButtonFrame(self): try: self.button_frame except NameError: self.createButtonFrame() warn( 'WARNING: Main button frame did not exist... Manually creating button frame' ) return self.button_frame def changePages(self, page_name: str): self.controller.show_frame(page_name)
class MirrorTimer(AbstractWidget): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) self.dateFormat24 = "%H:%M" self.dateFormat12 = "%I:%M %p" self.dayFormat = '%a %d %B' self.configuration = {} self.window = False self.timeDisplay = False self.dayDisplay = False def mount_widget(self, configuration): """ add text to display """ self.timeDisplay = Label(self, fg=configuration['text-color'], bg=configuration['background-color'], font=(configuration['font'], configuration['xlarge_text_size'])) self.timeDisplay.pack(side=TOP, anchor=E) self.dayDisplay = Label(self, fg=configuration['text-color'], bg=configuration['background-color'], font=(configuration['font'], configuration['medium_text_size'])) self.dayDisplay.pack(side=TOP, anchor=E) self.tick() self.update_date() def tick(self): """ recursive function to display real time """ if isinstance(self.timeDisplay, Label): self.timeDisplay.config(text=time.strftime(self.dateFormat24)) self.timeDisplay.after(200, self.tick) def update_date(self): """ recursive function to display the updated day """ if isinstance(self.dayDisplay, Label): self.dayDisplay.config(text=time.strftime(self.dayFormat)) self.dayDisplay.after(1000, self.update_date)
class App: def __init__(self, master): #################################################################### self.button = Button(top, text='START', command=self.convert0) self.button.place(x=50, y=50) self.label = Label(top, text='').grid(row=20, column=5) self.clock = Label(top, font=('times', 20, 'bold'), bg='green') self.clock.place(x=200, y=200) self.isRunning = False GPIO.add_event_detect(21, GPIO.BOTH, callback=self.callback) ################################################################### def convert0(self, tog=[0]): tog[0] = not tog[0] if tog[0]: ######################################### self.button.config(text='START') self.button.configure(bg="blue") self.button.configure(fg="white") self.label = Label(top, text='OFF', bg="blue", fg="white").place(x=150, y=55) ######################################### else: self.button.config(text='STOP') self.button.configure(bg="red") self.button.configure(fg="white") self.label = Label(top, text='OFF', bg="red", fg="red").place(x=150, y=55) self.label = Label(top, text='ON', bg="red", fg="white").place(x=150, y=55) ######################################### def tick(self): # get the current local time from the PC time1 = time.strftime('%I:%M:%S') # if time string has changed, update it self.clock.config(text=time1) # calls itself every 200 milliseconds # to update the time display as needed # could use >200 ms, but display gets jerky if self.isRunning: self.clock.after(200, self.tick) ################################################################### def start(self): self.isRunning = True self.clock.after(200, self.tick) def stop(self): self.isRunning = False def callback(self, channel): if self.isRunning: self.stop() else: self.start()
def pump_control(image: tk.Label): """ Refreshes the pump on/off sign """ pump_on = rtm.is_pump_on() if pump_on: image['image'] = red else: image['image'] = grey image.after(INTERVAL, pump_control, image)
def water_tank(label: tk.Label): """ Refreshes the water tank level label """ value = rtm.get_water_level() label['text'] = '{}/100'.format(round(value, 2)) if value <= 20 or value >= 80: label['fg'] = 'red' else: label['fg'] = 'black' label.after(INTERVAL, water_tank, label)
class UIWidget(Widget): """Represent gui widget of a digital clock.""" def __init__(self, master: Tk, font: Tuple[str, int, str], back_ground: str) -> None: self._widget = Label(master, font=font, bg=back_ground) def create_grid(self) -> None: self._widget.grid() def configure(self, text: str) -> None: self._widget.config(text=text) def continue_after(self, ms: int, option: Callable) -> None: self._widget.after(ms, option)
def ShowClock(self): self.SetServerTimeOffset() clockwindow = tix.Toplevel() clockwindow.resizable(0,0) tix.Label(clockwindow, text="현재 보인아이 시간").pack() clocklabel = Label(clockwindow, text="00:00:00", font=("TkDefaultFont", 50, "bold")) clocklabel.pack(expand=YES, fill=BOTH) clockwindow.update_idletasks() fontscale = Scale(clockwindow,label="글자크기",from_=10, to=200, orient=HORIZONTAL, resolution=10) fontscale.pack(fill=Y,anchor=S) fontscale.set(50) fontscale.bind("<ButtonRelease-1>",lambda x: self.UpdateStandaloneClock(clocklabel, fontscale)) clocklabel.after(100, self.UpdateBoiniClock(clocklabel))
class VideoGUI: def __init__(self, master, cap): self.master = master self.cap = cap self.airplanes = ['UH8', 'L6R', 'G7C', 'S1P', 'JW3', 'A2X'] # set up opencv shit self.lmain = Label(master) self.lmain.pack() # close self.close_b = Button(master, text="Close", command=master.quit) self.close_b.pack(side="bottom") # take picture self.calc_b = Button(master, text="Screen Grab", command=self.grab) self.calc_b.pack(side="bottom") self.show_frame() def grab(self): _, frame = self.cap.read() # convert to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) _, gray = cv2.threshold(gray, 255, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # OCR text = pytesseract.image_to_string(gray) print('found:', text) poss = difflib.get_close_matches(text, self.airplanes) if poss: idx = self.airplanes.index(poss[0]) print('Probably plane', chr(ord('A') + idx), 'with ID', poss[0]) else: print('No ID found') def show_frame(self): _, frame = self.cap.read() oframe = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(oframe) imgtk = ImageTk.PhotoImage(image=img) self.lmain.imgtk = imgtk self.lmain.configure(image=imgtk) self.lmain.after(10, self.show_frame)
def water_level(high_level: tk.Label, low_level: tk.Label): """ Refreshes the water level alarms """ high_level_alarm, low_level_alarm = rtm.get_water_level_alarms() if high_level_alarm: high_level['image'] = red else: high_level['image'] = grey if low_level_alarm: low_level['image'] = red else: low_level['image'] = grey high_level.after(INTERVAL, water_level, high_level, low_level)
def startWatch(): finish = time.perf_counter() x = round(finish - start) elapsed_time = time.strftime('%H:%M:%S', time.gmtime(x)) first_label = Label(my_frame2, text=elapsed_time, font='Times 50') first_label.grid(row=0, column=0, pady=60, padx=100) global solve solve = first_label.after(1000, startWatch)
def OnAutomate(self): Register_window = tix.Toplevel(self.master) Register_window.grab_set() Register_window.resizable(0, 0) clocklabel = Label(Register_window,text="현재 이 컴퓨터의 시간: %s:%s:%s"%(str(datetime.datetime.now().hour).rjust(2,"0"), str(datetime.datetime.now().minute).rjust(2,"0"),str(datetime.datetime.now().second).rjust(2,"0"))) boini_clock_label = Label(Register_window,text="현재 보인아이 홈페이지의 시간: (동기화 중...잠시만 기다려주세요)") clocklabel.grid(row=0,column=0,columnspan=2) boini_clock_label.grid(row=1, column=0, columnspan=2) clocklabel.after(500, lambda: self.UpdateOnAutomateClock(clocklabel, True)) boini_clock_label.after(1000, lambda: self.GetServerTime(boini_clock_label)) Label(Register_window,text="등록시작을 원하는 시간을 현재 보인아이의 시간을 기준으로 24시간:분:초 형식으로 입력해주세요\n(예:8시부터 신청을 원하면 20:00:00). 이 사간부터 프로그램은 될때까지 등록을 계속 합니다.").grid(row=2,column=0,columnspan=2) Label(Register_window, text="시간(24시간 형식):분:초").grid(row=3, column=0) timeentry = Entry(Register_window,textvariable=self.AutoRegisterInput) timeentry.grid(row=3, column=1) timeentry.bind("<KeyRelease>",self.OnAutomateCallBack) #Button(Register_window, text="설정하기", command= lambda: self.OnAutomateCallBack("event")).grid(row=3, column=0, columnspan=2) Label(Register_window, textvariable=self.AutoRegisterInfo).grid(row=4,column=0,columnspan=2) Button(Register_window, text="닫기", command=lambda: Register_window.destroy()).grid(row=5, column=0, columnspan=2)
class LogoFrame: def __init__(self, root): self.timeToNextFrame = 1250 # in ms self.labelImg = None self.img = None self.initFrame(root) def initFrame(self, root): self.img = getPhoto('\\img\\Welcome.png') self.labelImg = Label(root, image=self.img) self.labelImg['image'] = self.img self.labelImg.place(x=0, y=0) self.labelImg.pack() def hideFrame(self): self.labelImg.pack_forget() def setAfterFunc(self, afterFunc): self.labelImg.after(self.timeToNextFrame, afterFunc)
class ClockModule(Module): def __init__(self, root, side): super(ClockModule, self).__init__(root, side) font_big = Font(family="Helvetica", size=72) font_small = Font(family="Helvetica", size=48) sticky = utils.sides[side] self.day = Label(root, font=font_big, fg="white", bg="black", padx=0) self.day.grid(row=0, sticky=sticky) self.fulldate = Label(root, font=font_small, fg="white", bg="black", padx=0) self.fulldate.grid(row=1, column=0, sticky=sticky) self.clock = Label(root, font=font_small, fg="white", bg="black", padx=0) self.clock.grid(row=2, column=0, sticky=sticky) self.time = "" self.dotw = "" self.date = "" self.loop() @utils.overrides(Module) def loop(self): currday = datetime.datetime.today() dotw = calendar.day_name[currday.weekday()] + "," date = currday.strftime("%B %d, %Y") time = currday.strftime("%I:%M %p") if self.time != time: self.time = time self.clock.config(text=time) if self.dotw != dotw: self.dotw = dotw self.day.config(text=dotw) if self.date != date: self.date = date self.fulldate.config(text=date) self.day.after(1000, self.loop)
def register_user(self): pwd = self.password.get() #get() the input uname = self.username.get() #stores input in var try: #tries saving file with username as filename if uname == '' or uname.isspace() == True or len(uname) <= 1: err = Label(self.register, text=""" nome de usuário inválido! tente novamente""", font=("Arial", 10)) err.pack(side="top") err.after(900, err.destroy) elif pwd == '' or pwd.isspace() == True or len(pwd) < 8: err = Label(self.register, text=""" Senha inválida! Precisa conter 8 caráteres""", font=("Arial", 10)) err.pack(side="top") err.after(900, err.destroy) elif db_stuf.Register(uname, pwd).check() == True: label = Label(self.register, text="usuário já cadastrado!", font=("Arial", 10)) label.pack(side="top") self.register.after(900, label.destroy) else: lbl = Label(self.register, text="registrado!", font=("Arial", 10)) lbl.pack(side="top") self.register.after(900, lbl.destroy) except Error as e: print(e) self.username_entry.delete(0, END) #deletes self.password_entry.delete(0, END) #labels
def sensor(sensor_id: str, label: tk.Label, image: tk.Label): """ Refreshes the label and image according to sensor data """ value, alarm = rtm.get_sensor_data(sensor_id) label['text'] = '{}/100'.format(round(value, 2)) if (sensor_id == 'AIR_FLOW' and value <= 20) or (sensor_id != 'AIR_FLOW' and value >= 80): label['fg'] = 'red' image['image'] = red else: label['fg'] = 'black' image['image'] = grey if alarm: image['image'] = red else: image['image'] = grey label.after(INTERVAL, sensor, sensor_id, label, image)
class Clock(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg=ApiSettings.Background) self.time_format = 24 self.date_format = " %A : %d %B %Y" self.time = '' self.time_label = Label(self, font=(ApiSettings.Font, ApiSettings.LargeTextSize), fg=ApiSettings.Foreground, bg=ApiSettings.Background) self.time_label.pack(side=TOP, anchor=W) self.date = '' self.date_label = Label(self, text=self.date, font=(ApiSettings.Font, ApiSettings.MediumTextSize), fg=ApiSettings.Foreground, bg=ApiSettings.Background) self.date_label.pack(side=TOP, anchor=W) Logger.debug("Initialization of Clock class") self.tick() def tick(self): with setlocale(""): current_time = strftime( '%I:%M:%S %p') if self.time_format == 12 else strftime( '%H:%M:%S') current_date = strftime(self.date_format) if current_time != self.time: self.time = current_time self.time_label.config(text=self.time) if current_date != self.date: self.date = current_date self.date_label.config(text=self.date) self.time_label.after(500, self.tick)
lbl = Label(top, font=('Times', 52), bg='black', fg='white') lbl.pack(anchor='center', fill="both", expand=1) time() hoursT = tkinter.Label(top, text="Hours:") hoursE = tkinter.Entry(top) minuteT = tkinter.Label(top, text="Minutes:") minuteE = tkinter.Entry(top) secondT = tkinter.Label(top, text="Seconds:") secondE = tkinter.Entry(top) hoursT.pack(ipadx=1, ipady=1) hoursE.pack(ipadx=1, ipady=2) minuteT.pack(ipadx=2, ipady=1) minuteE.pack(ipadx=2, ipady=2) secondT.pack(ipadx=3, ipady=1) secondE.pack(ipadx=3, ipady=2) label = tkinter.Label(top) string = strftime('%H:%M:%S') label.config(text=string) label.after(1000, time) label = Label(top, font=('Times', 12, 'bold'), bg='light grey', fg='black') label.pack() button = tkinter.Button(top, text="Start Timer", command=updateButton) button.pack() top.title(" Alarm Timer ") top.mainloop()
class GUI_Meteo(tk.Frame): def __init__(self): tk.Frame.__init__(self, master=None, width=700, height=500, background='black') self.pack(expand=YES) self.creer_nextbutton() self.creer_prevbutton() self.creer_exitbutton() self.creer_page1() #def :defilement du numero de page def _nextPage(self): global PageNbr, NBRE_PAGE_MAX, PrevPage if PageNbr < NBRE_PAGE_MAX: PageNbr = PageNbr + 1 else: PageNbr = 1 self._changement_page() def _prevPage(self): global PageNbr, NBRE_PAGE_MAX, PrevPage if PageNbr == 1: PageNbr = NBRE_PAGE_MAX else: PageNbr = PageNbr - 1 self._changement_page() #changement de l'affichage de page, pas terrrible peux mieux faire en rajoutant un if avec prevPage def _changement_page(self): global PageNbr, PrevPage if PrevPage == 1: self.page1.grid_forget() elif PrevPage == 2: self.page2.grid_forget() if PageNbr == 2: self.creer_page2() elif PageNbr == 1: self.creer_page1() PrevPage = PageNbr #mise a jour de l'heure : def _maj_heure(self): myDatetime = datetime.datetime.now() heure = myDatetime.strftime('%H:%M:%S') return heure def _refresh_heure(self): new_heure = self._maj_heure() self.label_heure.configure(text=new_heure) self.label_heure.after(1000, self._refresh_heure) #creation données du jour à afficher def _create_data_list(self): data_list = data_forecast() return data_list #transformation des icones des previsions def _create_icon(self, data_list): #modification du format de fichier icon_path = "/home/pi/meteo/img/GIF/150x150/{}.gif".format(data_list) if os.path.isfile(icon_path): icon_today = tk.PhotoImage(file=icon_path) else: print(icon_path + " N'existe pas!") return icon_today def _create_data_today_text(self): #import depuis la base sql update_data_today = today_data() #mise a jour des variables # myDatetime = datetime.datetime.now() # myString = myDatetime.strftime('%H:%M:%S') data_text = f""" {datetime.date.today()} température : {update_data_today.get("temperature")} °C pression atmos. : {update_data_today.get("pressure")} hPa humidité de l'air : {update_data_today.get("humidity")} % vitesse du vent : {update_data_today.get("wind")} m/s""" return data_text #mise a jour des données du jour : def _update_data_today(self): data_text = self._create_data_today_text() self.label_data_text.configure(text=data_text) self.label_data_text.after(2000, self._update_data_today) def _create_icon_today(self): update_data_today = today_data() #modification du format de fichier icon_path = "/home/pi/meteo/img/GIF/250x250/{}.gif".format( update_data_today.get("today_icon")) if os.path.isfile(icon_path): icon_today = tk.PhotoImage(file=icon_path) else: print(icon_path + " N'existe pas!") return icon_today #mise a jour de l'icone du jour def _refresh_icon_today(self): update_icon_today = self._create_icon_today() self.label_icon.configure(image=update_icon_today) self.label_icon.image = update_icon_today self.label_icon.after(TIME_REFRESH_PAGE1, self._refresh_icon_today) ###################### éléments à afficher ############################################################################# ############################################################################################################## #bouton page suivante en haut à droite def creer_nextbutton(self): self.nextbutton = tk.Button(self, text="next page >", command=self._nextPage) self.nextbutton.grid(row=1, column=3, sticky=NE) #bouton page précédente en haut à gauche def creer_prevbutton(self): self.prevbutton = tk.Button(self, text="prev page <", command=self._prevPage) self.prevbutton.grid(row=1, column=1, sticky=NW) #bouton exit centrer en haut def creer_exitbutton(self): self.exitbutton = tk.Button(self, text="exit", command=self.quit) self.exitbutton.grid(row=1, column=2, sticky=N) ################## page1 ####################################################### def creer_page1(self): self.page1 = tk.Frame(self, background='black', width=700, height=500, borderwidth=2, relief=GROOVE) #texte du titre titrepage1 = Label(self.page1, text="Météo du jour", background='black', fg="WHITE", font=('Comic Sans MS', 20)) titrepage1.grid(row=1, columnspan=3, sticky=N) #affichage de l'icone icon_today = self._create_icon_today() w = icon_today.width() h = icon_today.height() self.label_icon = Label(self.page1, width=w, height=h, image=icon_today) self.label_icon.grid(rowspan=2, sticky=W) self.label_icon.image = icon_today #reference mise en memoire essentiel pour affichage en sortie de fonction self.label_icon.after(TIME_REFRESH_PAGE1, self._refresh_icon_today) #affichage de l'heure : heure = self._maj_heure() self.label_heure = Label(self.page1, text=heure, background='black', fg="WHITE", font=('Comic Sans MS', 22)) self.label_heure.grid(row=2, column=2) self.label_heure.after(1000, self._refresh_heure) #affichage texte des données du jour : data_text = self._create_data_today_text() self.label_data_text = Label(self.page1, text=data_text, background='black', fg="WHITE", font=('Comic Sans MS', 14)) self.label_data_text.grid(row=3, column=2) self.label_data_text.after(TIME_REFRESH_PAGE1, self._update_data_today) #init de la page 1 self.page1.grid(row=2, column=1, columnspan=3) ################## page 2 ################################################################## #création des Labels dédiés pour une journée de revisions def _labels_forecast(self, icon_morning, icon_afternoon, date, temp_morning, temp_afternoon, column): #infos des icones à afficher w_morning = icon_morning.width() h_morning = icon_morning.height() h_afternoon = icon_afternoon.height() w_afternoon = icon_afternoon.width() #icone du matin label_icon_M = Label(self.page2, width=w_morning, height=h_morning, image=icon_morning) label_icon_M.grid(row=3, column=column) label_icon_M.image = icon_morning #reference mise en memoire essentiel pour affichage en sortie de fonction #icone de l après midi label_icon_A = Label(self.page2, width=w_afternoon, height=h_afternoon, image=icon_afternoon) label_icon_A.grid(row=4, column=column) label_icon_A.image = icon_afternoon # date du jour de prevision #conversion de la str time en timestamp timestamp = time.mktime( datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").timetuple()) #conversion du timestamp dasn le nouveau format date = datetime.datetime.fromtimestamp(timestamp).strftime('%a %d/%m') label_date = Label(self.page2, text=date, background='black', fg="WHITE", font=('Comic Sans MS', 10)) label_date.grid(row=2, column=column) #temperature du matin label_temp_M = Label(self.page2, text=str(temp_morning) + ' °C ', background='WHITE', fg="black", font=('Comic Sans MS', 10)) label_temp_M.grid(row=3, column=column, sticky=NE) #temperature de l'apres midi label_temp_A = Label(self.page2, text=(str(temp_afternoon) + ' °C '), background='WHITE', fg="black", font=('Comic Sans MS', 10)) label_temp_A.grid(row=4, column=column, sticky=NE) #icon pour indiqué le moment de la prevision label_temp_AM = Label(self.page2, text='AM', background='WHITE', fg="black", font=('Comic Sans MS', 8)) label_temp_AM.grid(row=3, column=column, sticky=NW) label_temp_PM = Label(self.page2, text='PM', background='WHITE', fg="black", font=('Comic Sans MS', 8)) label_temp_PM.grid(row=4, column=column, sticky=NW) #création de la page 2 def creer_page2(self): #import de la liste de data data_list = self._create_data_list() #création de la page2 self.page2 = tk.Frame(self, background='black', width=700, height=500, borderwidth=2, relief=GROOVE) #texte du titre titrepage2 = Label(self.page2, text="prévisions météo", background='black', fg="WHITE", font=('Comic Sans MS', 20)) titrepage2.grid(row=1, columnspan=5, sticky=N) #forecast day 1: icon_morning = self._create_icon(data_list[1]) icon_afternoon = self._create_icon(data_list[4]) self._labels_forecast(icon_morning, icon_afternoon, data_list[3], data_list[2], data_list[5], 1) #forecast day 2: icon_morning = self._create_icon(data_list[7]) icon_afternoon = self._create_icon(data_list[10]) self._labels_forecast(icon_morning, icon_afternoon, data_list[9], data_list[8], data_list[11], 2) #forecast day 3: icon_morning = self._create_icon(data_list[13]) icon_afternoon = self._create_icon(data_list[16]) self._labels_forecast(icon_morning, icon_afternoon, data_list[15], data_list[14], data_list[17], 3) self.page2.grid(row=2, column=1, columnspan=3)
class CameraFrame(LabelFrame): def __init__(self, master): super(CameraFrame, self).__init__(master, width=300, height=140, text="Camera", font=("Helvetica", 14)) self.movementComms = None self._job1 = None self._job2 = None self.root = master self.HorizontalSlider = Scale(self, from_=180, to=0, width=35, orient=HORIZONTAL, command=self.updateHorizontal, showvalue='false') self.VerticalSlider = Scale(self, from_=180, to=0, width=35, command=self.updateVertical, showvalue='false') self.CenterButton = Button(self, text="Center", command=self.center, font=("Helvetica", 14)) self.HorizontalSlider.grid(row=0, column=1, sticky=EW + S) self.VerticalSlider.grid(row=1, column=0, sticky=NS + E) self.CenterButton.grid(row=0, column=0, sticky=NSEW, ipadx=2, ipady=2) self.HorizontalSlider.set(90) self.VerticalSlider.set(90) self.Video = Label(self, anchor='nw', padx=0, pady=0) self.Video.grid(row=1, column=1, sticky='nsew', padx=5, pady=5) self.FaceRecognitionOpenCV = IntVar() self.OpenCVCheckBox = Checkbutton(self, text="OpenCV face detection", variable=self.FaceRecognitionOpenCV, font=("Helvetica", 14)) self.OpenCVCheckBox.grid(row=2, column=0, columnspan=2, sticky=NW) self.bind('<Configure>', self.resize) imgtk = ImageTk.PhotoImage(image=self.empty_image(480, 640)) self.Video.lmain = imgtk self.Video.configure(image=imgtk) self.LastImage = None def SetMovement(self, movementComms): self.movementComms = movementComms def new_image(self, LastImage): try: if (self.LastImage is not None): self.LastImage = LastImage else: self.LastImage = LastImage self.video_stream() except Exception as ex: traceback.print_exc() print(ex) def video_stream(self, width=480, height=640): cv_image = cv2.cvtColor(self.LastImage, cv2.COLOR_BGR2RGB) if self.FaceRecognitionOpenCV.get() == 1: cv_image = FaceDetection.detect(cv_image) pil_image = Image.fromarray(cv_image) imgtk = ImageTk.PhotoImage(image=pil_image) self.Video.lmain = imgtk self.Video.configure(image=imgtk) self.Video.after(10, self.video_stream) def resize(self, event): if (self.LastImage != None): self.video_stream(event.width, event.height) def empty_image(self, width, height): img_a = np.zeros([width, height, 3], dtype=np.uint8) img_a.fill(55) img = Image.fromarray(img_a, 'RGB') return img def updateHorizontal(self, event): if self._job1: self.root.after_cancel(self._job1) self._job1 = self.root.after(500, self.sendUpdateHorizontalValue) def sendUpdateHorizontalValue(self): if self.movementComms is not None: self.movementComms.CameraLeftRightSetValue( self.HorizontalSlider.get()) def updateVertical(self, event): if self._job2: self.root.after_cancel(self._job2) self._job2 = self.root.after(500, self.sendUpdateVerticalValue) def sendUpdateVerticalValue(self): if self.movementComms is not None: self.movementComms.CameraUpDownSetValue(self.VerticalSlider.get()) def center(self): self.HorizontalSlider.set(90) self.VerticalSlider.set(90) self.sendUpdateHorizontalValue() self.sendUpdateVerticalValue()
class pomodoro(): def __init__(self): self.path = Path(__file__).parent.absolute( ) #Get the absolute path to the directory of the current file self.toaster = ToastNotifier() self.window = Tk() self.timer = [ 0, 0 ] #List for keeping and calculating minutes and seconds (timer [0] - minutes, timer [1] - seconds) self.pomodorocount = 0 #Variable for storing performed pomodoros self.status = 1 #Variable for determining the state (0 - work, 1 - short break, 2 - long break) self.after_id = 0 #Variable to storing the identifier of the after method (to stop the timer, we will transmit this identifier to the after_cancel method) self.timestr = str(self.timer[0]) + ':' + str( self.timer[1]) #Variable type str to update label_time self.window.title('Pomodoro Timer') self.window.geometry('400x400') self.label_work = Label(text='Pomodoro') self.frame_work = Frame() #Used to group widgets self.entry_m_work = Entry(self.frame_work, width=5) self.entry_s_work = Entry(self.frame_work, width=5) text = '25' self.entry_m_work.insert( 0, text) #We prescribe the initial values in the input field text = '0' self.entry_s_work.insert(0, text) self.label_relax = Label(text='Short break') self.frame_relax = Frame() self.entry_m_relax = Entry(self.frame_relax, width=5) self.entry_s_relax = Entry(self.frame_relax, width=5) text = '5' self.entry_m_relax.insert(0, text) text = '0' self.entry_s_relax.insert(0, text) self.label_longrelax = Label(text='Long break') self.frame_longrelax = Frame() self.entry_m_longrelax = Entry(self.frame_longrelax, width=5) self.entry_s_longrelax = Entry(self.frame_longrelax, width=5) text = '30' self.entry_m_longrelax.insert(0, text) text = '0' self.entry_s_longrelax.insert(0, text) self.label_infopomodoro = Label(text='Number of pomodoros: {}'.format( self.pomodorocount), font=("Times", 20)) self.label_infostatus = Label(text='Get started!', fg="blue", font=("Times", 20)) self.label_time = Label(text='0:0', font=("Area", 100)) self.frame_button = Frame() self.button_start = Button(self.frame_button, width=5, text='Start', command=self.start) self.button_reset = Button(self.frame_button, width=5, text='Reset', command=self.reset, state='disabled') def pack(self): #Use the pack method for widgets in this function self.label_work.pack() self.frame_work.pack() self.entry_m_work.pack(side=LEFT) self.entry_s_work.pack(side=LEFT) self.label_relax.pack() self.frame_relax.pack() self.entry_m_relax.pack(side=LEFT) self.entry_s_relax.pack(side=LEFT) self.label_longrelax.pack() self.frame_longrelax.pack() self.entry_m_longrelax.pack(side=LEFT) self.entry_s_longrelax.pack(side=LEFT) self.label_infopomodoro.pack() self.label_infostatus.pack() self.label_time.pack() self.frame_button.pack() self.button_start.pack(side=LEFT) self.button_reset.pack(side=LEFT) def start(self): #The function is called by pressing the Start button self.button_start.configure(state='disabled') self.button_reset.configure(state='active') self.status_check() def tick(self): #Timer update function self.timer[1] -= 1 #We subtract one second if self.timer[1] == -1: #When the value becomes -1: self.timer[1] = 59 #Set the value of seconds in 59 self.timer[0] -= 1 #We subtract one minute self.timestr = str(self.timer[0]) + ':' + str( self.timer[1] ) #We combine values from the list to the timestr variable in the form of 0:0 self.label_time.configure(text=self.timestr) #We update the label self.status_check() #Call the check function def status_check(self): #Status check function (work or break) if self.timestr == '0:0': #Checking whether the timer time ended if self.status == 0: #If you work self.pomodorocount += 1 #Add 1 to performed pomodoros self.label_infopomodoro.configure( text='Number of pomodoros: {}'.format(self.pomodorocount), font=("Times", 20)) #We update the label if self.pomodorocount % 4 == 0: #If the number of pomodoros is multiple 4 self.status = 2 #We update status in 2 (long break) self.status_change() #Call the status change function else: self.status = 1 #We update status in 1 (short break) self.status_change() #Call the status change function elif self.status == 1 or self.status == 2: #If we break self.status = 0 #We update status in 0 (work) self.status_change() #Call the status change function else: self.after_id = self.label_time.after( 1000, self.tick ) #If the time did not end, call the after method to execute the tick function every second def status_change(self): #Status change function (check the value in the status variable) if self.status == 0: #Work #Show notification + we prescribe an absolute path to the timer.ico icon (due to lying next to the current file) self.toaster.show_toast("Pomodoro Timer", "Time for work!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure( text='Time for work!', fg="red", font=("Times", 20)) #We update the label with the status self.timer[0] = int(self.entry_m_work.get( )) #Record the values of the input fields to the timer list self.timer[1] = int(self.entry_s_work.get()) elif self.status == 1: #Short break self.toaster.show_toast("Pomodoro Timer", "Time for short break!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure(text='Time for short break!', fg="green", font=("Times", 20)) self.timer[0] = int(self.entry_m_relax.get()) self.timer[1] = int(self.entry_s_relax.get()) elif self.status == 2: #Long break self.toaster.show_toast("Pomodoro Timer", "Time for long break!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure(text='Time for long break!', fg="lime", font=("Times", 20)) self.timer[0] = int(self.entry_m_longrelax.get()) self.timer[1] = int(self.entry_s_longrelax.get()) if self.timer[ 1] > 60: #If in the input field of seconds it was a value of more than 60, then set the value of 60 self.timer[1] = 60 if self.timer[ 1] == 0: #If there was zero in the input field in the input field, then we subtract out of 1 minutes and set the value of seconds in 60 self.timer[0] -= 1 self.timer[1] = 60 self.after_id = self.label_time.after( 1000, self.tick ) #Call an after method for executing the tick function every second def reset(self): #Timer restart function - set the initial values of variables, update labels and buttons self.button_reset.configure(state='disabled') self.label_time.after_cancel( self.after_id) #Stop the timer for the after identifier self.timer = [0, 0] self.pomodorocount = 0 self.status = 1 self.after_id = 0 self.timestr = str(self.timer[0]) + ':' + str(self.timer[1]) self.label_time.configure(text=self.timestr) self.button_start.configure(state='active') self.label_infopomodoro.configure( text='Number of pomodoros: {}'.format(self.pomodorocount), font=("Times", 20)) self.label_infostatus.configure(text='Get started!', fg="blue", font=("Times", 20)) def mainloop(self): self.window.mainloop()
class GameUI(StartUI): def __init__(self, master): self.master = master self.canvas = Canvas(master, width=WIDTH, height=HEIGHT, bg="white") self.canvas.pack(fill=BOTH, side=TOP) # Buttons self.check_mode = False self.check_button = Button(master, text="Check", fg='green', command=self.check_sudoku) self.check_button.pack(side=RIGHT) self.solve_button = Button(master, text="Solve", fg='blue', command=self.draw_solution) self.solve_button.pack(side=RIGHT) self.hint_button = Button(master, text="Hint", fg='purple', command=self.give_hint) self.hint_button.pack(side=LEFT) # Get a sudoku and its solution. self.original_sudoku = sudoku_solver.randomized_sudoku( number_of_removed_cells) # Original self.user_sudoku = deepcopy(self.original_sudoku) # User will change self.sudoku_solution = sudoku_solver.solve_sudoku( deepcopy(self.user_sudoku)) # Solution of the sudoku self.canvas.bind("<Button-1>", self.canvas_click) self.canvas.bind("<Key>", self.canvas_key) # Start some variables self.row, self.column = 0, 0 self.start_time = time.time() # Set up the clock self.clock = Label(master) self.clock.pack(side=BOTTOM) self.__draw_clock() self.__draw_sudoku() def __draw_grid(self): """ Draws grid divided with blue lines into 3x3 squares """ for i in range(10): color = "black" if i % 3 == 0 else "gray" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_numbers(self): """ Fills the grid with sudoku numbers """ self.canvas.delete("numbers") for i in range(9): for j in range(9): number = self.user_sudoku[i][j] if number != 0: if number == self.original_sudoku[i][j]: color = "black" # Highlight numbers that are wrong elif self.check_mode and \ number != self.sudoku_solution[i][j]: color = "red" else: color = "blue" x = MARGIN + SIDE / 2 + i * SIDE y = MARGIN + SIDE / 2 + j * SIDE self.canvas.create_text(x, y, text=number, tags="numbers", fill=color) def canvas_click(self, event): ''' Selects which cell has been clicked ''' x, y = event.x, event.y if WIDTH - MARGIN > x > MARGIN and HEIGHT - MARGIN > y > MARGIN: self.canvas.focus_set() row = (x - MARGIN) // SIDE column = (y - MARGIN) // SIDE if (row, column) == (self.row, self.column): (self.row, self.column) = (-1, -1) elif self.original_sudoku[row][column] == 0: self.row, self.column = row, column self.__draw_red_box() def __draw_red_box(self): ''' Draw red box around the cell selected ''' self.canvas.delete("red_square") if self.row >= 0 and self.column >= 0: x0 = MARGIN + self.row * SIDE + 1 y0 = MARGIN + self.column * SIDE + 1 x1 = MARGIN + (self.row + 1) * SIDE - 1 y1 = MARGIN + (self.column + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="red_square") def canvas_key(self, event): ''' Selects which key has been pressed ''' number = event.char if number in "1234567890" and self.row >= 0 and self.column >= 0: self.user_sudoku[self.row][self.column] = int(number) self.__draw_sudoku() def __draw_sudoku(self): self.__draw_grid() self.__draw_numbers() self.__draw_red_box() if self.is_sudoku_solved(): self.__draw_victory() def draw_solution(self): ''' Solve the sudoku and draw it ''' self.user_sudoku = self.sudoku_solution self.__draw_sudoku() def give_hint(self): ''' Gives the solution for a random cell ''' while True: i = np.random.randint(0, 9) j = np.random.randint(0, 9) if self.user_sudoku[i][j] == 0: self.user_sudoku[i][j] = self.sudoku_solution[i][j] print('Hint for cell: ', i, ',', j) self.__draw_sudoku() return def check_sudoku(self): self.check_mode = True self.__draw_numbers() self.check_mode = False def is_sudoku_solved(self): for i in range(9): for j in range(9): number = self.user_sudoku[i][j] if number != self.sudoku_solution[i][j]: return False return True def __draw_clock(self): game_time = time.time() - self.start_time min = game_time // 60 sec = game_time % 60 t = "%02d:%02d" % (min, sec) self.clock.config(text=t) # Call this function to update the clock every 200 ms if not (self.is_sudoku_solved()): self.clock.after(200, self.__draw_clock) def __draw_victory(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark blue", outline="blue") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="Congrats!", tags="winner", fill="white", font=("Arial", 32)) self.check_button.destroy() self.hint_button.destroy() self.solve_button.destroy() self.start_button = Button(self.master, text="Restart", fg='purple', command=self.start_game) self.start_button.pack(side=BOTTOM)
import imageio from tkinter import Tk, Label from PIL import ImageTk, Image from pathlib import Path video_name = str(Path().absolute()) + 'spacebot poker 1.mp4' video = imageio.get_reader(video_name) delay = int(1000 / video.get_meta_data()['fps']) def stream(label): try: image = video.get_next_data() except: video.close() return label.after(delay, lambda: stream(label)) frame_image = ImageTk.PhotoImage(Image.fromarray(image)) label.config(image=frame_image) label.image = frame_image if __name__ == '__main__': root = Tk() my_label = Label(root) my_label.pack() my_label.after(delay, lambda: stream(my_label)) root.mainloop()
def keepUpdating(): x = time.time() + (6*3600) current_time = time.strftime('%H:%M:%S', time.gmtime(x)) my_label = Label(my_frame1, text=current_time, font='Times 50') my_label.grid(row=0, column=0, pady=60, padx=110) my_label.after(1000, keepUpdating)
class client(): def __init__(self, master): self.root = master self.root.title(glv.get_variable("APP_NAME")) self.root.minsize(800, 600) set_window_center(self.root, 800, 600) self.root.resizable(False, False) self.root.update() self.var_port = IntVar(value=3333) self.var_address = StringVar(value="0.0.0.0") self.default_timeout = IntVar(value=-999) self.path_remote = StringVar() self.path_local = StringVar() self.inputFileName = "" self.filelist_local = None self.filelist_remote = None self.toolbar_box = None # 工具按钮栏 self.quickbar_box = None # 快速连接栏 self.footer_box = None # 底部状态栏 self.content_box = None # 主要内容视图容器 self.remote_box = None # 远程服务端资源 self.local_box = None # 本地资源 self.ftp_connect = FTP() self.init_view() def init_view(self): """界面""" app_menu.AppMenu(self.root) self.init_frame() self.init_toolbar() self.init_header() self.init_remote() self.init_local() self.init_footer() def init_frame(self): """基本框架""" # 工具按钮栏 self.toolbar_box = Frame(self.root, relief="ridge", bd=1) self.toolbar_box.pack(fill="x", expand=None, side="top", anchor="n") # 快速连接栏 self.quickbar_box = Frame(self.root, relief="ridge", bd=1) self.quickbar_box.pack(fill="x", expand=None, side="top", anchor="n") # 底部状态栏 self.footer_box = Frame(self.root, relief="ridge", bd=1) self.footer_box.pack(fill="x", expand=None, side="bottom", anchor="s") # 主要内容视图容器 self.content_box = Frame(self.root, relief="ridge", bd=0) self.content_box.pack(fill="both", expand=True) # 远程服务端文件列表 self.remote_box = Frame(self.content_box, relief="ridge", bd=0) self.remote_box.pack(fill="both", expand=True, side="right") # 本地文件列表 self.local_box = Frame(self.content_box, relief="ridge", bd=0) self.local_box.pack(fill="both", expand=True, side="left") def init_header(self): """头部栏""" Label(self.quickbar_box, text="主机:").pack(side="left") self.entry_ip = Entry(self.quickbar_box, textvariable=self.var_address) self.entry_ip["width"] = 15 self.entry_ip.pack(side="left") Label(self.quickbar_box, text="账号:").pack(side="left") self.entry_user = Entry(self.quickbar_box, width=15) self.entry_user.pack(side="left") Label(self.quickbar_box, text="密码:").pack(side="left") self.entry_passwd = Entry(self.quickbar_box, show="*", width=15) self.entry_passwd.pack(side="left") Label(self.quickbar_box, text="端口:").pack(side="left") self.entry_port = Entry(self.quickbar_box, textvariable=self.var_port) self.entry_port["width"] = 5 self.entry_port.pack(side="left") button_connect = Button(self.quickbar_box, text="快速连接") button_connect["command"] = self.ftp_login button_connect["width"] = 10 button_connect.pack(side="left") def init_toolbar(self): """工具栏""" button_connect = Button(self.toolbar_box, text="快速连接") button_connect["command"] = self.ftp_login button_connect.pack(side="left") button_disconnect = Button(self.toolbar_box, text="断开") button_disconnect["command"] = self.ftp_quit button_disconnect.pack(side="left") button_reflash = Button(self.toolbar_box, text="刷新") button_reflash["command"] = self.flash_remote button_reflash.pack(side="left") def init_remote(self): """远程文件列表""" btn_bar = Frame(self.remote_box, relief="ridge", bd=1) btn_bar.pack(fill="x", expand=False, side="top") Label(btn_bar, text="远程:").pack(fill="x", expand=None, side="left") path = Entry(btn_bar, textvariable=self.path_remote) path.pack(fill="x", expand=True, side="left") Button(btn_bar, text="打开", command=self.select_path_remote).pack(fill="x", expand=None, side="left") Button(btn_bar, text="重连", command=self.ftp_login).pack(side="left") Button(btn_bar, text="断开", command=self.ftp_quit).pack(side="left") Button(btn_bar, text="刷新", command=self.flash_remote).pack(fill="x", expand=None, side="right") file_list = Frame(self.remote_box, relief="ridge", bd=0) file_list.pack(fill="both", expand=True, side="top") # Listbox # self.filelist_remote = Listbox(self.remote_box) # self.filelist_remote.bind("<Double-Button-1>", self.click_db) # self.filelist_remote.pack(fill="both", expand=True, side="top") tree = Treeview(file_list, show="headings") # 列索引ID tree["columns"] = ("pra", "id", "user", "group", "size", "date", "name") # 表头设置 tree.heading("pra", text="权限") tree.heading("id", text="ID") tree.heading("user", text="用户") tree.heading("group", text="组") tree.heading("size", text="大小") tree.heading("date", text="最后修改日期") tree.heading("name", text="文件名") tree.column("pra", width="100") tree.column("id", width="50", anchor="center") tree.column("user", width="50") tree.column("group", width="50") tree.column("size", width="50") tree.column("date", width="50") tree.column("name", width="50") self.filelist_remote = tree vbar = Scrollbar(file_list, orient="vertical", command=tree.yview) tree.configure(yscrollcommand=vbar.set) tree.grid(row=0, column=0, sticky="nswe") vbar.grid(row=0, column=1, sticky="ns") def init_local(self): """本地文件列表""" btns = Frame(self.local_box, relief="ridge", bd=1) btns.pack(fill="x", expand=False, side="top") Label(btns, text="本地:").pack(fill="x", expand=None, side="left") Entry(btns, textvariable=self.path_local).pack(fill="x", expand=True, side="left") Button(btns, text="打开", command=self.select_path_local).pack(fill="x", expand=None, side="left") Button(btns, text="刷新", command=self.flash_local).pack(fill="x", expand=None, side="right") self.filelist_local = Listbox(self.local_box) self.filelist_local.bind("<Double-Button-1>", self.click_db) self.filelist_local.pack(fill="both", expand=True, side="top") def init_footer(self): """底部状态栏""" Label(self.footer_box, text="欢迎使用").pack(side="left") Label(self.footer_box, text="欢迎使用").pack(fill="x", side="left") ct = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) self.clock = Label(self.footer_box, text=ct) self.clock.pack(side="right") self.clock.after(1000, self.trickit) self.trickit() def trickit(self): ct = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) self.clock["text"] = ct self.clock.update() self.clock.after(1000, self.trickit) def ftp_login(self): self.ftp_connect.connect(self.var_address.get().strip(), int(self.entry_port.get().strip())) self.ftp_connect.login(self.entry_user.get(), self.entry_passwd.get()) self.flash_remote() # 加载列表 def ftp_quit(self): if self.ftp_connect is not None: self.ftp_connect.quit() def ftp_close(self): if self.ftp_connect is not None: self.ftp_connect.close() def flash_remote(self): file_list = [] self.ftp_connect.dir("", file_list.append) for x in file_list: i = x.split() # 或者filename = x.split("\t")[列的起始值:列的终止值] self.filelist_remote.insert("", "end", text="", values=(i[0], i[1], i[2], i[3], i[4], i[5:8], i[-1])) def flash_local(self): filelist = os.listdir(self.path_local.get()) print(filelist) if self.filelist_local.size() > 0: self.filelist_local.delete(0, "end") for i in range(len(filelist)): self.filelist_local.insert("end", filelist[i]) # file_list = [] # self.ftp_connect.dir("", file_list.append) # for x in file_list: # i = x.split() # 或者filename = x.split("\t")[列的起始值:列的终止值] # self.filelist_local.insert( # "", # "end", # text="", # values=(i[0], i[1], i[2], i[3], i[4], i[5:8], i[-1])) def click_db(self, event): self.download() def download(self): inputFileName = self.filelist_remote.get( self.filelist_remote.curselection()) file_handler = open(self.path_remote.get() + "/" + inputFileName, "wb").write self.ftp_connect.retrbinary( "RETR %s" % os.path.basename(inputFileName), file_handler, 1024) def select_path_local(self): path = filedialog.askdirectory() if os.path.isdir(path): self.path_local.set(path) def select_path_remote(self): path = filedialog.askdirectory() if os.path.isdir(path): self.path_remote.set(path) def quit(self): self.root.quit()