class ProgressApp(Tk): def __init__(self): super().__init__() self.value = IntVar() self.value.set(5) self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate", maximum=100, variable=self.value) stop_button = Button(self, text='Stop', command=self.stop_progress_bar) start_button = Button(self, text='Start', command=self.start_progress_bar) increment_button = Button(self, text='Increment', command=self.increment) label = Label(self, text="Progess Bar") label.grid(row=0, column=0) self.progress_bar.grid(row=0, column=1) start_button.grid(row=1, column=0) stop_button.grid(row=1, column=1) increment_button.grid(row=2, column=0) def stop_progress_bar(self): self.progress_bar.stop() def start_progress_bar(self): self.progress_bar.start() self.progress_bar.step(10) def increment(self): self.value.set(self.value.get() + 5)
class GUI: def __init__(self, master): self.master = master self.test_button = Button(self.master, command=self.tb_click) self.test_button.configure(text="Start", background="Grey", padx=50) self.test_button.pack(side=TOP) def progress(self): self.prog_bar = Progressbar(self.master, orient="horizontal", length=200, mode="indeterminate") self.prog_bar.pack(side=TOP) def tb_click(self): self.progress() self.prog_bar.start() self.queue = queue.Queue() ThreadedTask(self.queue).start() self.master.after(100, self.process_queue) def process_queue(self): try: msg = self.queue.get(0) # Show result of the task if needed self.prog_bar.stop() except queue.Empty: self.master.after(100, self.process_queue)
class ProcessBar: # creates a progressbar widget in a thread that runs simultaneous with a predefined other task in a second threat def __init__(self, task, frame, label): self.label = label self.task = task self.frame = frame def make_frame(self): self.label = Label(self.frame, text=self.label) self.label.pack() self.prg_bar = Progressbar(self.frame, orient='horizontal', mode='indeterminate') self.prg_bar.pack() self.prg_bar.start(15) self.t2 = threading.Thread(target=self.task) self.t2.setDaemon( True) # make the thread close when sys.exit is called self.t1 = threading.Thread(target=self.progressbar) self.t1.setDaemon(True) def progressbar(self): while True: if not self.t2.is_alive(): self.prg_bar.stop() break def workflow(self): self.t2.start() self.t1.start()
def load_to_serv(self): """ Загрузить что-то на сервер """ try: file_name: str = filedialog.askopenfilename( initialdir="/home/snorcros", title="Select a File", filetypes=(("Text files", "*.txt*"), ("all files", "*.*"))) if file_name: print(file_name) progressbar = Progressbar(self, orient='horizontal', length=200, mode='indeterminate') progressbar.grid(row=2, column=2) progressbar.config(maximum=100, value=0) load_thread = threading.Thread(target=self.client.load, args=(file_name, )) load_thread.start() progressbar.start(interval=50) while load_thread.is_alive(): self.master.update_idletasks() time.sleep(0.05) file_name = file_name.split(sep='/')[-1] progressbar.stop() progressbar.destroy() ft_done("File " + file_name + " was load to server") self.add_file_to_root(file_name) except ConnectionResetError: ft_error("Server died :c") self.disconnect() except Exception as e: ft_error(e)
def save(self, file_name, row): """ Скачать что-то с сервера """ try: path: str = filedialog.askdirectory( initialdir="/home/snorcros", title="Select a dir for download", mustexist=1) if path: progressbar = Progressbar(self, orient='horizontal', length=150, mode='indeterminate') progressbar.grid(row=row, column=4) progressbar.config(maximum=100, value=0) save_thread = threading.Thread(target=self.client.save, args=(file_name, path)) save_thread.start() progressbar.start(interval=50) while save_thread.is_alive(): self.master.update_idletasks() time.sleep(0.05) progressbar.stop() progressbar.destroy() ft_done("File " + file_name + " was download to " + path) except ConnectionResetError: ft_error("Server died :c") self.disconnect() except Exception as e: ft_error(e)
class SomeClass1(threading.Thread): def __init__(self, q, root, total_rows, loop_time=1.0 / 60): self.q = q self.timeout = loop_time self.total_rows = 50 self.root1 = tk.Tk() self.root_ref = root self.processed = 0 self.progress = Progressbar(root, orient=HORIZONTAL, variable=1, length=120) self.progress.config(maximum=MAX, mode='determinate', value=1) self.progress.step(1) self.progress.grid(row=0, column=1) super(SomeClass1, self).__init__() def onThread(self, function, *args, **kwargs): self.q.put((function, args, kwargs)) def run(self): while True: try: function, args, kwargs = self.q.get(timeout=self.timeout) function(*args, **kwargs) print("run processed") except queue.Empty: self.idle() print("run empty") def idle(self): # put the code you would have put in the `run` loop here print("idle") self.progress = Progressbar(self.root_ref, orient=HORIZONTAL, variable=self.processed, length=120) self.progress.config(maximum=MAX, mode='determinate', value=1) def doSomething(self, processed_row): global processed print("waiting in increment_progress_bar...", processed_row, ":", self.total_rows) #int_processed_row = int(processed_row,10) if (processed_row >= self.total_rows): print("in progress stop") self.progress.stop() self.progress.grid_forget() else: print("in progress step") #self.progress.step(processed_row) self.processed = processed_row print("updated progress bar...") def doSomethingElse(self, b): print("doSomethingElse", b) self.progress.step(1) time.sleep(2)
def progress(self, column, thread): progressbar = Progressbar(self, orient='horizontal', length=150, mode='indeterminate') progressbar.grid(column=column) progressbar.config(maximum=100, value=0) progressbar.start() while thread.is_alive(): self.master.update_idletasks() time.sleep(0.05) progressbar.stop() progressbar.destroy()
class App: file_name = None input_dir = None def __init__(self, master): master.minsize(width=520, height=100) master.maxsize(width=520, height=100) master.title('DocCleaner v1.0') Label(master, text="Directory:").grid(row=0, column=0, sticky='e') global input_dir input_dir = Entry(master, width=60) input_dir.grid(row=0, column=1, padx=2, pady=2, sticky='we', columnspan=9) Button(master, text="Select File", command=self.open_file).grid(row=0, column=10, sticky='e' + 'w', padx=10, pady=2) self.btn = Button(master, text="Process File", command=self.submit_file) self.btn.grid(row=1, column=10, sticky='e' + 'w', padx=10, pady=2) self.progress = Progressbar(master, orient=HORIZONTAL, length=300, mode='indeterminate') @staticmethod def open_file(event=None): input_file_name = tkinter.filedialog\ .askopenfilename(filetypes=[("All Files", "*.*"), ("MS Word", "*.doc;*.docx")]) if input_file_name: global file_name file_name = input_file_name input_dir.delete(0, END) input_dir.insert(0, file_name) def submit_file(self): def real_progress(): self.progress.grid(row=1, column=1, sticky='e') self.progress.start() global input_dir if input_dir.get() != "": tc = TextExtractor(file_name) tc.process_text() time.sleep(5) self.progress.stop() self.progress.grid_forget() input_dir.delete(0, END) self.btn['state'] = 'normal' self.btn['state'] = 'disabled' threading.Thread(target=real_progress).start()
class ChargeProgress(Tk): def __init__(self): super().__init__() self.progress = Progressbar(self, orient=HORIZONTAL, mode='determinate') def runbar(self, event=None): def real_runbar(): self.progress.pack(expand=True, fill=BOTH, side=TOP) self.progress.start(3) time.sleep(0.3) self.progress.stop() self.progress.grid_forget() threading.Thread(target=real_runbar).start()
class App_Build(): def __init__(self, master): self = tkinter.Tk() self.geometry("600x600") self.resizable(width=False, height=False) self.title("FlashLAB") self.configure(background='#6abea7') self.iconbitmap('img/logooooico.ico') self.Btn() # Text # T = Text(self, height=100, width=300) # T.pack() # T.insert(END, "fhsdhfidshf") # Button, Launching progress bar # self.btn = Button(self, text='Deploy', command=self.traitement) # self.btn.grid(row=2,column=10) # self.progress = Progressbar(self, orient=HORIZONTAL,length=500, mode='indeterminate') def Btn(self): self.btn = Button(self, text='Deploy', command=self.traitement) self.btn.grid(row=2, column=10) self.progress = Progressbar(self, orient=HORIZONTAL, length=500, mode='indeterminate') def traitement(self): def real_traitement(): self.progress.grid(row=0, column=0) self.progress.start() # Tps attente avant disparition de la barre time.sleep(10) self.progress.stop() self.progress.grid_forget() self.btn['state'] = 'normal' self.btn['state'] = 'disabled' threading.Thread(target=real_traitement).start()
class ProgressApp(Tk): def __init__(self): super().__init__() self.value = IntVar() self.value.set(0) style = ttk.Style() style.theme_use('clam') style.configure("blue.Horizontal.TProgressbar", background='light green') self.progress_bar = Progressbar(self, orient="horizontal", mode="determinate", style="blue.Horizontal.TProgressbar", maximum=100, variable=self.value) # stop_button = Button(self, text='Stop', command=self.stop_progress_bar) # start_button = Button(self, text='Start', command=self.start_progress_bar) # increment_button = Button(self, text='Increment', command=self.increment) self.start_progress_bar() label = Label(self, text="Progess Bar") label.grid(row=0, column=0) self.progress_bar.grid(row=0, column=1) label2 = Label(self, font=20) label2.config(text=self.value.get()) label2.grid(row=1, column=1) # start_button.grid(row=1,column=0) # stop_button.grid(row=1,column=1) # increment_button.grid(row=2,column=0) def stop_progress_bar(self): self.progress_bar.stop() def start_progress_bar(self): self.progress_bar.start() self.progress_bar.step(100) def increment(self): self.value.set(self.value.get() + 5)
class PantallaEsperaView(View): def __init__(self, controller): super().__init__(Toplevel(), controller) self.construir_main_frame() self.construir_progressbar_frame() self.ocultar_vista() def configurar_root(self): super(PantallaEsperaView, self).configurar_root() self.root.geometry("250x150") def construir_main_frame(self): self.main_frame = Frame(self.root) self.main_frame.pack() def construir_progressbar_frame(self): self.label = Label(self.main_frame) self.label.config(pady=20, padx=20, font=("Helvetica", 10)) self.label.grid(row=0, column=0) self.pb_frame = Frame(self.main_frame) self.pb_frame.config(padx=20, pady=20) # self.pb_frame.grid(row=1, column=0) self.progressbar = Progressbar(self.pb_frame) self.progressbar.config(mode="indeterminate", length=150) self.progressbar.pack() def ocultar_vista(self): self.progressbar.stop() super(PantallaEsperaView, self).ocultar_vista() self.pb_frame.grid_remove() def mostrar_vista(self): self.pb_frame.grid(row=1, column=0) super(PantallaEsperaView, self).mostrar_vista() self.progressbar.start(10)
class MonApp(Tk): def __init__(self): super().__init__() self.btn = Button(self, text='Traitement', command=self.traitement) self.btn.grid(row=0,column=0) self.progress = Progressbar(self, orient=HORIZONTAL,length=100, mode='indeterminate') def traitement(self): def real_traitement(): self.progress.grid(row=1,column=0) self.progress.start() time.sleep(5) self.progress.stop() self.progress.grid_forget() self.btn['state']='normal' self.btn['state']='disabled' threading.Thread(target=real_traitement).start()
class gui(): def __init__(self, tk_obj, num): self.num = num self.root = tk_obj self.button = tk.Button(master=self.root, text='count', command=self.call_count) self.button.pack(side='top') self.v1 = tk.IntVar() self.v1.set(1) if os.path.isfile('result1.pkl'): os.remove('result1.pkl') self.pbar = Progressbar(master=self.root, mode='indeterminate') #self.pbar.grid(row=1,column=1) self.pbar.pack(side='top') def call_count(self): # caller that starts a process and call a top level function self.v1.set(5) count_fn(self.num) self.p1 = Process(target=count_fn, args=(self.num, )) self.p1.start() self.pbar.start(1) self.pbar.after(1, self.onGetValue) def onGetValue(self): #if not os.path.isfile('result1.pkl'): if self.p1.is_alive(): self.pbar.after(1, self.onGetValue) return else: print('DONE') self.pbar.stop()
class MonApp(Tk): def __init__(self): super().__init__() self.initWin() self.initBtn() def initWin(self): self.geometry("600x600") self.resizable(width=False, height=False) self.title("FlashLAB") self.configure(background='#6abea7') self.iconbitmap('img/logooooico.ico') def initBtn(self): self.btn = Button(self, text='Deploy', width=25, command=self.traitement, bg='#6abea7') self.btn.grid(row=5, column=5) self.progress = Progressbar(self, orient=HORIZONTAL, length=500, mode='indeterminate') # Progress bar def traitement(self): def real_traitement(): self.progress.grid(row=5, column=5) time.sleep(3) self.progress.start() time.sleep(3) self.progress.stop() self.progress.grid_forget() self.btn['state'] = 'normal' self.btn['state'] = 'disabled' threading.Thread(target=real_traitement).start()
class MonApp(Tk): def __init__(self): super().__init__() self.btn = Button(self, text='Export employee data', command=self.start) self.btn.grid(row=0,column=0) self.label = Label(self,text="") self.label.grid(row=0, column=1) self.progress = Progressbar(self, orient=HORIZONTAL,length=200, mode='indeterminate') def start(self): def real_start(): self.progress.grid(row=1,column=0) self.progress.start() self.label['text'] = 'Data processing...' time.sleep(5) self.progress.stop() self.progress.grid_forget() self.label['text'] = 'Done.' self.btn['state']='normal' self.btn['state']='disabled' threading.Thread(target=real_start).start()
def splashScreen(): from tkinter import Button, Tk, HORIZONTAL from tkinter.ttk import Progressbar import time import threading root0 = tkinter.Tk() root0.title("OdCrypt v 1.0 ") root0.geometry("500x500") root0.configure(background='turquoise') progress = Progressbar(orient=HORIZONTAL, length=100, mode='indeterminate') progress.pack() progress.start() time.sleep(15) progress.stop() progress.grid_forget() threading.Thread(target=splashScreen).start() encryptionButton() root0.mainloop()
class StatusBar(Frame): def __init__(self, master, progressMax=100, **kwargs): Frame.__init__(self, master, **kwargs) self.label = Label(self, text="Ready...") self.label.pack(anchor=Tkc.W) self.progressVar = IntVar() self.progress = Progressbar(self, mode='determinate', maximum=abs(progressMax), length="150", variable=self.progressVar) def showText(self, message): self.label.configure(text=message) self.progress.stop() self.progress.pack_forget() self.label.pack(anchor=Tkc.W) def showProgress(self): self.progress.configure(mode='determinate') self.label.pack_forget() self.progress.pack(anchor=Tkc.W) self.update_idletasks() def setProgress(self, value): self.progressVar.set(value) self.update_idletasks() def setProgressMax(self, value): self.progress.configure(maximum=abs(value)) def showActivity(self): self.progress.configure(mode='indeterminate') self.progress.start() self.showProgress()
def initialize(): progressbar = Progressbar(root, orient=HORIZONTAL, length=100, mode='indeterminate') progressbar.pack() progressbar.start(10) print("starting") try: filepath = open("path.txt") file = open(filepath.read()) except: file = open(easygui.fileopenbox()) filepath = open("path.txt", "w") filepath.write(file.name) print("threading url") with concurrent.futures.ThreadPoolExecutor() as exe: exe.map(create_urls, file) print("done creating urls") with concurrent.futures.ThreadPoolExecutor() as exe: exe.map(update_printers, printers) print("done") finish = time.perf_counter() print(f'finished in {round(finish-start,2)} seconds') root_frame.title(f'Printer Stats {datetime.now()}') print(len(root.winfo_children())) for frames in printer_frames: frames.destroy() printer_frames.clear() create_frames() progressbar.stop() progressbar.destroy()
class AppTracker(Frame): def __init__(self, parent): Frame.__init__(self, parent) # widgets self._status_label = Label(parent, anchor="w", font=("Gisha", 8), text="", background="#d9d9d9", foreground="#3f3f3f") self._status_label.grid(sticky="NEWS", row=1, rowspan=1, column=0, columnspan=3, ipady=1) self._progress_bar = Progressbar(parent, maximum=40, mode='determinate', orient="horizontal") self._loading_bar = Progressbar(parent, maximum=40, mode='indeterminate', orient="horizontal") # self._preset_button = Button(parent, border=0, font=("Gisha", 8), text="Change preset file..") # self._preset_button.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) @property def loading_bar(self): return self._loading_bar @property def progress_bar(self): return self._progress_bar @property def status_label(self): return self._status_label # @property # def preset_button(self): # return self._preset_button def show_loading_bar(self): self._loading_bar.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) self._loading_bar.update_idletasks() def hide_loading_bar(self): self._loading_bar.stop() self._loading_bar.grid_forget() self._loading_bar.update_idletasks() def show_progress_bar(self): self._progress_bar.grid(sticky="EW", row=1, rowspan=1, column=2, columnspan=1) self._progress_bar.update_idletasks() def hide_progress_bar(self): self._progress_bar.grid_forget() self._progress_bar.update_idletasks() def update_status_label(self, text): self._status_label.configure(text=text) self._status_label.update_idletasks() def update_progress_bar(self, value): self._progress_bar['value'] = value self._progress_bar.update_idletasks() def update_loading_bar(self, value): self._loading_bar.step(value) self._loading_bar.update_idletasks()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, name="frame") self.parent = parent self.initUI() def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.btn1 = Button(self, text='Populate Queue', command=self.on_populate) self.btn1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.btn2 = Button(self, text='Check Queue', command=self.on_check) self.btn2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W + E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E + W + S + N) def on_populate(self): print('populating queue ...') #populate_queue() #lengthy_function() self.p2 = Process(target=populate_queue) self.p2.start() def on_check(self): print('checking queue ...') # iterate through queue and print messages while True: try: result = q.get(timeout=0) except queue.Empty: print('queue is empty') return print(result) '''while True: if queue.Empty: print('queue is empty') return else: print('queue is not empty') result = q.get() print(result)''' '''while True: item = q.get() if item == 'done': break else: print(item)''' def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) self.p1 = Process(target=lengthy_function) self.p1.start() self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue) def onGetValue(self): if (self.p1.is_alive()): self.after(DELAY1, self.onGetValue) return else: try: result = q.get(timeout=0) except queue.Empty: print('queue is empty') return # Do work print(result) self.pbar.stop() self.startBtn.config(state=NORMAL)
class qbtConvertor(Tk): """ GUI Application for migration from uTorrent to qBittorrent """ def __init__(self): Tk.__init__(self) self.title("uT to qBt convertor") #main frame self.main_frame = Frame(self, padding="3 3 12 12") self.main_frame.grid(column=0, row=0, sticky=(N, W, E, S)) self.main_frame.columnconfigure(0, weight=1) self.main_frame.rowconfigure(0, weight=1) #uT part self.ut_data = StringVar() self.ut_label = Label(self.main_frame, text="uT data") self.ut_label.grid(column=0, row=1, sticky=(W)) self.ut_entry = Entry(self.main_frame, width=100, textvariable=self.ut_data) self.ut_entry.grid(column=1, row=1, sticky=(W)) self.ut_button = Button(self.main_frame, text="Browse", command=self.load_file) self.ut_button.grid(column=2, row=1) #qBt part self.qbt_folder = StringVar() self.qbt_label = Label(self.main_frame, text="qBt folder") self.qbt_label.grid(column=0, row=4, sticky=(W)) self.qbt_entry = Entry(self.main_frame, width=100, textvariable=self.qbt_folder) self.qbt_entry.grid(column=1, row=4, sticky=(W)) self.qbt_button = Button(self.main_frame, text="Browse", command=self.open_dir) self.qbt_button.grid(column=2, row=4, sticky=(W, E)) #convertor self.convertor_button = Button(self.main_frame, text="Convert", command=self.convert, width=50) self.convertor_button.grid(column=1, columnspan=2, row=5) self.progress_bar = Progressbar(self.main_frame, orient=HORIZONTAL, length=300, mode="indeterminate") self.progress_bar.grid(column=1, columnspan=3, row=6) #set padding for each element for child in self.main_frame.winfo_children(): child.grid_configure(padx=5, pady=5) def convert(self): message = messagebox if not self.qbt_folder.get() or not self.ut_data.get(): message.showerror("ERROR", "Specify paths!") return self.progress_bar.start() convertor(self.ut_data.get(), self.qbt_folder.get()) self.progress_bar.stop() def load_file(self): file_name = filedialog.askopenfilename(filetypes=(("UT resume file", "*.dat"), ("All", "*"))) if file_name: self.ut_data.set(file_name) def open_dir(self): dir_name = filedialog.askdirectory() if dir_name: self.qbt_folder.set(dir_name)
class Example(Frame): def __init__(self, parent, q): Frame.__init__(self, parent) self.queue = q self.parent = parent self.initUI() def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W+E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N) def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) self.digits = int(self.ent1.get()) self.accuracy = int(self.ent2.get()) self.p1 = Process(target=self.generatePi, args=(self.queue,)) self.p1.start() self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue) def onGetValue(self): if (self.p1.is_alive()): self.after(DELAY1, self.onGetValue) return else: try: self.txt.insert('end', self.queue.get(0)) self.txt.insert('end', "\n") self.pbar.stop() self.startBtn.config(state=NORMAL) except queue.Empty: print("queue is empty") def generatePi(self, queue): getcontext().prec = self.digits time.sleep(10) pi = Decimal(0) k = 0 n = self.accuracy while k < n: pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - (Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5)) - (Decimal(1)/(8*k+6))) k += 1 print(self.p1.is_alive()) queue.put(pi) print("end")
class AppGUI(Frame): def __init__(self, master=None): # Avoiding to send it continuously. self.lock = False Frame.__init__(self, master) self.grid() self.master = master # Setting for ComboBox. self.url_lang_combobox_str = StringVar() self.url_lang_combobox_list = lang_list # UI components. self.receiver_email_text = Label(self, text="Receiver:") self.receiver_email_field = Entry(self, width=50) self.subject_text = Label(self, text='Subject:') self.subject_field = Entry(self, width=50) self.receiver_name_text = Label(self, text='Name:') self.receiver_name_field = Entry(self, width=50) self.url_lang_text = Label(self, text='Link lang:') self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly') self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300) self.send_button = Button(self, text='Send', command=self._send_mail) self.quit_button = Button(self, text='Exit', command=self.__exit) self.log_msg_text = ScrolledText(self) # Attachment. self.mail_attachment_list = attachment_list[:] self.url_lang_link_title = None self.url_lang_link = copy.deepcopy(content_link) # Mailer self._mailer = None # Let Mailer can control components. Mailer.window_content = self self.__create_widgets() def _send_mail(self): if not self.lock: threading.Thread(target=self.__send_mail).start() else: messagebox.showinfo('Warning', "Now it's processing...") def _choose(self, event): # arr = self.url_lang_link.get(self.url_lang_combobox_str.get()) # Get the array by choosing language. pass def _modify_content_url_link(self): link_arr = self.url_lang_link.get(self.url_lang_combobox_str.get()) content = self._mailer.content for index in range(len(link_arr)): content_index = content.index(self.url_lang_link_title[index]) + len(self.url_lang_link_title[index]) content = content[:content_index] + '\n' + link_arr[index] + content[content_index:] self._mailer.content = content return False def _make_mailer(self): self.mail_attachment_list = attachment_list[:] # Clone a list. if atta_lang_list[self.url_lang_combobox.current()]: for i in range(len(self.mail_attachment_list)): # Only from the third file to the end file can change language. if i > 2: # Modify the file name. att = self.mail_attachment_list[i].split('.') self.mail_attachment_list[i] = ''.join([' ', atta_lang_list[self.url_lang_combobox.current()], '.']).join(att) # ** IMPORTANT, we set the content path here!! path = 'content.docx' if self.url_lang_combobox.get() == lang_list[2] or self.url_lang_combobox.get() == lang_list[3]: path = 'content chinese.docx' if debug_log: print(self.mail_attachment_list) # ** IMPORTANT, we have to new an object here. Otherwise, we couldn't check the error checking. return Mailer(content_path=path, attachment_list=self.mail_attachment_list) def __create_widgets(self): """ Construct all of the UI components. """ self.receiver_email_text.grid(row=0, column=0) self.receiver_email_field.grid(row=0, column=1, columnspan=6) self.subject_text.grid(row=1, column=0) self.subject_field.grid(row=1, column=1, columnspan=6) self.subject_field.insert(0, 'Osaka Mariko Apartment Location & Condition') self.receiver_name_text.grid(row=2, column=0) self.receiver_name_field.grid(row=2, column=1, columnspan=6) self.url_lang_text.grid(row=3, column=0) self.url_lang_combobox.grid(row=3, column=2, columnspan=2) self.send_progressbar.grid(row=4, column=0, columnspan=7) self.send_button.grid(row=5, column=2) self.quit_button.grid(row=5, column=3) self.log_msg_text.grid(row=6, column=0, columnspan=7) # Default setting. self.url_lang_combobox.current(0) self.url_lang_combobox.bind("<<ComboboxSelected>>", self._choose) def __exit(self): if not self.lock: self.log_msg_text.insert(END, '\n\n -- Bye Bye --\n') self.master.quit() else: messagebox.showinfo('Error', "Now it's processing...please wait it ;)") @DecoratorThreadLockerApp() @DecoratorErrorCheckAndInitApp() def __send_mail(self): self.send_progressbar.start() # Start processing the progress. ending = 'Welcome to use my application :)' if self._mailer.send_mail() \ else '** Your sending was failed :( please send it again!' self.log_msg_text.insert(END, ending) self.send_progressbar.stop() # Stop processing the progress.
class TextFrameTry02(Frame): def __init__(self, parent, q): Frame.__init__(self, parent) # self.queue = q self.parent = parent # Status XInitThreads(void) # XInitThreads(void) self.initUI() def callback(self): self.root.quit() def initUI(self): # self.root = tk.Tk() # self.root = Tk() # self.root.protocol("WM_DELETE_WINDOW", self.callback) self.parent.title("TextFrameTry02 init title only") #self.title("TextFrameTry02 init title only") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W + E) # self.txt = st.ScrolledText(win) self.txt = st.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E + W + S + N) self.txt.insert(INSERT, "\nJust set up this txt.\n") self.txt.insert(INSERT, "Just set up this txt.\n") self.txt.insert(INSERT, "Just set up this txt.\n") self.txt.insert(INSERT, "Just set up this txt.\n") self.txt.insert(INSERT, "Just set up this txt.\n\n") # aKeyStrk = keyboard.read_key() # aKeyStrk = input() aComment = ''' st.insert(tkinter.INSERT, 'Following Ports are open\n' ) st.insert(tkinter.INSERT, str(portlist)) # Creating scrolled text # area widget text_area = st.ScrolledText(win, wrap = tk.WORD, width = 40, height = 10, font = ("Times New Roman", 15)) text_area.grid(column = 0, pady = 10, padx = 10) # Placing cursor in the text area text_area.focus() ''' # self.txt = st.ScrolledText(self.root, wrap = tk.WORD, width = 40, height = 10, font = ("Times New Roman", 15), grid=(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N)) # self.txt = st.ScrolledText(width = 40, height = 10, font = ("Times New Roman", 15), grid.row(2), grid.column(0), grid.rowspan(4), grid.padx(10), grid.pady(5), grid.columnspan(5), grid.sticky(E+W+S+N), wrap(tk.WORD)) # self.txt = st.ScrolledText(self) # self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E+W+S+N) # text_area = st.ScrolledText(win, #wrap = tk.WORD, #width = 40, #height = 10, #font = ("Times New Roman", #15)) # self.root.mainloop() def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) self.txt.insert(INSERT, "\n\nNow onStart method is running.\n\n") print(self.onStart, "\nNow onStart method is running.\n") self.digits = int(self.ent1.get()) self.accuracy = int(self.ent2.get()) print("\nonStart, start to process generatePi is next.\n") self.txt.insert( INSERT, "\n\nonStart, start to process to generatePi is next.\n\n") self.parent_conn, self.child_conn = multiprocessing.Pipe() # creating new processes # p1 = multiprocessing.Process(target=sender, args=(parent_conn,msgs)) # p2 = multiprocessing.Process(target=receiver, args=(child_conn,)) msgs = "" # self.p1 = Process(target=self.generatePi) # self.p1 = Process(target=self.generatePi, args=(self.queue, )) self.p1 = Process(target=self.generatePi, args=(self.parent_conn, msgs)) self.p1.start() print("\nonStart, start to parallel process to generatePi started.\n") self.txt.insert( INSERT, "\n\nonStart, start to parallel process to generatePi started.\n\n" ) self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue(self.child_conn, msgs)) def onGetValue(self, conn, msgs): # if (self.p1.is_alive()): while self.p1.is_alive(): print( "\nonGetValue finds ------------------------- generatePi Process is alive" ) self.txt.insert( INSERT, "\nonGetValue finds ---------------------- generatePi Process is alive\n" ) # self.after(DELAY1, self.onGetValue(conn, msgs)) # self.onGetValue) # return # msg = conn.recv() # self.txt.insert( msg ) time.sleep(0.1) # else: # while 1: # msg = conn.recv() # if msg == "END": # break # print("Received the message: {}".format(msg)) # try: msg = "msg" msg = conn.recv() print("This should be a pi: ", msg) self.txt.insert(END, "\nThis should be a pi: ") # self.queue.get(0)) self.txt.insert(END, msg) # self.queue.get(0)) self.txt.insert(END, "\n") self.txt.insert(INSERT, "\n\nNow running onGetValue else section.\n\n") print("\nNow running onGetValue else section.\n") self.pbar.stop() self.startBtn.config(state=NORMAL) # except conn.Empty: # queue.Empty: # print("\nqueue is PLACEKEEPER empty\n") # self.txt.insert("\nqueue is PLACEKEEPER empty\n") def generatePi(self, conn, msgs): # def generatePi(self, queue): # def generatePi(self): self.queue, , self.parent_conn, msgs # def sender(conn, msgs): getcontext().prec = self.digits pi = Decimal(0) # pi=999 k = 0 n = self.accuracy # self.txt.delete('1.0', END) # clear the outputtext text widget. 1.0 and # self.txt.delete("1.0", "end-1c") #self.txt.focus() # self.txt.delete(1.0,tk.END) # clear the outputtext text widget. 1.0 and tk.END are neccessary. tk implies the tkinter module. If you just want to add text dont incude that line print("\nNow running generatePi section.\n") ##### self.text.put("---------------") self.txt.insert(INSERT, "\n\n---------------\n\n") self.txt.insert(INSERT, "\n\nNow running generatePi section.\n\n") # aComment=''' while k < n: pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - \ (Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5))- \ (Decimal(1)/(8*k+6))) k += 1 # self.txt.insert(INSERT, 'Following Ports are open\n' ) #st.insert(tkinter.INSERT, 'Following Ports are open\n' ) #st.insert(tkinter.INSERT, str(portlist)) # myvar = "the answer is {}".format(answer) # myvar = "the answer is " + str(answer) insertToTxtfr = ("\nTextFrameTry02 is still alive = " + str(self.p1.is_alive()) + "") # insertToTxtfr = ('TextFrameTry02 is still alive = {}'.format(self.p1.is_alive()) # insertToTxtfr = ('TextFrameTry02 is still alive = XXX') print(insertToTxtfr) # queue.put("TextFrameTry02 is still alive = ", self.p1.is_alive()) # queue.put(" ") # outputtext.insert(tk.END,entryvar) # insert the entry widget contents in the text widget. tk.END is necessary. #self.txt.insert(INSERT, insertToTxtfr) # insert the entry widget contents in the text widget. tk.END is necessary. ##### self.txt.update_idletasks() # XInitThreads # self.txt.pack # conn.send( insertToTxtfr ) time.sleep(0.01) # ''' #### self.txt.update_idletasks() # self.txt.pack print("\nNow running print out pi section.\n") self.txt.insert(INSERT, "\n\nNow running print out pi section.\n\n") print(pi) print(self.parent.title(), " frame end") self.txt.insert(INSERT, "\n\nNow running INSERT out pi section.\n\n") self.txt.insert(INSERT, pi) self.txt.insert(INSERT, "\n\nDone INSERTING and printing out pi.\n\n") print("\nDone INSERTING and printing out pi.\n") conn.send(pi) #queue.put(" ") #queue.put("Putting Pi from generatePi function.\n") #queue.put(pi) #queue.put("Done putting Pi from generatePi function.\n") # queue.put(" ") # self.txt.pack print("Returning from generatePi.") return pi
class AutoEmail_GUI: def __init__(self): self.window = tk.Tk() self.window.geometry("720x550") self.widgets = {} # Language dropdown # Options bar self.opt_bar = tk.Frame(self.window, height=40) languages = list(lang_ctl._ALL.keys()) self.current_lang = StringVar(self.window) self.current_lang.set(languages[0]) self.lang_menu = tk.OptionMenu(self.opt_bar, self.current_lang, *languages) self.lang_menu.pack(side="right", fill="both", expand=True) # Get lang self.text_dict = lang_ctl.get_lang(self.current_lang.get()) self.window.title(self.text_dict["window"]["title"]) select_lang_label = tk.Label( self.opt_bar, text=self.text_dict["window"]["select_lang"]) self.widgets["window/select_lang"] = select_lang_label select_lang_label.pack(side="top", fill="both", expand=True) self.opt_bar.pack(side="top") # Top Frame self.menu_top = tk.Frame(self.window, height=100) # Main text welcome_text = tk.Label(self.menu_top, text=self.text_dict["window"]["body"], anchor="w", justify="left") self.widgets["window/body"] = welcome_text welcome_text.pack() self.menu_top.pack(side="top", fill="both", expand=True) # It's duplicated, we need a list of widgets here self.widgets["window/select_file"] = [] self.widgets["button/open"] = [] self.widgets["window/sample_path"] = [] # Mid Frame self.menu_credentials = tk.Frame(self.window, height=1, width=200) self.menu_credentials_left = tk.Frame(self.menu_credentials) creds = tk.Label(self.menu_credentials, text=self.text_dict["window"]["credentials"], font=("", 16)) self.widgets["window/credentials"] = creds creds.pack(side=tk.TOP, pady=5) # Delete credentials button del_button = tk.Button( self.menu_credentials, text=self.text_dict["button"]["delete"], command=self.reset_credentials, height=2, width=30, ) self.widgets["button/delete"] = del_button del_button.pack(side=tk.TOP, pady=10) tk.Label(self.menu_credentials_left, text="Email", font=("", 10)).pack(side=tk.TOP) self.menu_credentials_left.pack(side=tk.LEFT, padx=(0, 10)) self.menu_credentials_right = tk.Frame(self.menu_credentials) # User Entry self.username = StringVar(self.window) self.username.set("*****@*****.**") self.user_box = tk.Entry(self.menu_credentials_right, textvariable=self.username, width=40) self.user_box.pack(side=tk.TOP) self.menu_credentials_right.pack(side=tk.RIGHT) self.menu_credentials.pack(pady=10) self.menu_mid = tk.Frame(self.window, height=150) self.menu_mid.pack(side="top", fill="both", expand=True) self.menu_mid_left = tk.Frame(self.menu_mid, height=200, width=200, bd=2, relief="groove", padx=5) self.input_file_box(self.menu_mid_left, False, True) self.menu_mid_left.pack(side="left", fill="both", expand=True, padx=10, pady=10) self.menu_mid_right = tk.Frame(self.menu_mid, height=200, width=200, bd=2, relief="groove", padx=5) self.input_file_box(self.menu_mid_right, True, False) self.menu_mid_right.pack(side="right", fill="both", expand=True, padx=10, pady=10) # Bottom Frame self.menu_bot = tk.Frame(self.window, height=50) # Checkbox Menu self.options_menu = tk.Frame(self.window, height=20, relief="groove", bd=2) # Checkbox Debug self.checkbox_debug = tk.BooleanVar(self.window) self.checkbox_debug.set(True) debug_checkbox = tk.Checkbutton( self.options_menu, text=self.text_dict["settings"]["debug"], variable=self.checkbox_debug, command=self.debug_checkbox_clicked, ) self.widgets["settings/debug"] = debug_checkbox debug_checkbox.pack(side="right") # Checkbox SendIfFiles self.checkbox_only_att = tk.BooleanVar(self.window) self.checkbox_only_att.set(True) sendiffiles_checkbox = tk.Checkbutton( self.options_menu, text=self.text_dict["settings"]["only_att"], variable=self.checkbox_only_att, command=self.onlyatt_checkbox_clicked) self.widgets["settings/only_att"] = sendiffiles_checkbox sendiffiles_checkbox.pack(side="left", padx=(5, 0)) self.num_att = tk.Spinbox(self.options_menu, from_=0, to=99) self.num_att.pack(side="left", padx=(0, 0)) # Checkbox OnlyPDF self.checkbox_onlypdf = tk.BooleanVar(self.window) self.checkbox_onlypdf.set(True) onlypdf_checkbox = tk.Checkbutton( self.options_menu, text=self.text_dict["settings"]["only_pdf"], variable=self.checkbox_onlypdf, command=self.onlypdf_checkbox_clicked, ) self.widgets["settings/only_pdf"] = onlypdf_checkbox onlypdf_checkbox.pack(side="left", padx=(20, 20)) self.options_menu.pack(side="top", pady=(0, 10)) # Execute bttton run_button = tk.Button(self.menu_bot, text=self.text_dict["button"]["run"], font=("", 14), command=self.bar_init, height=2, width=30) self.widgets["button/run"] = run_button run_button.pack() self.progressbar = Progressbar(self.menu_bot, mode="indeterminate") self.progressbar.pack(side="bottom", fill="both", expand=True, padx=5, pady=5) self.progressbar.config(value=0, maximum=0) self.menu_bot.pack(fill="both", expand=True) # link function to change dropdown self.current_lang.trace("w", self.change_lang) self.domainCtl = Domain_Ctl() self.window.mainloop() def debug_checkbox_clicked(self): self.domainCtl.set_debug_mode(self.checkbox_debug.get()) def onlyatt_checkbox_clicked(self): self.domainCtl.set_only_with_att(self.checkbox_only_att.get()) def onlypdf_checkbox_clicked(self): self.domainCtl.set_only_pdf(self.checkbox_onlypdf.get()) def select_file(self, isleft: bool, isdir: bool): tk.Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing///// if isdir: filename = askdirectory( ) # show an "Open" dialog box and return the path to the selected file else: filename = askopenfilename( ) # show an "Open" dialog box and return the path to the selected file if isleft: self.left_file.delete(0, tk.END) self.left_file.insert(0, filename) logging.info("Data file selected: " + str(filename)) else: self.right_file.delete(0, tk.END) self.right_file.insert(0, filename) logging.info("Attachment dir selected: " + str(filename)) def input_file_box(self, parent, dir: bool, left: bool): input1_text = tk.Label(parent, text=self.text_dict["window"]["select_file"], font=("", 12)) self.widgets["window/select_file"].append(input1_text) input1_text.pack() if left: self.left_file = tk.Entry(parent) self.widgets["window/sample_path"].append(self.left_file) self.left_file.insert(0, self.text_dict["window"]["sample_path"]) self.left_file.pack(side="left", fill="x", expand=True, ipady=4) bt = tk.Button(parent, text=self.text_dict["button"]["open"], command=lambda: self.select_file(left, dir)) self.widgets["button/open"].append(bt) bt.pack(side="right") else: self.right_file = tk.Entry(parent) self.widgets["window/sample_path"].append(self.right_file) self.right_file.insert(0, self.text_dict["window"]["sample_path"]) self.right_file.pack(side="left", fill="x", expand=True, ipady=4) bt = tk.Button(parent, text=self.text_dict["button"]["open"], command=lambda: self.select_file(left, dir)) self.widgets["button/open"].append(bt) bt.pack(side="right") def reset_credentials(self): try: os.remove(common.BASE_DIR / pathlib.Path("resources\\.credentials\\token.pickle")) showinfo(lang_ctl._FULL_VERSION, self.text_dict["popup"]["cred_del"]) except: showinfo(lang_ctl._FULL_VERSION, self.text_dict["popup"]["cred_del_err"]) def run(self): excel = self.left_file.get() att_dir = self.right_file.get() if os.path.exists(excel) and os.path.exists(att_dir): logging.info("Send_emails_from_excel Started") self.domainCtl.set_credentials(self.username.get()) self.domainCtl.set_min_att(int(self.num_att.get())) logging.info("Min att is %d" % int(self.num_att.get())) try: self.domainCtl.send_emails_from_excel(excel, att_dir) except PermissionError as e1: showerror(self.text_dict["popup"]["cred_err"], str(e1)) except Exception: # General exception showerror(self.text_dict["popup"]["err"]) if len(self.domainCtl.mail_error_list) != 0: showinfo( lang_ctl._FULL_VERSION, self.text_dict["popup"]["finished_w_err"] + "\n".join(self.domainCtl.mail_error_list)) self.domainCtl.clear_error_list() else: showinfo(lang_ctl._FULL_VERSION, self.text_dict["popup"]["finished"]) else: showerror("IOError", self.text_dict["popup"]["ioerror"]) def bar_init(self): # first layer of isolation, note var being passed along to the self.start_bar function # target is the function being started on a new thread, so the "bar handler" thread self.start_bar_thread = threading.Thread(target=self.start_bar) # start the bar handling thread self.start_bar_thread.start() def start_bar(self): # the progressbar needs to be configured for indeterminate amount of bouncing self.progressbar.config(mode="indeterminate", maximum=100, value=0) # 8 here is for speed of bounce self.progressbar.start(8) # start the work-intensive thread, again a var can be passed in here too if desired self.work_thread = threading.Thread(target=self.run) self.work_thread.start() # close the work thread self.work_thread.join() # stop the indeterminate bouncing self.progressbar.stop() # reconfigure the bar so it appears reset self.progressbar.config(value=0, maximum=0) self.change_lang() def change_lang(self, *args): self.text_dict = lang_ctl.get_lang(self.current_lang.get()) self.set_text() def set_text(self): for key in self.widgets: group, index = tuple(key.split("/")) if isinstance(self.widgets[key], list): for wg in self.widgets[key]: if isinstance(wg, tk.Entry): wg.delete(0, tk.END) wg.insert(0, self.text_dict[group][index]) else: wg.configure(text=self.text_dict[group][index]) else: self.widgets[key].configure(text=self.text_dict[group][index])
class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.resizable(0, 0) self.master.protocol("WM_DELETE_WINDOW", self.save_and_exit) self.main_frame = tk.Frame(master) self.main_frame.grid(row=0, column=0, columnspan=2, padx=10) self.spm = SpotipyManager() # Set default settings self.settings = {'cache': True, 'playlists_exclude': []} # Load settings from file try: with open('./data/settings.pickle', 'rb') as file: self.settings = pickle.load(file) except FileNotFoundError: pass self.cache = { 'date_modified': datetime.now(timezone.utc), 'data': None } # Load cache from file try: with open('./data/cache-playlists.pickle', 'rb') as file: self.cache = pickle.load(file) except FileNotFoundError: pass # Thread created even if settings disable cache in case setting is changed later on. cache_thread = threading.Thread(target=self.cache_playlists_helper) cache_thread.daemon = True cache_thread.start() self.create_base_widgets() def save_and_exit(self): """ Saves self.settings to a file and exits """ with open('./data/settings.pickle', 'wb+') as file: pickle.dump(self.settings, file) with open('./data/cache-playlists.pickle', 'wb+') as file: pickle.dump(self.cache, file) self.master.destroy() def cache_playlists_helper(self): """ Sets cache data to correct format of playlists. Function should only called in a thread. """ playlists = self.spm.get_spotipy_client().current_user_playlists() self.cache['data'] = self.spm.cache_songs_in_playlists(playlists) def create_base_widgets(self): """ Initialises all widgets and puts onto the grid the widgets that appear at the start of the application. """ # GUI widgets header = tk.Label(self.main_frame, text="Spotify Playlist Searcher", width=50) header.grid(row=0, column=0, columnspan=2, pady=10) settings_btn = tk.Button( self.main_frame, text="Settings", command=lambda: self.create_settings_widgets()) settings_btn.grid(row=0, column=1, sticky=tk.E) # Song Search self.create_song_widgets() # Playlist Search self.create_playlist_widgets() def create_song_widgets(self): """ Initialises widgets related to searching for songs on Spotify """ song_search = tk.Frame(self.main_frame) song_search.grid(row=1, column=0, columnspan=2, rowspan=3) self.search_bar = tk.Entry(song_search, width=50) self.search_bar.grid(row=0, column=0) self.search_bar.focus() # Lambda expression is necessary because of self arg self.search_bar.bind('<Return>', lambda x: self.search_submit()) search_bar_submit = tk.Button(song_search, text="Search for Song", command=self.search_submit) search_bar_submit.grid(row=0, column=1) search_results_label = tk.Label(song_search, text='Song Results') search_results_label.grid(row=1, column=0, columnspan=2) self.search_results = tk.Listbox(song_search, width=50) self.search_results.grid(row=2, column=0, columnspan=2, padx=5, pady=5) self.search_results.bind('<<ListboxSelect>>', lambda x: self.check_song_selection()) self.search_results.bind('<Return>', lambda x: self.search_playlists()) def create_playlist_widgets(self): """ Initialises widgets related to searching through playlists for a song. Does not display the playlist results listbox and label. """ playlist_search = tk.Frame(self.main_frame) playlist_search.grid(row=4, column=0, columnspan=2, rowspan=3, pady=(0, 10)) self.playlist_search_btn = tk.Button(playlist_search, text="Search Playlists For Song", command=self.search_playlists, state=tk.DISABLED) self.playlist_search_btn.grid(row=0, column=0, columnspan=2, pady=5) # Will be displayed at later point self.playlist_label = tk.Label(playlist_search, text='Playlist Results') self.playlist_results = tk.Listbox(playlist_search, width=50) # Loading Bar loading_style = Style() loading_style.theme_use('alt') loading_style.configure('TProgressbar', thickness=10) self.playlist_loading = Progressbar(self.main_frame, style='TProgressbar', mode='indeterminate', length=150, maximum=50) def search_submit(self): """ Takes search entered and displays the songs in the listbox. Also, initialises a dict mapping the song names to their Spotify uri. """ # Disables playlist button and clears search results self.search_results.delete(0, tk.END) self.playlist_search_btn['state'] = tk.DISABLED self.song_dict = { } # Maps how song appears in listbox to the song's uri for playlist searching search = self.search_bar.get() if search: paging_object = self.spm.get_spotipy_client().search(search) tracks = paging_object['tracks']['items'] for track in tracks: artists = track['artists'] artists_str = '' for i, artist in enumerate(artists): artists_str += f'{artist["name"]}' if not i == len(artists) - 1: artists_str += ', ' output_str = f"{track['name']} - {artists_str}" self.search_results.insert(tk.END, output_str) self.song_dict[output_str] = track['uri'] def check_song_selection(self): """ If a song has been selected in the song listbox, then the button to search through the playlists can be pressed. """ if self.search_results.curselection(): self.playlist_search_btn['state'] = tk.NORMAL else: self.playlist_search_btn['state'] = tk.DISABLED def search_playlists(self): """ Searches through the playlists for the selected song and displays the results in a new listbox. """ def threaded_search(): # If nothing is selected, selection_get() throws an error try: song_selected = self.search_results.selection_get() except: return song_uri = self.song_dict[song_selected] # If caching is enabled and the cache has data, use cached data if self.settings['cache'] and not self.cache['data'] is None: playlist_uris = set() for playlist_uri in self.cache['data']: if song_uri in self.cache['data'][ playlist_uri] and playlist_uri not in self.settings[ 'playlists_exclude']: playlist_uris.add(playlist_uri) else: playlist_uris = self.spm.find_song_in_playlists( song_uri, self.settings['playlists_exclude']) playlist_names = [ self.spm.get_name_from_uri(uri) for uri in playlist_uris ] # Displaying playlist listbox and then inserting playlists self.playlist_label.grid(row=1, column=0, columnspan=2, pady=(10, 5)) self.playlist_results.grid(row=2, column=0, columnspan=2, padx=5) self.playlist_results.delete(0, tk.END) if playlist_names: playlist_names.sort() for name in playlist_names: self.playlist_results.insert(tk.END, name) else: self.playlist_results.insert( tk.END, 'The selected song is not found in any of your playlists.') # Remove Loading Bar self.playlist_loading.stop() self.playlist_loading.grid_forget() # Start and draw Loading Bar self.playlist_loading.grid(row=8, column=0, columnspan=2, sticky=tk.E, pady=(0, 10)) self.playlist_loading.start() # Initialize thread thread = threading.Thread(target=lambda: threaded_search()) thread.daemon = True # Prevents thread from running after application closes thread.start() def create_settings_widgets(self): """ Creates a new window for settings related to the application """ self.settings_window = tk.Toplevel(self.master) self.settings_window.resizable(0, 0) self.settings_window.title('Settings') self.settings_window.protocol("WM_DELETE_WINDOW", self.exit_settings) settings_frame = tk.Frame(self.settings_window) settings_frame.grid(row=0, column=0) settings_header = tk.Label(settings_frame, text='Settings') settings_header.grid(row=0, column=0, columnspan=2) # TODO Implement caching self.cache_toggle_val = tk.BooleanVar() self.cache_toggle_val.set(self.settings['cache']) cache_toggle = tk.Checkbutton( settings_frame, variable=self.cache_toggle_val, text= 'Enable Caching (Inaccurate results if the playlist have been modified recently)' ) cache_toggle.grid(row=1, column=0, sticky=tk.W) playlist_options_frame = tk.LabelFrame(settings_frame, text='Playlists Searched') playlist_options_frame.grid(row=3, column=0, columnspan=2, pady=(0, 10)) self.options_toggle_val = tk.BooleanVar() self.options_toggle_val.set(True) playlist_options_toggle = tk.Checkbutton( playlist_options_frame, text='Toggle all playlists', variable=self.options_toggle_val, command=self.playlists_toggle) playlist_options_toggle.grid(row=0, column=0, columnspan=2, sticky=tk.W) # TODO Add scrollbar if too many playlist options playlists = self.spm.get_spotipy_client().current_user_playlists() self.playlist_exclude_data = [ ] # List of Tuple (Playlist_URI, BooleanVar) # Generates checkboxes for each user playlist for i, playlist in enumerate(playlists['items']): playlist_name = f'{playlist["name"]}' is_playlist_excluded = tk.BooleanVar() if playlist['uri'] in self.settings['playlists_exclude']: is_playlist_excluded.set(False) else: is_playlist_excluded.set(True) self.playlist_exclude_data.append( (playlist["uri"], is_playlist_excluded)) option = tk.Checkbutton(playlist_options_frame, text=playlist_name, variable=self.playlist_exclude_data[i][1]) option.grid(row=i + 1, column=0, columnspan=2, sticky=tk.W) reset_btn = tk.Button(settings_frame, text='Reset Settings', command=self.reset_settings) reset_btn.grid(row=4, column=0, columnspan=2, pady=(0, 10)) def exit_settings(self): """ Saves settings to self.settings before exiting. """ self.settings['cache'] = self.cache_toggle_val.get() self.settings['playlists_exclude'] = [ check_val[0] for check_val in self.playlist_exclude_data if not check_val[1].get() ] self.settings_window.destroy() def reset_settings(self): """ Resets settings to default values. """ self.settings = {'cache': True, 'playlists_exclude': []} self.cache_toggle_val.set(True) for val in self.playlist_exclude_data: val[1].set(True) def playlists_toggle(self): """ Toggles all of the playlist checkboxes on or off """ toggle_val = self.options_toggle_val.get() for check_val in self.playlist_exclude_data: check_val[1].set(toggle_val)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, name="frame") self.parent = parent self.initUI() def initUI(self): self.parent.title("Pi computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W + E) self.txt = scrolledtext.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E + W + S + N) def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) #self.p1 = Process(target=generatePi, args=(q, digits, accuracy)) self.p1 = Process(target=lengthy_function) self.p1.start() self.pbar.start(DELAY2) #20 self.after( DELAY1, self.listen_for_results) # after 80 ms, start checking for results # consumer function is in the GUI class def listen_for_results(self): # if the worker process is still running, delay a bit and check again if (self.p1.is_alive()): print('p1 is still alive') self.after(DELAY1, self.listen_for_results) return else: # the worker process has finished and put the result in the queue print('p1 is NOT alive') print(f'Checking if queue.Empty(): {q.empty()}') print(f'Checking queue.qsize(): {q.qsize()}') while q.qsize() > 0: print('something in the queue') record = q.get() print(record) time.sleep(1) print('queue is empty') self.pbar.stop() self.startBtn.config(state=NORMAL) '''while True:
class Example(Frame): def __init__(self, parent, q): Frame.__init__(self, parent) self.queue = q self.parent = parent self.initUI() def callback(self): self.root.quit() def initUI(self): # self.root = tk.Tk() # self.root.protocol("WM_DELETE_WINDOW", self.callback) self.parent.title("Pi Computation") self.pack(fill=BOTH, expand=True) self.grid_columnconfigure(4, weight=1) self.grid_rowconfigure(3, weight=1) lbl1 = Label(self, text="Digits:") lbl1.grid(row=0, column=0, sticky=E, padx=10, pady=10) self.ent1 = Entry(self, width=10) self.ent1.insert(END, "4000") self.ent1.grid(row=0, column=1, sticky=W) lbl2 = Label(self, text="Accuracy:") lbl2.grid(row=0, column=2, sticky=E, padx=10, pady=10) self.ent2 = Entry(self, width=10) self.ent2.insert(END, "100") self.ent2.grid(row=0, column=3, sticky=W) self.startBtn = Button(self, text="Start", command=self.onStart) self.startBtn.grid(row=1, column=0, padx=10, pady=5, sticky=W) self.pbar = Progressbar(self, mode='indeterminate') self.pbar.grid(row=1, column=1, columnspan=3, sticky=W + E) self.txt = st.ScrolledText(self) self.txt.grid(row=2, column=0, rowspan=4, padx=10, pady=5, columnspan=5, sticky=E + W + S + N) # self.root.mainloop() def onStart(self): self.startBtn.config(state=DISABLED) self.txt.delete("1.0", END) self.digits = int(self.ent1.get()) self.accuracy = int(self.ent2.get()) self.p1 = Process(target=self.generatePi, args=(self.queue, )) # self.p1 = Process(target=self.generatePi, args=(self.queue )) self.p1.start() self.pbar.start(DELAY2) self.after(DELAY1, self.onGetValue) def onGetValue(self): if (self.p1.is_alive()): self.after(DELAY1, self.onGetValue) return else: try: self.txt.insert('end', self.queue.get(0)) self.txt.insert('end', "\n") self.pbar.stop() self.startBtn.config(state=NORMAL) except queue.Empty: print("queue is empty") def generatePi(self, queue): getcontext().prec = self.digits pi = Decimal(0) k = 0 n = self.accuracy while k < n: pi += (Decimal(1)/(16**k))*((Decimal(4)/(8*k+1)) - \ (Decimal(2)/(8*k+4)) - (Decimal(1)/(8*k+5))- \ (Decimal(1)/(8*k+6))) k += 1 print("Example frame is still alive = ", self.p1.is_alive()) # queue.put("Example frame is still alive = ", self.p1.is_alive()) queue.put(pi) print("Example frame end")
def work(): # global lbl submit_btn.destroy() reroll_songs_btn.destroy() destroy_radio_buttons() lbl.destroy() # del lbl # window.update_idletasks() progress_var = DoubleVar() progress = Progressbar(window, variable=progress_var, orient=HORIZONTAL, length=250, mode='determinate') progress.place(x=500, y=270) progress_lbl = Label(window, text="Loading...") progress_lbl.place(x=600, y=315) time.sleep(5) # window.update_idletasks() model = load_model('../data/first.model') lyrics = [] for b, s in zip(chosen_bands, chosen_songs): print(b, s) artist = df[df.band == b] song = artist[df.name == s] lyr = song.lyrics.item().split(';') lyrics.append(song2matrix(most_freq_words(lyr), model)) final_matrix = [] for mat in lyrics: final_matrix = add_matices(final_matrix, mat) songs_recommended = "" for i in get_recommendations(final_matrix, model, pvar=progress_var, window=window): songs_recommended += get_band(i) + " - " + get_name(i) + "\n" t1 = 'Based on your taste:\n' for b, s in zip(chosen_bands, chosen_songs): t1 += "\n{} - {}".format(b, s) final_lbl = Label(window, text=t1) final_lbl.place(x=850, y=100) t2 = "\n\nRecommended songs are:\n\n" + songs_recommended final_lbl = Label(window, text=t2) final_lbl.place(x=850, y=250) progress.stop() progress_lbl.destroy() done_lbl = Label(window, text="Done! 100%") done_lbl.place(x=600, y=315) print("Done!")
class MainApplication(Frame): def __init__(self, master, *args, **kwargs): Frame.__init__(self, master, *args, **kwargs) self.master.title('CFDI 2 Excel') self.master.resizable(0, 0) self.lbl_titulo = Label(self, text='CFDI 2 Excel', font=('Arial Bold', 20)) self.lbl_titulo.grid(column=0, row=0, columnspan=4, sticky='ew', padx=10, pady=10) self.btn_fuente = Button(self, text='...', command=self.btn_fuente_click) self.btn_fuente.grid(row=1, column=0, sticky='ew', padx=10, pady=10) self.lbl_fuente = Label(self, text='Folder fuente:') self.lbl_fuente.grid(row=1, column=1, sticky='ew', padx=10, pady=10) self.lbl_path_fuente = Label(self, text=os.getcwd()) self.lbl_path_fuente.grid(row=1, column=2, columnspan=2, sticky='ew', padx=10, pady=10) self.btn_destino = Button(self, text='...', command=self.btn_destino_click) self.btn_destino.grid(row=2, column=0, sticky='ew', padx=10, pady=10) self.lbl_destino = Label(self, text='Folder destino:') self.lbl_destino.grid(row=2, column=1, sticky='ew', padx=10, pady=10) self.lbl_path_destino = Label(self, text=os.getcwd()) self.lbl_path_destino.grid(row=2, column=2, columnspan=2, sticky='ew', padx=10, pady=10) self.pgb_status = Progressbar(self) self.pgb_status.grid(row=3, column=0, columnspan=2, sticky='ew', padx=10, pady=10) self.c1_v1 = IntVar() self.cb_valida = Checkbutton(self, text='Valida SAT', onvalue=1, offvalue=0, variable=self.c1_v1) self.cb_valida.grid(row=3, column=2, sticky='ew', padx=10, pady=10) self.btn_procesar = Button(self, text='Procesar', command=self.btn_procesar_click) self.btn_procesar.grid(row=3, column=3, sticky='ew', padx=10, pady=10) self.lbl_estado = Label(self, text='Listo') self.lbl_estado.grid(row=4, column=0, columnspan=4, sticky='ew', padx=10, pady=10) def btn_fuente_click(self): path = self.lbl_path_fuente['text'] path = askdirectory(initialdir=path) if path: self.lbl_path_fuente['text'] = path def btn_destino_click(self): path = self.lbl_path_destino['text'] path = askdirectory(initialdir=path) if path: self.lbl_path_destino['text'] = path def btn_procesar_click(self): res = askokcancel('Confirmar', '¿Seguro que quiere procesar?') if not res: return self.btn_fuente['state'] = 'disabled' self.btn_destino['state'] = 'disabled' self.btn_procesar['state'] = 'disabled' Thread(target=self.task_xml_to_excel).start() def task_xml_to_excel(self): self.pgb_status.start() validacion = Validacion() fuente_path = self.lbl_path_fuente['text'] destino_path = self.lbl_path_destino['text'] files = [ os.path.join(dp, f) for dp, dn, filenames in os.walk(fuente_path) for f in filenames if os.path.splitext(f)[1] == '.xml' ] text = 'XML encontrados: {}'.format(len(files)) self.lbl_estado['text'] = text wb = Workbook() sheet = wb.active sheet.append( ('Version', 'UUID', 'Serie', 'Folio', 'Tipo', 'Fecha emision', 'Fecha certificacion', 'pacCertifico', 'RFC emisor', 'Razon emisor', 'RFC receptor', 'Razon receptor', 'Conceptos', 'Uso CFDI', 'Moneda', 'Tipo de cambio', 'Metodo pago', 'Forma pago', 'SubTotal', 'Descuento', 'IVA Trasladado', 'ISR Trasladado', 'IEPS Trasladado', 'IVA Retenido', 'ISR Retenido', 'Impuesto Local', 'Total', 'TipoRelacion', 'CfdiRelacionados', 'codigo_estatus', 'es_cancelable', 'estado')) for f in files: try: self.lbl_estado['text'] = 'Procesando: {}'.format(f) root = etree.parse( f, parser=etree.XMLParser(huge_tree=True, recover=True)).getroot() version = root.get('Version') uuid = root.find('cfdi:Complemento/tfd:TimbreFiscalDigital', namespaces=NSMAP).get('UUID') serie = root.get('Serie') folio = root.get('Folio') tipo = root.get('TipoDeComprobante') fecha = root.get('Fecha') fecha_timbrado = root.find( 'cfdi:Complemento/tfd:TimbreFiscalDigital', namespaces=NSMAP).get('FechaTimbrado') pac = root.find('cfdi:Complemento/tfd:TimbreFiscalDigital', namespaces=NSMAP).get('RfcProvCertif') rfc_emisor = root.find('cfdi:Emisor', namespaces=NSMAP).get('Rfc') nombre_emisor = root.find('cfdi:Emisor', namespaces=NSMAP).get('Nombre') rfc_receptor = root.find('cfdi:Receptor', namespaces=NSMAP).get('Rfc') nombre_receptor = root.find('cfdi:Receptor', namespaces=NSMAP).get('Nombre') conceptos = '' for i, c in enumerate( root.findall('cfdi:Conceptos/cfdi:Concepto', namespaces=NSMAP)): conceptos += '|-{}-|: {}: {} '.format( i + 1, c.get('Descripcion'), c.get('Importe')) uso = root.find('cfdi:Receptor', namespaces=NSMAP).get('UsoCFDI') moneda = root.get('Moneda') tipo_cambio = root.get('TipoCambio') metodo_pago = root.get('MetodoPago') forma_pago = root.get('FormaPago') subtotal = root.get('SubTotal') descuento = root.get('Descuento') iva = 0.0 isr = 0.0 ieps = 0.0 for t in root.findall( 'cfdi:Impuestos/cfdi:Traslados/cfdi:Traslado', namespaces=NSMAP): if t.get('Impuesto') == '002': iva += float(t.get('Importe')) if t.get('Impuesto') == '001': isr += float(t.get('Importe')) if t.get('Impuesto') == '003': ieps += float(t.get('Importe')) iva_ret = 0 isr_ret = 0 for t in root.findall( 'cfdi:Impuestos/cfdi:Retenciones/cfdi:Retencion', namespaces=NSMAP): if t.get('Impuesto') == '002': iva_ret += float(t.get('Importe')) if t.get('Impuesto') == '001': isr_ret += float(t.get('Importe')) total = root.get('Total') tipo_relacion = '' relaciones = '' cfdi_relacionados = root.find('cfdi:CfdiRelacionados', namespaces=NSMAP) if cfdi_relacionados is not None: tipo_relacion = cfdi_relacionados.get('TipoRelacion') for r in cfdi_relacionados.findall('cfdi:CfdiRelacionado', namespaces=NSMAP): relaciones += '{}, '.format(r.get('UUID')) implocal = 0 for t in root.findall( 'cfdi:Complemento/implocal:ImpuestosLocales/implocal:TrasladosLocales', namespaces=NSMAP): implocal += float(t.get('Importe')) # teste de validacion con el SAT if self.c1_v1.get() == 1: status = validacion.obtener_estado(rfc_emisor, rfc_receptor, total, uuid) codigo_estatus = status['codigo_estatus'] es_cancelable = status['es_cancelable'] estado = status['estado'] else: codigo_estatus = '' es_cancelable = '' estado = '' print( 'uuid: {}, rfc_emisor: {}, rfc_receptor: {}, total: ${} -> {}' .format(uuid, rfc_emisor, rfc_receptor, total, estado)) sheet.append( (version, uuid, serie, folio, tipo, fecha, fecha_timbrado, pac, rfc_emisor, nombre_emisor, rfc_receptor, nombre_receptor, conceptos, uso, moneda, tipo_cambio, metodo_pago, forma_pago, subtotal, descuento, iva, isr, ieps, iva_ret, isr_ret, implocal, total, tipo_relacion, relaciones, codigo_estatus, es_cancelable, estado)) except Exception as e: sheet.append((str(e), )) file_path = os.path.join(destino_path, 'cfdis.xlsx') wb.save(file_path) self.pgb_status.stop() self.btn_fuente['state'] = 'normal' self.btn_destino['state'] = 'normal' self.btn_procesar['state'] = 'normal' showinfo( 'Completado', 'Proceso completado\nArchivo guardado en: {}'.format(file_path)) os.system('start excel "{}"'.format(file_path))
class GraphicalApp(tk.Frame): """Interface graphique du jeu.""" def __init__(self, dispatcher): self.dispatcher = dispatcher self.master = None self.treeview = None self.chats = { } # contient des listes [id, treeview, entry, bouton, messageCpt] self.progress = None self.previousAngles = {} self.initializeGraphicalApp() self.dispatcher.setGraphicalApp(self) self.mainloop() def initializeGraphicalApp(self): """Initialise l'interface graphique.""" self.master = tk.Tk() self.master.title("To the conquest of the dragon balls !") super().__init__(self.master) self.master.resizable(False, False) self.createWidgets() self.setUpBindingEvent() self.master.protocol("WM_DELETE_WINDOW", self.closeWindow) msg = "Welcome space travelers !\n\n" msg += "A brand new race has been created. " msg += "You may ask yourself : \"Why should i participate ?\" " msg += "Well because the reward is worth it, it's nothing more than the seven dragon balls !\n" msg += "Suddenly fell more excited right ?!\n" msg += "But watch out, you are not the only one interested...\n\n" msg += "In order to move your vehicle, use your keyboard's directional arrows.\n" msg += "You can also drop a bomb with the \"B\" button.\n\n" msg += "Good luck !" messagebox.showinfo(title="Welcome !", message=msg) def createWidgets(self): """Crée tous les widgets de l'interface.""" tk.Label(self.master, text="Your pseudo", font="-weight bold").grid(row=0, column=0, sticky=tk.W) self.pseudoEntry = tk.Entry(self.master) self.pseudoEntry.grid(row=0, column=1, sticky=tk.EW) self.pseudoEntry.focus_set() tk.Label(self.master, text="Status : ", font="-weight bold").grid(row=1, column=0, sticky=tk.W) self.statusLabel = tk.Label(self.master, text="Not yet connected...") self.statusLabel.grid(row=1, column=1, sticky=tk.W) self.progress = Progressbar(self.master, orient=tk.HORIZONTAL, mode='indeterminate') self.progress.grid(row=1, column=2) self.exitButton = tk.Button(self.master) self.exitButton["text"] = "Exit" self.exitButton["state"] = tk.DISABLED self.exitButton["bg"] = "#FF0A2D" self.exitButton["activebackground"] = "#FF415C" self.exitButton["fg"] = "#FFFFFF" self.exitButton["activeforeground"] = "#FFFFFF" self.exitButton["relief"] = tk.FLAT self.exitButton["bd"] = 0 self.exitButton["command"] = lambda: self.dispatcher.onExitClicked() self.exitButton.grid(row=2, column=1, sticky=tk.EW) self.connectionButton = tk.Button(self.master) self.connectionButton["text"] = "Connect to the server" self.connectionButton["bg"] = "#1296EC" self.connectionButton["activebackground"] = "#33A5EF" self.connectionButton["fg"] = "#FFFFFF" self.connectionButton["activeforeground"] = "#FFFFFF" self.connectionButton["relief"] = tk.FLAT self.connectionButton["bd"] = 0 self.connectionButton["command"] = lambda: self.onConnectionClicked( self.connectionButton) self.connectionButton.grid(row=2, column=0, sticky=tk.EW) self.createScoreTable() self.createSpaceEnvironment() self.notebook = Notebook(self.master) self.notebook.grid(row=5, column=3, columnspan=2, rowspan=3, sticky=tk.NSEW) self.createChat("Public", enable=False) def setUpBindingEvent(self): """Met en place tous les événement permettant eu joueur de contrôler son pod.""" # Les code de mise à jour du joueur doivent être exécutés dans un autre thread. # Dans le cas contraire, il y a un interblocage entre le thread de # l'interface graphique (celui-ci), et celui qui met à jour périodiquement les position des joueurs. self.master.bind('<Left>', self.dispatcher.antiClockEvent) self.master.bind('<Right>', self.dispatcher.clockEvent) self.master.bind('<Up>', self.dispatcher.thrustEvent) self.master.bind('b', self.dispatcher.putBomb) def createSpaceEnvironment(self): """Crée un décor spatial.""" self.canvasLock = Lock() self.canvas = tk.Canvas(self.master, width=dat.ARENA_L * 2, height=dat.ARENA_H * 2, bg="black") self.canvas.grid(row=5, column=0, columnspan=3, rowspan=5, pady=(10, 0)) # Ajoute 200 étoiles for __ in range(0, 200): self.drawRandomStar() def drawRandomStar(self): """Dessine une étoile à une position aléatoire.""" maxX = int(self.canvas["width"]) maxY = int(self.canvas["height"]) x = random.randint(0, maxX) y = random.randint(0, maxY) self.canvas.create_oval(x, y, x + 5, y + 5, fill="white") def createScoreTable(self): """Crée le tableau des scores.""" tk.Label(self.master, text="Scores", font="-weight bold").grid(row=3, column=0, columnspan=2) tv = Treeview(self.master, height=3) tv['columns'] = ('Score', "Bomb") tv.heading("#0", text='User', anchor=tk.W) tv.heading('Bomb', text='Bombs available', anchor=tk.W) tv.column('Bomb', anchor=tk.W, width=100) tv.heading('Score', text='Score', anchor=tk.W) tv.column('Score', anchor=tk.W, width=100) tv.grid(row=4, column=0, columnspan=3, sticky=tk.EW) self.treeview = tv def increaseBombOf(self, player): """Incrémente le nombre de bombe que possède un joueur dans le tableau d'affichage. Arguments: player - Le pseudo du joueur pour lequel on doit incrémenter son nombre de bombe. """ for i in self.treeview.get_children(): item = self.treeview.item(i) # Nous sommes bien sur l'item du joueur qui nous interesse if item["text"] == player: oldValue = item['values'] oldValue[1] += 1 self.treeview.item(i, values=oldValue) break def decreaseBombOf(self, player): """Décrémente le nombre de bombe que possède un joueur dans le tableau d'affichage. Arguments: player - Le pseudo du joueur pour lequel on doit décrémenter son nombre de bombe. """ for i in self.treeview.get_children(): item = self.treeview.item(i) # Nous sommes bien sur l'item du joueur qui nous interesse if item["text"] == player: oldValue = item['values'] oldValue[1] -= 1 self.treeview.item(i, values=oldValue) break def setBombOf(self, player, nbBomb): """Met à jour le nombre de bombe que possède un joueur dans le tableau d'affichage. Arguments: player - Le pseudo du joueur pour lequel on doit mettre à jour son nombre de bombe. nbBomb - Le nouveau nombre de bombe du joueur. """ for i in self.treeview.get_children(): item = self.treeview.item(i) # Nous sommes bien sur l'item du joueur qui nous interesse if item["text"] == player: oldValue = item['values'] oldValue[1] = nbBomb self.treeview.item(i, values=oldValue) break def createChat(self, nom, enable=True): """Créer un nouveau chat pour un joueur donné. Arguments: nom - Le nom du joueur avec lequel l'utilisateur pourra parler avec ce chat Keyword Arguments: enable -- Est-ce que le chat doit être activer par défaut. (default: {True}) """ frame = tk.Frame(self.notebook) self.notebook.add(frame, text=nom) chat = Treeview(frame, height=15) chat['columns'] = ('Date') chat.heading("#0", text='Messages', anchor=tk.W) chat.heading('Date', text='Date', anchor=tk.W) chat.column('Date', anchor=tk.W, width=150) chat.grid(row=0, column=0, columnspan=2, rowspan=3, sticky=tk.NSEW) chat.tag_configure('even', background='#DAE5F4') chat.tag_configure('odd', background='#B8D1F3') chat.tag_configure('from_me', font=("Helvetica", 10, "bold")) chat.tag_configure('not_from_me', font=("Helvetica", 10)) messageEntry = tk.Entry(frame) messageEntry.grid(row=4, column=0, sticky=tk.S) messageButton = tk.Button(frame) messageButton["text"] = "Envoyer" if not enable: messageButton["state"] = tk.DISABLED messageButton["bg"] = "#1296EC" messageButton["activebackground"] = "#33A5EF" messageButton["fg"] = "#FFFFFF" messageButton["activeforeground"] = "#FFFFFF" messageButton["relief"] = tk.FLAT messageButton["bd"] = 0 messageButton["command"] = lambda: self.sendMessage(nom, messageEntry) messageButton.grid(row=4, column=1, sticky=tk.S) self.chats[nom] = [frame, chat, messageEntry, messageButton, 0] def deleteChat(self, name): """Supprime un chat permmetant de communiquer avec un joueur donnée. Arguments: name -- Le nom du joueur pour lequel on doit supprimer le chat. """ self.notebook.forget(self.chats[name][0]) def sendMessage(self, target, entry): """Signale au dispatcher la volonté de l'utilisateur d'envoyer un message. Arguments: target -- La cible à laquelle le joueur souhaite envoyer le message. entry -- L'entry source sur laquelle l'utilisateur a saisi son message. """ message = entry.get() if message == "": messagebox.showerror(title="Empty message", message="You cannot send an empty message") else: self.dispatcher.sendMessage(target, message) entry.delete(0, tk.END) def addMessage(self, chatName, message, fromMe=False): """Ajout un message à un chat. Arguments: chatName -- Le nom du chat. message -- Le message. Keyword Arguments: fromMe -- Indique si le message vient de l'utilisateur de l'application cliente. (default: {False}) """ currentDate = strftime("%d/%m/%Y-%H:%M:%S", gmtime()) fromMeTag = 'from_me' if fromMe else 'not_from_me' odd_even_tag = 'even' if (self.chats[chatName][4] % 2) == 0 else 'odd' self.chats[chatName][1].insert('', 'end', text=message, values=currentDate, tags=(odd_even_tag, fromMeTag)) self.chats[chatName][4] += 1 def addScoreToTable(self, user, score): """ Ajoute un nouveau score au tableau des scores. Si le joueur est déjà présent, met à jour sa ligne. Arguments: user -- Un pseudo. score -- Un score. """ edited = False for i in self.treeview.get_children(): item = self.treeview.item(i) # Nous sommes bien sur l'item du joueur qui nous interesse if item["text"] == user: oldValue = item['values'] oldValue[0] = score self.treeview.item(i, values=oldValue) edited = True break if not edited: self.treeview.insert('', 'end', text=str(user), values=(str(score), "0")) def createGraphicalPlayer(self, playerX, playerY): """Crée un joueur à une position spécifique. Arguments: playerX -- La coordonnée X du joueur. playerY -- La coordonnée Y du joueur. Returns: tuple -- Un tuple contenant le tag du joueur dans le canvas et ses images. """ convertedPos = self.convertPosition(playerX, playerY) playerImage = Image.open('images/pod_sprite_50.png') podPicture = ImageTk.PhotoImage(playerImage) self.canvasLock.acquire() tagPlayer = self.canvas.create_image(convertedPos[0], convertedPos[1], image=podPicture) self.canvasLock.release() return (tagPlayer, playerImage, podPicture) def createGraphicalOpponent(self, playerX, playerY): """Crée un adversaire à une position spécifique. Arguments: playerX -- La coordonnée X de l'adversaire. playerY -- La coordonnée Y de l'adversaire. Returns: tuple -- Un tuple contenant le tag de l'adversaire dans le canvas et ses images. """ convertedPos = self.convertPosition(playerX, playerY) opponentImage = Image.open('images/pod2_sprite_50.png') podPicture = ImageTk.PhotoImage(opponentImage) self.canvasLock.acquire() tagOpponent = self.canvas.create_image(convertedPos[0], convertedPos[1], image=podPicture) self.canvasLock.release() return (tagOpponent, opponentImage, podPicture) def createGraphicalObstacle(self, obstacleX, obstacleY): """Crée un obstacle à une position spécifique. Arguments: obstacleX -- La coordonnée X de l'obstacle. obstacleY -- La coordonnée Y de l'obstacle. Returns: tuple -- Un tuple contenant le tag de l'obstacle dans le canvas et sa photoImage. """ convertedPos = self.convertPosition(obstacleX, obstacleY) obstacleImage = Image.open('images/obstacles/asteroid_sprite_55.png') obstaclePicture = ImageTk.PhotoImage(obstacleImage) self.canvasLock.acquire() tagOstacle = self.canvas.create_image(convertedPos[0], convertedPos[1], image=obstaclePicture) self.canvasLock.release() return (tagOstacle, obstaclePicture) def createGraphicalGenkidma(self, genkidamaX, genkidamaY): """Crée un genkidama à une position spécifique. Arguments: genkidamaX -- La coordonnée X du genkidama. genkidamaY -- La coordonnée Y du genkidama. Returns: tuple -- Un tuple contenant le tag du genkidama dans le canvas et sa photoImage. """ convertedPos = self.convertPosition(genkidamaX, genkidamaY) genkidamaImage = Image.open('images/bombs/spirit_bomb_35.png') genkidamaPicture = ImageTk.PhotoImage(genkidamaImage) self.canvasLock.acquire() tagGenkidama = self.canvas.create_image(convertedPos[0], convertedPos[1], image=genkidamaPicture) self.canvasLock.release() return (tagGenkidama, genkidamaPicture) def deleteGraphicalGenkidma(self, genkidamaX, genkidamaY): """Enlève un genkidama situé à une position spécifique. Arguments: genkidamaX -- La coordonnée X du genkidama. genkidamaY -- La coordonnée Y du genkidama. Returns: tuple -- Un tuple contenant le tag du genkidama dans le canvas et sa photoImage. """ convertedPos = self.convertPosition(genkidamaX, genkidamaY) self.canvasLock.acquire() tagGenki = self.canvas.find_closest(convertedPos[0], convertedPos[1]) self.canvas.delete(tagGenki) self.canvasLock.release() def onConnectionClicked(self, button): """Handler du clique sur le bouton de connexion Arguments: button -- Le bouton source. """ pseudo = self.pseudoEntry.get() if pseudo == "": msg = "No pseudo given. You have to give a pseudo in order to connect to the server." messagebox.showerror(title="No pseudo", message=msg) else: success = self.dispatcher.onConnectionClicked(pseudo) if success: button["state"] = tk.DISABLED self.exitButton["state"] = tk.NORMAL self.chats["Public"][3]["state"] = tk.NORMAL self.statusLabel["text"] = "Connection succeed !" self.pseudoEntry.delete(0, tk.END) else: msg = "Connection to the server failed.\nMake sure the server is running." messagebox.showerror(title="Connection failed", message=msg) def closeWindow(self): """Handler de la fermeture de la fenêtre. Signale au dispatcher que l'utilisateur souhaite quitter l'application et ferme l'interface. """ self.dispatcher.onCloseWindow() # Il se peut qu'un thread soit bloqué en attente d'une réponse du thread de l'interface # En exécutant un update, on va le débloquer self.master.update() self.master.destroy() def updateUIPlayer(self, player): """Met à jour la position et l'angle de rotation d'un joueur. Arguments: player -- Le joueur. """ self.canvasLock.acquire() if player.getPseudo( ) not in self.previousAngles or self.previousAngles[ player.getPseudo()] != player.getAngle(): self.rotatePlayer(player) self.updatePlayer(player) self.canvasLock.release() def updatePlayer(self, player): """Met à jour la position d'un joueur. Arguments: player -- Le joueur. """ convertedPos = self.convertPosition(player.getPositionX(), player.getPositionY()) self.canvas.coords(player.getCanvasTagId(), (convertedPos[0], convertedPos[1])) def rotatePlayer(self, player): """Met à jour l'angle de rotation d'un joueur. Arguments: player -- Le joueur. """ self.previousAngles[player.getPseudo()] = player.getAngle() self.canvas.delete(player.getCanvasTagId()) podPicture = ImageTk.PhotoImage(player.getImage().rotate( player.getAngle())) convertedPos = self.convertPosition(player.getPositionX(), player.getPositionY()) newId = self.canvas.create_image(convertedPos[0], convertedPos[1], image=podPicture) player.setCanvasTagId(newId) player.setPhotoImage(podPicture) def convertPosition(self, x, y): """Convertie des coordonnées pour qu'elle soit utilisable par le canvas. Arguments: x -- La coordonnée X. y -- La coordonnée Y. Returns: tuple(x, y) -- Un tuple contenant les positions converties. """ newX = x + dat.ARENA_L newY = y + dat.ARENA_H return (newX, newY) def showDeniedMessage(self): """Affiche un message indiquant à l'utilisateur que sa tentative de connexion à été refusée.""" msg = "The server refused the connection.\nYou may try again with an other pseudo" messagebox.showerror(title="Connection refused", message=msg) self.statusLabel["text"] = "Pseudo already used..." self.connectionButton["state"] = tk.NORMAL def showWaitingMessage(self): """Met à jour le label de status pour indiquer à l'utilisateur d'attendre le début de la partie.""" print("Waiting") self.statusLabel["text"] = "Waiting for game to start..." self.progress.start(10) def showStartMessage(self): """Met à jour le label de status pour indiquer à l'utilisateur que la partie à commencé.""" print("Good game") self.statusLabel["text"] = "Good game !" self.progress.stop() def showWinner(self, winnerName, iWin): """Affiche une fenêtre avec le nom du gagnant. Arguments: winnerName -- Le nom du gagnant. iWin -- Indique si le gagnant est le joueur actuel. """ msg = "" if iWin: msg = "Congratulation you have won !" else: msg = winnerName + " has won !" messagebox.showinfo(title="We have a winner !", message=msg) def showObjectif(self, objectifX, objectifY, objectifNumber): """Ajoute un objectif (une dragon ball). Arguments: objectifX -- La coordonnée X de l'objectif. objectifY -- La coordonnée Y de l'objectif. objectifNumber -- Le numéro de l'objectif (utiliser pour choisir quelle dragon ball utiliser). Returns: tuple(idTag, photoImage) -- Un tuple contenant le tag de l'objectif et son image. """ converted = self.convertPosition(objectifX, objectifY) newImage = Image.open('images/dragon_ball/ball_' + str(objectifNumber) + ".png") newPhotoImage = ImageTk.PhotoImage(newImage) self.canvasLock.acquire() tagImage = self.canvas.create_image(converted[0], converted[1], image=newPhotoImage) self.canvasLock.release() return (tagImage, newPhotoImage) def reset(self): """Remet à zéro l'application graphique.""" self.resetScores() for (_, chat) in self.chats.items(): self.notebook.forget(chat[0]) self.chats = {} # On ajoute de nouveau le chat public self.createChat("Public", enable=True) def resetScores(self): """Remet à zéro le tableau des scores.""" self.progress.stop() for i in self.treeview.get_children(): self.treeview.delete(i) def removeOpponent(self, opponentName): """Supprime un adversaire dde l'interface graphique. Arguments: opponentName -- Le nom de l'adversaire. """ for child in self.treeview.get_children(): item = self.treeview.item(child) if (item["text"]) == opponentName: self.treeview.delete(child) if opponentName in self.chats: del self.chats[opponentName] def deleteFromCanvas(self, tag): """Supprime un élément du canavas identifié par son tag. Arguments: tag -- Le tag de l'élément à supprimer. """ self.canvas.delete(tag) def showElement(self, tag): self.canvas.itemconfigure(tag, state='normal') def hideElement(self, tag): self.canvas.itemconfigure(tag, state='hidden')