class ProgressCheckButton(Frame, Observable): def __init__(self, parent, model, index, status_model): Frame.__init__(self, parent) Observable.__init__(self) self.model = model self.index = index self.status_model = status_model self.var = IntVar() self.var.set(model.get_checked()) self.progress_var = IntVar() self.progress_status = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self.model.add_listener(self._model_changed) def _model_changed(self, new_status): model_state = self.model.get_checked() gui_state = self.var.get() if model_state is not gui_state: self.model.set_checked(gui_state) def refresh_check(self): if self.status_model.is_checked_force_reload(): self.check_button.select() else: self.check_button.deselect() def is_checked(self): return self.var.get() def _progress_status_changed(self, new_status): self._refresh_progress() def _refresh_progress(self): status = self.status_model.get_status() if not status == self.progress_status: if status == ProgressStatus.in_progress: self.progress_bar.pack(side=RIGHT, fill="both", expand=True) else: self.progress_bar.pack_forget() def _check_changed(self): new_checked = self.var.get() if new_checked is not self.model.get_checked(): self.model.set_checked(new_checked) if new_checked is not self.status_model.is_checked(): self._notify(self.index, new_checked)
class ProgressListBoxItem(Frame, Observable): def __init__(self, parent, model): Frame.__init__(self, parent) Observable.__init__(self) self._model = model # Create variables and initialise to zero self._checked_var = IntVar() self._progress_var = IntVar() self._checked_var.set(0) self._progress_var.set(0) self._current_gui_checked_state = CheckStatus.undefined self._current_gui_progress_state = ProgressStatus.undefined self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed) self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var) self.check_button.pack(side=LEFT, fill="both", expand=True) self._update() self._model.add_listener(self._model_changed) def _model_changed(self): self.update() def _update(self): # Update check status model_check_state = self._model.get_check_status() if model_check_state is not self._current_gui_checked_state: self._current_gui_checked_state = model_check_state # if self.status_model.is_checked_force_reload(): if model_check_state: self.check_button.select() else: self.check_button.deselect() # Update progress status model_progress_state = self._model.get_progress_status if not model_progress_state == self._current_gui_progress_state: self._current_gui_progress_state = model_progress_state if model_progress_state == ProgressStatus.in_progress: self.progress_bar.pack(side=RIGHT, fill="both", expand=True) else: self.progress_bar.pack_forget() def _user_check_changed(self): new_checked = self._checked_var.get() if new_checked is not self._model.get_check_status(): self._model.manual_set_checked(new_checked)
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()
class waitWindowProgressBar(Toplevel): def __init__(self, parent=None): """ Initialises the calculate wait window. Waits for other processes to finish, then packs everything. messages, setup_dataset and stop are the functions that change the layout of the frame. """ super().__init__(parent) self.title("Setting up.......") #self.attributes("-topmost", True) self.pb_val = IntVar(self) self.pb_val.set(0) self.pb = Progressbar(self, length=400, variable=self.pb_val) self.pb.pack(pady=20, padx=20) self.pb.configure(maximum=10) self.labeltext = StringVar() self.labeltext.set("Waiting for other process.....") self.waiting_label = Label(self, textvariable=self.labeltext) self.waiting_label.configure(anchor="center") self.waiting_label.pack(pady=20, padx=20, fill='both', expand=True) self.stopbutton = Button(self, text="Stop!", compound="bottom", command=self.stop) self.stopbutton.pack(side="left", fill="x", expand=True) self.stopflag = 0 self.update() def stop(self): """ Sets the stopflag to 1, thus stopping the calculation. """ self.stopflag = 1 def setup_dataset(self, dataset): """ Sets up the calculation wait window for the different stages of calculation. """ self.dataset = dataset self.title("Calculating Dataset %s" % os.path.basename(dataset.path)) self.waiting_label.pack(pady=20, padx=20) self.update() def errormessage(self, dataset): messagebox.showwarning( "Invalid parameters", "Dataset %s was skipped in the computation because of invalid parameters. Please configure Cut-off frequency and / or Filter type." % os.path.basename(dataset.path)) def return_function(self): """ Returns two functions for further use in the model. """ @ri.rternalize def messages(i, r, each): """ Messages function given to the R environment. Gives feedback on the state of the Monte-Carlo simulation. """ self.pb.step() count = np.asarray((i, r)) if (count[0] == -1): self.title("Computation for Dataset %s" % os.path.basename(self.dataset.path)) self.pb.pack(pady=20, padx=20) self.pb_val.set(0) self.stopbutton["state"] = "normal" if self.dataset.metadata[ "Method"] == "HILDE-Homogeneous" or self.dataset.metadata[ "Method"] == "HILDE-Heterogeneous": self.pb.configure(maximum=int( self.dataset.metadata["Repetitions_Hilde"])) else: self.pb.configure( maximum=int(self.dataset.metadata["Repetitions"])) self.labeltext.set( "Currently computing quantile for Dataset:\n%s \n Press Stop! button to stop computation for current dataset." % os.path.basename(self.dataset.path)) if (count[0] == -2): self.pb.pack_forget() self.labeltext.set( "Calculating fit for Dataset:\n%s\nThis computation cannot be interrupted and may take a few minutes." % os.path.basename(self.dataset.path)) self.stopbutton["state"] = "disabled" self.waiting_label.pack(pady=20, padx=20) self.update() return self.stopflag return messages, self.setup_dataset, self.errormessage
class App: def __init__(self, master): self.root = master self.root.protocol("WM_DELETE_WINDOW", self.ask_quit) self.set_app_title(master, "Parsing Tool") self.status = {'parsing': False} self.main_frame = ATIHorizontalGrid(master, expand=True, relief="sunken") self.gr_frame = ATIHorizontalGrid(master, expand=True, relief="sunken") self.input_frame = ATIDashboard(self.main_frame.frame, expand=True) self.input_label = ATILabel(self.input_frame.frame, text='Input Goes Here') self.output_frame = ATIDashboard(self.main_frame.frame, expand=True) self.output_label = ATILabel(self.output_frame.frame, text='Output Appears Here') self.menu_frame = ATIDashboard(self.main_frame.frame, relief="sunken") self.log = ATILog(self.input_frame.frame, scrollbar=True) self.output_log = ATILog(self.output_frame.frame, scrollbar=True) self.output_log.log.config(state="disabled") self.parse_button = ATIButton(self.menu_frame.frame, text="Parse", btn_response=self.parse_btn_response) self.progressbar = Progressbar(mode="determinate", orient="horizontal", length=200) self.gr_label = ATILabel(self.gr_frame.frame, text='PCFG Grammar Rules') self.gr_log = ATILog(self.gr_frame.frame, scrollbar=True) self.gr = PCFG_Grammar('./test.gr') for nt in self.gr.get_non_terminals(): for rule in self.gr.get_rules(nt): self.gr_log.add_text(rule.get_rule_str(), align='left') def set_app_title(self, master, title): top_level = master.winfo_toplevel() top_level.title(title) def parse_btn_response(self): if not self.status['parsing']: self.parse() else: self.process.terminate() def parse(self): self.status['parsing'] = True self.parse_button.button.config(text="Stop") self.output_log.clear(disable=True) sen = Sentence(self.log.retrieve_text()) self.recv_end, send_end = multiprocessing.Pipe(False) self.process = multiprocessing.Process(target=parse_sen, args=(self.gr, sen, send_end, True)) self.progressbar.pack() self.log.log.config(state="disabled") self.root.config(cursor="wait") self.root.update() self.process.start() self.progressbar.start() self.root.after(50, self.check_completed) def check_completed(self): if self.process.is_alive(): self.root.after(50, self.check_completed) else: self.status['parsing'] = False self.parse_button.button.config(text="Parse") self.progressbar.stop() self.progressbar.pack_forget() self.log.log.config(state="normal") try: output_str = self.recv_end.recv() except EOFError: output_str = '' if not output_str == '' and output_str is not None: self.output_log.add_text(TreePrettyPrinter( Tree.fromstring(output_str)), disable=True) self.root.config(cursor="") self.root.update() def ask_quit(self): self.root.destroy() self.root.quit()
class PageScreener(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.flag = 0 self.FLAG_THRD_SCREEN_DATA = 1 # 处理数据队列 self.queData = Queue() # 数据缓存,用于重复使用, self.listData = [] topFrame = tk.Frame(self) self.btnMainPage = tk.Button(topFrame, text="主页面", command=self.on_btn_main_page).pack( side=tk.LEFT, padx=4) # 日期选择 # Calendar((x, y), 'ur').selection() 获取日期,x,y为点坐标 date_start_gain = lambda: [ self.date_start.set(date) for date in [CalendarCustom(None, 'ul').selection()] if date ] self.btnStart = tk.Button(topFrame, text='选股日期:', command=date_start_gain) self.btnStart.pack(side=tk.LEFT, padx=4) # ret = self.btnStart.winfo_geometry() self.date_start = tk.StringVar() ttk.Entry(topFrame, textvariable=self.date_start).pack(side=tk.LEFT) today = get_last_valid_trade_date() dt = datetime.datetime.strptime(today, '%Y%m%d') today = dt.strftime('%Y-%m-%d') self.date_start.set(today) tk.Label(topFrame, text="选股类型:").pack(side=tk.LEFT) self.screenTypeStr = tk.StringVar() cmbScreenType = ttk.Combobox(topFrame, width=15, textvariable=self.screenTypeStr, state='readonly') # Adding combobox drop down list cmbScreenType['values'] = ('平台突破', '均线附近') cmbScreenType.current(1) cmbScreenType.pack(side=tk.LEFT, padx=4) # cmbScreenType.bind("<<ComboboxSelected>>", self.on_cmb_screen_select) # 选股周期数 self.screenIntervalCountStr = tk.StringVar(value='25') # state=tk.DISABLED 默认禁止输入 self.screenIntervalCount = ttk.Entry( topFrame, width=10, textvariable=self.screenIntervalCountStr) self.screenIntervalCount.pack(side=tk.LEFT, padx=4) # 选股周期类型 self.screenIntervalTypeStr = tk.StringVar() cmbScreenInterval = ttk.Combobox( topFrame, width=8, textvariable=self.screenIntervalTypeStr, state='readonly') # Adding combobox drop down list cmbScreenInterval['values'] = ('日', '周', '月') cmbScreenInterval.current(0) cmbScreenInterval.pack(side=tk.LEFT, padx=4) # cmbScreenInterval.bind("<<ComboboxSelected>>", self.on_cmb_screen_interval_select) self.chkST = tk.IntVar() tk.Checkbutton(topFrame, text="包括ST", variable=self.chkST).pack(side=tk.LEFT, padx=4) self.chkTech = tk.IntVar() tk.Checkbutton(topFrame, text="包括科创板", variable=self.chkTech).pack(side=tk.LEFT, padx=4) self.btnStart = tk.Button(topFrame, text="选股", command=self.on_btn_start) self.btnStart.pack(side=tk.LEFT, padx=4) topFrame.pack(side=tk.TOP, fill=tk.BOTH) self.tipsStr = tk.StringVar() tk.Label(topFrame, textvariable=self.tipsStr, font=("simsun", 12)).pack(side=tk.LEFT) self.tipsStr.set('状态:准备...') # Progress bar widget self.progress = Progressbar(topFrame, orient=tk.HORIZONTAL, length=100, mode='determinate') # self.progress.pack(side=tk.LEFT, padx=4) # self.progress.pack_forget() # 列表框 self.frameReport = tk.Frame(self) self.sheet = Sheet(self.frameReport) self.sheet.enable_bindings(( # "single_select", # "single_select" or "toggle_select" # "drag_select", # enables shift click selection as well # "column_drag_and_drop", # "row_drag_and_drop", # "column_select", "row_select", "column_width_resize", "double_click_column_resize", # "row_width_resize", # "column_height_resize", # "arrowkeys", # "row_height_resize", # "double_click_row_resize", # "right_click_popup_menu", # "rc_select", # "rc_insert_column", # "rc_delete_column", # "rc_insert_row", # "rc_delete_row", # "hide_columns", # "copy", # "cut", # "paste", # "delete", # "undo", # "edit_cell" )) self.sheet.pack(side=tk.TOP, fill=tk.BOTH, expand=1) self.frameReport.pack(side=tk.TOP, fill=tk.BOTH, expand=1, pady=4) self.sheet.headers(['编码', '名称', '板块', '收盘价', '涨幅']) self.sheet.refresh() def on_btn_main_page(self): self.controller.show_frame('PageMain') pass def on_btn_start(self): if self.FLAG_THRD_SCREEN_DATA == self.flag & self.FLAG_THRD_SCREEN_DATA: return self.flag |= self.FLAG_THRD_SCREEN_DATA self.progress.pack(side=tk.LEFT, padx=4) # 获取数据线程,取一个放入队列,由另一个线程处理 # 周期参数 iInterval = int(self.screenIntervalCountStr.get()) # TODO 测试代码, iInterval = 43 type = 'd' if self.screenIntervalTypeStr.get() == '周': type = 'w' elif self.screenIntervalTypeStr.get() == '月': type = 'm' start_date = self.date_start.get().replace('-', '') # 多获取 10 组数据 thrd = threading.Thread(target=dbService.get_data_thread, args=( iInterval + 30, type, self.chkST.get(), self.chkTech.get(), self.queData, start_date, )) thrd.setDaemon(True) # 守护线程 thrd.start() cnt = self.sheet.get_total_rows() for i in range(cnt): self.sheet.delete_row(i) self.sheet.refresh() if self.screenTypeStr.get() == '平台突破': thrd = threading.Thread(target=self.screen_platform, args=(self.queData, )) thrd.setDaemon(True) # 守护线程 thrd.start() elif self.screenTypeStr.get() == '均线附近': thrd = threading.Thread(target=self.screen_ma_around, args=(self.queData, )) thrd.setDaemon(True) # 守护线程 thrd.start() pass def screen_platform(self, in_q): """ 平台突破 找出N天内创新高的股票, :return: """ self.btnStart['state'] = 'disabled' self.tipsStr.set('状态:正在读取数据,请耐心等待...') # 准备数据 iInterval = int(self.screenIntervalCountStr.get()) type = 'd' if self.screenIntervalTypeStr.get() == '周': type = 'w' elif self.screenIntervalTypeStr.get() == '月': type = 'm' self.progress['value'] = 5 # root.update_idletasks() # 避免中间缺数据 * 2 count = iInterval + 5 datas = dbService.get_data(count, type, self.chkST.get(), self.chkTech.get()) screenCount = 0 self.tipsStr.set('状态:正在选股,请耐心等待...') per_interval = len(datas) / 95 step_count = 0 progress_step = 5 pickup_list = [] for it in datas: step_count += 1 if step_count >= per_interval: step_count = 0 progress_step += 1 self.progress['value'] = progress_step # root.update_idletasks() result = platform_break_through(it, iInterval) if result: screenCount += 1 print(result) pickup_list.append(result) pickup_sorted = sorted(pickup_list, key=itemgetter(3), reverse=True) for it in pickup_sorted: self.sheet.insert_row(values=it) self.sheet.refresh() self.progress['value'] = 100 # root.update_idletasks() self.tipsStr.set('状态:共选出 {:d} 只股票'.format(screenCount)) self.flag &= (~self.FLAG_THRD_SCREEN_DATA) self.btnStart['state'] = 'normal' self.progress.pack_forget() print("screen_platform exit ==========") pass def screen_ma_around(self, in_q): """ 参数 120,2 表示 120 日均线,2%附近 ma120*0.98 < 收盘价 < ma120*1.2 :return: """ self.btnStart['state'] = 'disabled' screenCount = 0 self.tipsStr.set('状态:正在处理,请耐心等待...') # 准备数据 param = [(self.screenIntervalCountStr.get())] per_interval = get_code_count() / 95 step_count = 0 progress_step = 5 pickup_list = [] while True: try: it = in_q.get_nowait() except queue.Empty as e1: continue if it is None: break step_count += 1 if step_count >= per_interval: step_count = 0 progress_step += 1 self.progress['value'] = progress_step result = ma25_around(it, param) if result: screenCount += 1 print(result) self.sheet.insert_row(values=result) # self.sheet.refresh() # pickup_list.append(result) # pickup_sorted = sorted(pickup_list, key=itemgetter(3), reverse=True) # # for it in pickup_sorted: # self.sheet.insert_row(values=it) self.progress['value'] = 100 # root.update_idletasks() self.tipsStr.set('状态:共选出 {:d} 只股票'.format(screenCount)) self.flag &= (~self.FLAG_THRD_SCREEN_DATA) self.btnStart['state'] = 'normal' self.progress.pack_forget() self.progress['value'] = 0 print("screen_ma_around exit ==========") pass def tree_solution_selected(self, selected): print('tree_solution_selected items:', selected) pass
class Sender_Connect(tk.Frame): ''' -Create a socket connection -scans for recivers -select reciver -file transer -End of socket connection ''' def __init__(self, parent, root, user_name, files): tk.Frame.__init__(self, parent) self.root = root self.parent = parent self.files = files self.title = tk.Label(self, text="Sending Files Boss ", relief='solid', fg='blue', bg='red', font=("arial", 16, "bold")) self.title.pack(fill=tk.BOTH, padx=2, pady=2) self.user_name = user_name self.sender_socket = socket.socket() # Create a socket object self.port = 2500 self.recievers = [] #variable to check if something is still loading in page self.waiting = False #scan for recivers self.show_scanning() def show_scanning(self): #Show loading animation self.show_loading() self.s = threading.Thread(target=self.create_connection, daemon=True) self.s.start() self.title.configure(text="Searching for recivers") def show_loading(self): self.waiting = True #Loading animation GUI self.update() theme = Style() theme.theme_use("default") theme.configure("green.Horizontal.TProgressbar", background="green", thickness=100) #progress bar self.bar = Progressbar(self, style="blue.Horizontal.TProgressbar", orient="horizontal", mode="indeterminate", length=300) self.bar.pack(fill=tk.BOTH, pady=30, padx=10) self.loading_anim = threading.Thread(target=self.loading, daemon=True) self.loading_anim.start() def loading(self): while self.waiting: self.bar['value'] += 1 self.update_idletasks() time.sleep(0.01) self.bar.pack_forget() def create_connection(self): self.get_recivers() def get_recivers(self): ''' scan network and display who are all waiting to recive file -select reciver to send file ''' #For testing self.recievers = [["Ram", '192.168.1.7'], ["Sam", '192.168.1.7']] self.sender_socket.connect(('192.168.1.7', self.port)) self.sender_socket.send(str("name").encode()) data = self.sender_socket.recv(1024) ''' D = Network('192.168.1.1') D.scan_network() port = 2500 for host in D.host_list: try: self.sender_socket.connect((host, self.port)) self.sender_socket.send(str("name").encode()) data = self.sender_socket.recv(1024) self.recievers.append([str(data,"utf-8"),host]) except: print("Something happend") print("Done checking") print("Recivers available ") print("------------------") ''' for name, ip in self.recievers: print(name, '----->', ip) print() self.waiting = False self.title.configure(text="Please Select Reciver") self.recievers_list_frame = tk.Frame(self) for name, ip in self.recievers: tk.Button(self.recievers_list_frame, text=name, relief=tk.GROOVE, bg="lime", fg="blue", font=("arial", 16, "bold"), command=lambda: self.send_files(name, ip)).pack( fill=tk.BOTH, pady=15, padx=10, side=tk.TOP) tk.Button(self.recievers_list_frame, text="Rescan", relief=tk.GROOVE, bg="orange", fg="red", font=("arial", 16, "bold"), command=self.rescan).pack(fill=tk.BOTH, pady=15, padx=30, side=tk.TOP) self.recievers_list_frame.pack(fill=tk.BOTH, pady=30, expand=tk.YES) def rescan(self): self.recievers_list_frame.pack_forget() self.show_scanning() def get_file_names(self, files): files = [file_path.split("/")[-1] for file_path in files] return ' '.join(files) def send_files(self, name, ip): ''' name -> username of reciver ip -> ip addr of reciver ''' self.sender_socket = socket.socket() self.sender_socket.connect((ip, self.port)) self.sender_socket.send(self.user_name.encode()) self.show_loading() self.sender_socket.send(self.get_file_names(self.files).encode()) file_sizes = ' '.join( [str(os.path.getsize(file_path)) for file_path in self.files]) self.sender_socket.send(file_sizes.encode()) print("Sending files") for file_name in self.files: print(file_name) with open(file_name, 'rb') as f: chunk = 1 while (chunk): chunk = f.read(1024 * 1024) self.sender_socket.send(chunk) print('Done sending') self.sender_socket.close()
relief=RAISED, command=open_file) b.pack(side="top", ipadx=3, ipady=3) input_file = Label(master, font=("Lato", 10), anchor=W, justify=LEFT, background=grey) input_file.pack(pady=(0, 5)) foot_frame = Frame(master) foot_frame.pack(side="bottom", fill="x") progress_frame = Frame(master) progress_frame.configure(background=grey) progress_frame.pack() btn('Convert', convert) btn('Reset', reset) progress = Progressbar(progress_frame, orient=HORIZONTAL, length=200, mode="determinate", takefocus=True, maximum=1500) progress.pack_forget() footer(foot_frame) mainloop()
class GUI: def __init__(self): self.ACTIVEBACKGROUND = consts.ACTIVEBACKGROUND self.ACTIVEBUTTONBACKGROUND = consts.ACTIVEBUTTONBACKGROUND self.ACTIVEFIELDBACKGROUND = consts.ACTIVEFIELDBACKGROUND self.ACTIVEFRAMEBORDER = consts.ACTIVEFRAMEBORDER self.TEXTCOLOR = consts.TEXTCOLOR self.INACTIVEBACKGROUND = consts.INACTIVEBACKGROUND self.INACTIVEBUTTONBACKGROUND = consts.INACTIVEBUTTONBACKGROUND self.INACTIVEFIELDBACKGROUND = consts.INACTIVEFIELDBACKGROUND self.INACTIVEFRAMEBORDER = consts.INACTIVEFRAMEBORDER self.root = Tk() self.root.title("YSU Thermography") self.root['bg'] = self.ACTIVEBACKGROUND # root.iconbitmap("images/YSU_Logo") self.progressbar = None # Get description dictionary self.descriptions = get_description_dict() # Creating variables for checkboxes to change self.dataset = None self.viewer = None # Dataset related variables self.remove_top = BooleanVar(False) self.remove_bot = BooleanVar(False) self.scale_factor = IntVar(value=1) self.start_frame = IntVar(value=-1) self.end_frame = IntVar(value=-1) # Viewer related variables self.contour_threshold = IntVar(value=None) self.follow = StringVar(value=None) self.follow_size = IntVar(value=20) self.info_pane = StringVar(value=None) self.frame_delay = IntVar(value=1) self.framerate = IntVar(value=60) # Composite related variables self.composite_threshold = IntVar(value=None) self.generate_img = BooleanVar(False) self.save_frame = BooleanVar() self.play_video = BooleanVar(False) self.save_video = BooleanVar(False) self.gen_threshold_img = BooleanVar(False) self.data_set = BooleanVar() self.gradient_plots = BooleanVar() self.pixel_temp_range = BooleanVar() self.tempData = StringVar() self.genthreshold_threshold = StringVar() self.save_FrameNumber = StringVar() self.save_ImageNumber = StringVar() self.play_scaleFactor = StringVar() self.play_frameDelay = StringVar() self.play_pixelAroundMax = StringVar() self.play_contourTempThresh = StringVar() self.play_contourPixelRange = StringVar() self.play_frameRate = StringVar() self.play_removeTopReflection = BooleanVar() self.play_removeBottomReflection = BooleanVar() self.play_displayMeltPool = BooleanVar() self.play_saveStartFrame = StringVar() self.play_saveEndFrame = StringVar() self.play_displayContour = BooleanVar() self.plot_PixelLocX = StringVar() self.plot_PixelLocY = StringVar() self.plot_TempThresh = StringVar() self.plot_StartFrame = StringVar() self.plot_EndFrame = StringVar() self.grad_mag = BooleanVar() self.grad_angle = BooleanVar() self.grad_2dHist = BooleanVar() self.grad_scatter = BooleanVar() self.grad_hexBin = BooleanVar() self.grad_3D = BooleanVar() self.plot_line = BooleanVar() self.grad_all = BooleanVar() # Creating Frame Sections self.filePanel = Frame(self.root, bg=self.ACTIVEBACKGROUND) self.filePanel.pack(side=TOP, fill=BOTH, pady=10) self.dataset_panel = Frame(self.root, bg=self.ACTIVEBACKGROUND) self.dataset_panel.pack(side=TOP, fill=BOTH, pady=10) self.viewer_panel = Frame(self.root, bg=self.ACTIVEBACKGROUND) self.viewer_panel.pack(side=TOP, fill=BOTH, pady=10) self.optionsPanel = Frame(self.root, bg=self.ACTIVEBACKGROUND, bd=1, highlightthickness=1, highlightcolor=self.ACTIVEFRAMEBORDER, highlightbackground=self.ACTIVEFRAMEBORDER, padx=5, relief=FLAT) self.optionsPanel.pack(fill=BOTH) self.optionsPanel.columnconfigure(0, weight=1) self.optionsPanel.columnconfigure(1, weight=1) self.optionsPanel.rowconfigure(0, weight=1) self.optionsPanel.rowconfigure(1, weight=1) self.optionsPanel.rowconfigure(2, weight=1) self.optionsPanel.rowconfigure(3, weight=1) # Building all frames self.buildFileFrame() self.build_dataset_frame() self.build_viewer_frame() self.build_composite_frame() self.buildPlotOptionsFrame() self.buildGradOptionsFrame() # Main GUI loop self.root.mainloop() def gradSelectAll(self): if self.grad_all.get(): self.grad_mag.set(1) self.grad_angle.set(1) self.grad_2dHist.set(1) self.grad_scatter.set(1) self.grad_hexBin.set(1) self.grad_3D.set(1) def buildFileFrame(self): tempDataLabel = Label(self.filePanel, text="File Path Build Data Folder: ", padx=0, pady=0, bg=self.ACTIVEBACKGROUND, foreground=self.TEXTCOLOR) ToolTip.createToolTip(tempDataLabel, self.descriptions['temp_data']) tempDataLabel.pack(side=LEFT, fill=BOTH) tempDataEntry = Entry(self.filePanel, width=75, textvariable=self.tempData, relief=FLAT, bg=self.ACTIVEFIELDBACKGROUND, foreground=self.TEXTCOLOR) tempDataEntry.pack(side=LEFT, fill=BOTH) tempDataBrowse = Button( self.filePanel, text="Browse", command=lambda: handler.browseFiles(self, tempDataEntry), bd=2, bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT, padx=0, pady=0, activeforeground=self.TEXTCOLOR, foreground=self.TEXTCOLOR) tempDataBrowse.pack(side=LEFT) def build_dataset_frame(self): # Main Frame self.dataset_frame = func.buildOuterLabelFrame(obj=self, root=self.dataset_panel, label='Dataset Options') self.dataset_frame.pack(fill=BOTH) self.dataset_frame.columnconfigure(0, weight=1) self.dataset_frame.columnconfigure(1, weight=1) self.dataset_frame.columnconfigure(2, weight=1) self.dataset_frame.columnconfigure(3, weight=1) self.dataset_frame.columnconfigure(4, weight=1) self.dataset_frame.rowconfigure(0, weight=1) # Frame to hold checkbox to remove top reflection remove_top_label = func.buildInnerLabelFrame( obj=self, root=self.dataset_frame, label='Remove Top Reflection') ToolTip.createToolTip(remove_top_label, self.descriptions['remove_top']) remove_top_label.grid(row=0, column=0, sticky=W + E + N + S) remove_top_cb = func.buildFunctionCheckButton(obj=self, root=remove_top_label, variable=self.remove_top, command=None) remove_top_cb.pack() # Frame to hold checkbox to remove bottom reflection remove_bot_label = func.buildInnerLabelFrame( obj=self, root=self.dataset_frame, label='Remove Bottom Reflection') ToolTip.createToolTip(remove_bot_label, self.descriptions['remove_bot']) remove_bot_label.grid(row=0, column=1, sticky=W + E + N + S) remove_bot_cb = func.buildFunctionCheckButton(obj=self, root=remove_bot_label, variable=self.remove_bot, command=None) remove_bot_cb.pack() # Frame to hold entry for scale factor scale_factor_label = func.buildInnerLabelFrame(obj=self, root=self.dataset_frame, label='Scale Factor') ToolTip.createToolTip(scale_factor_label, self.descriptions['scale_factor']) scale_factor_label.grid(row=0, column=2, sticky=W + E + N + S) scale_factor_entry = func.buildEntry(obj=self, root=scale_factor_label, textvariable=self.scale_factor) scale_factor_entry.pack() # Frame to hold entry for start frame start_frame_label = func.buildInnerLabelFrame(obj=self, root=self.dataset_frame, label='Start Frame') ToolTip.createToolTip(start_frame_label, self.descriptions['start_frame']) start_frame_label.grid(row=0, column=3, sticky=W + E + N + S) start_frame_entry = func.buildEntry(obj=self, root=start_frame_label, textvariable=self.start_frame) start_frame_entry.pack() # Frame to hold entry for end frame end_frame_label = func.buildInnerLabelFrame(obj=self, root=self.dataset_frame, label='End Frame') ToolTip.createToolTip(end_frame_label, self.descriptions['end_frame']) end_frame_label.grid(row=0, column=4, sticky=W + E + N + S) end_frame_entry = func.buildEntry(obj=self, root=end_frame_label, textvariable=self.end_frame) end_frame_entry.pack() def build_viewer_frame(self): # Main Frame self.viewer_frame = func.buildOuterLabelFrame(obj=self, root=self.viewer_panel, label='Viewer Options') self.viewer_frame.pack(fill=BOTH) self.viewer_frame.columnconfigure(0, weight=1) self.viewer_frame.columnconfigure(1, weight=1) self.viewer_frame.columnconfigure(2, weight=1) self.viewer_frame.columnconfigure(3, weight=1) self.viewer_frame.columnconfigure(4, weight=1) self.viewer_frame.rowconfigure(0, weight=1) # Frame to hold entry for contour threshold contour_thresh_label = func.buildInnerLabelFrame( obj=self, root=self.viewer_frame, label='Contour Threshold') ToolTip.createToolTip(contour_thresh_label, self.descriptions['contour_threshold']) contour_thresh_label.grid(row=0, column=0, sticky=W + E + N + S) contour_thresh_entry = func.buildEntry( obj=self, root=contour_thresh_label, textvariable=self.contour_threshold) contour_thresh_entry.pack() # Radio buttons to determine what to focus frame on follow_buttons_dict = { 'Contour': 'contour', 'Max Temp': 'max', 'None': None } follow_buttons_frame = self.build_radio_button_set( self.viewer_frame, 'Frame focus', follow_buttons_dict, self.follow) follow_buttons_frame.grid(row=0, column=1, sticky=W + E + N + S) # Frame to hold entry for follow_size follow_size_frame = func.buildInnerLabelFrame( obj=self, root=self.viewer_frame, label='Focused frame size') ToolTip.createToolTip(follow_size_frame, self.descriptions['follow_size']) follow_size_frame.grid(row=0, column=2, sticky=W + E + N + S) follow_size_entry = func.buildEntry(obj=self, root=follow_size_frame, textvariable=self.follow_size) follow_size_entry.pack() # Radio buttons to determine what info pane to show info_buttons_dict = { 'Contour': 'contour', 'Meltpool': 'mp', 'None': None } info_buttons_frame = self.build_radio_button_set( self.viewer_frame, 'Info Pane', info_buttons_dict, self.info_pane) info_buttons_frame.grid(row=0, column=3, sticky=W + E + N + S) execute_buttons_frame = func.buildInnerLabelFrame( obj=self, root=self.viewer_frame, label=None) execute_buttons_frame.columnconfigure(0, weight=1) execute_buttons_frame.columnconfigure(1, weight=1) execute_buttons_frame.rowconfigure(0, weight=1) execute_buttons_frame.rowconfigure(1, weight=1) execute_buttons_frame.rowconfigure(2, weight=1) execute_buttons_frame.grid(row=0, column=4, sticky=W + E + N + S) play_button = Button(execute_buttons_frame, text='Play Video', command=lambda: handler.play(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) play_button.grid(row=0, column=0) frame_delay_entry = func.buildEntry(obj=self, root=execute_buttons_frame, textvariable=self.frame_delay) frame_delay_entry.grid(row=0, column=1) save_video_button = Button(execute_buttons_frame, text='Save Video', command=lambda: handler.save(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) save_video_button.grid(row=1, column=0) framerate_entry = func.buildEntry(obj=self, root=execute_buttons_frame, textvariable=self.framerate) framerate_entry.grid(row=1, column=1) save_frame_button = Button(execute_buttons_frame, text='Save Frames', command=lambda: handler.save_frames(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) save_frame_button.grid(row=2, column=0) def build_composite_frame(self): self.composite_frame = func.buildOuterLabelFrame( obj=self, root=self.optionsPanel, label='Composite options') self.composite_frame.pack(fill=BOTH) threshold_frame = func.buildInnerLabelFrame( obj=self, root=self.composite_frame, label='Temperature Threshold') ToolTip.createToolTip(threshold_frame, self.descriptions['threshold']) threshold_frame.pack(side=LEFT, padx=10) threshold_input = func.buildEntry( obj=self, root=threshold_frame, textvariable=self.composite_threshold) threshold_input.pack() normal_composite_button = Button( self.composite_frame, text='Create Composite Image', command=lambda: handler.save_thresh_img(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) normal_composite_button.pack(side=LEFT, padx=40) integration_composite_button = Button( self.composite_frame, text='Integration Composite', command=lambda: handler.save_integration_img(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) integration_composite_button.pack(side=LEFT, padx=40) other_composite_frame = func.buildInnerLabelFrame( obj=self, root=self.composite_frame, label='Other Composite Images') other_composite_frame.pack(side=RIGHT, padx=40) average_composite_button = Button( other_composite_frame, text='Average Composite', command=lambda: handler.save_avg_composite(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) average_composite_button.pack() max_temp_composite_button = Button( other_composite_frame, text='Max Temp Composite', command=lambda: handler.save_max_composite(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) max_temp_composite_button.pack() hotspot_composite_button = Button( other_composite_frame, text='Hot Spot Composite', command=lambda: handler.save_hotspot_composite(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) hotspot_composite_button.pack() def buildPlotOptionsFrame(self): self.plotOptionsFrame = func.buildOuterLabelFrame( obj=self, root=self.optionsPanel, label='Plot Options') self.plotOptionsFrame.pack(fill=BOTH) self.plotOptionsFrame.columnconfigure(0, weight=1) self.plotOptionsFrame.columnconfigure(1, weight=1) self.plotOptionsFrame.columnconfigure(2, weight=1) self.plotOptionsFrame.rowconfigure(0, weight=1) self.plotOptionsFrame.rowconfigure(1, weight=1) self.plotOptionsFrame.rowconfigure(2, weight=1) pixelLocationFrame = func.buildInnerLabelFrame( obj=self, root=self.plotOptionsFrame, label='Pixel Location') ToolTip.createToolTip(pixelLocationFrame, self.descriptions['plot_pixel_location']) pixelLocationFrame.grid(row=0, column=1, sticky=W + E + N + S) pixelLocationFrame.columnconfigure(0, weight=1) pixelLocationFrame.columnconfigure(1, weight=1) pixelLocationFrame.columnconfigure(2, weight=1) pixelLocationFrame.columnconfigure(3, weight=1) pixelLocationFrame.rowconfigure(0, weight=1) pixelXLocationInput = func.buildEntry(obj=self, root=pixelLocationFrame, textvariable=self.plot_PixelLocX) pixelXLocationInput.grid(row=0, column=0, sticky=W + E + N + S) comma = Label(pixelLocationFrame, text=",", bd=0, highlightthickness=0, bg=self.ACTIVEBACKGROUND) comma.grid(row=0, column=1, sticky=W + E + N + S) pixelYLocationInput = func.buildEntry(obj=self, root=pixelLocationFrame, textvariable=self.plot_PixelLocY) pixelYLocationInput.grid(row=0, column=2, sticky=W + E + N + S) select_pixels_button = Button( pixelLocationFrame, text='Select Pixels', command=lambda: handler.select_pixels(self), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) select_pixels_button.grid(row=0, column=3) histthreshFrame = func.buildInnerLabelFrame(obj=self, root=self.plotOptionsFrame, label='Temp Thresh') ToolTip.createToolTip(histthreshFrame, self.descriptions['threshold']) histthreshFrame.grid(row=0, column=0, sticky=W + E + N + S) histthreshInput = func.buildEntry(obj=self, root=histthreshFrame, textvariable=self.plot_TempThresh) histthreshInput.insert(END, 200) histthreshInput.pack() frameRangeFrame = func.buildInnerLabelFrame(obj=self, root=self.plotOptionsFrame, label='Frame Range') ToolTip.createToolTip(frameRangeFrame, self.descriptions['range']) frameRangeFrame.grid(row=0, column=2, sticky=W + E + N + S) frameRangeFrame.columnconfigure(0, weight=1) frameRangeFrame.columnconfigure(1, weight=1) frameRangeFrame.rowconfigure(0, weight=1) plotStartFrameInput = func.buildEntry( obj=self, root=frameRangeFrame, textvariable=self.plot_StartFrame) plotStartFrameInput.insert(END, 0) plotStartFrameInput.grid(row=0, column=0) plotEndFrameInput = func.buildEntry(obj=self, root=frameRangeFrame, textvariable=self.plot_EndFrame) plotEndFrameInput.insert(END, -1) plotEndFrameInput.grid(row=0, column=1) def buildGradOptionsFrame(self): self.gradFrame = func.buildOuterLabelFrame(obj=self, root=self.optionsPanel, label='Gradient Plots') self.gradFrame.pack(fill=BOTH) emptyFrame = Frame(self.gradFrame, bg=self.ACTIVEBACKGROUND) emptyFrame.pack(anchor=CENTER) gradMagFrame = func.buildInnerLabelFrame( obj=self, root=emptyFrame, label='Gradient Magnitude Plot') gradMagFrame.grid(row=0, column=0) gradMagCheckButton = func.buildFlagCheckButton(obj=self, root=gradMagFrame, variable=self.grad_mag) gradMagCheckButton.pack() gradAngleFrame = func.buildInnerLabelFrame(obj=self, root=emptyFrame, label='Gradient Angle Plot') gradAngleFrame.grid(row=0, column=1) gradAngleCheckButton = func.buildFlagCheckButton( obj=self, root=gradAngleFrame, variable=self.grad_angle) gradAngleCheckButton.pack() grad2dHistFrame = func.buildInnerLabelFrame( obj=self, root=emptyFrame, label='Gradient 2D Histogram') grad2dHistFrame.grid(row=0, column=2) grad2dHistCheckButton = func.buildFlagCheckButton( obj=self, root=grad2dHistFrame, variable=self.grad_2dHist) grad2dHistCheckButton.pack() gradScatterFrame = func.buildInnerLabelFrame( obj=self, root=emptyFrame, label='Gradient Scatter Plot') gradScatterFrame.grid(row=1, column=0) gradScatterCheckButton = func.buildFlagCheckButton( obj=self, root=gradScatterFrame, variable=self.grad_scatter) gradScatterCheckButton.pack() gradHexBinFrame = func.buildInnerLabelFrame( obj=self, root=emptyFrame, label='Gradient Hex Bin Plot') gradHexBinFrame.grid(row=1, column=1) gradHexBinCheckButton = func.buildFlagCheckButton( obj=self, root=gradHexBinFrame, variable=self.grad_hexBin) gradHexBinCheckButton.pack() grad3dFrame = func.buildInnerLabelFrame(obj=self, root=emptyFrame, label='3D Plot') grad3dFrame.grid(row=1, column=2) grad3dCheckButton = func.buildFlagCheckButton(obj=self, root=grad3dFrame, variable=self.grad_3D) grad3dCheckButton.pack() tempHistoryFrame = func.buildInnerLabelFrame( obj=self, root=emptyFrame, label='Temperature History') tempHistoryFrame.grid(row=2, column=0) tempHistoryButton = func.buildFlagCheckButton( obj=self, root=tempHistoryFrame, variable=self.plot_line) tempHistoryButton.pack() gradAllFrame = func.buildInnerLabelFrame(obj=self, root=emptyFrame, label='All Plots') gradAllFrame.grid(row=2, column=1) gradAllCheckButton = func.buildFunctionCheckButton( obj=self, root=gradAllFrame, variable=self.grad_all, command=self.gradSelectAll) gradAllCheckButton.pack() create_plots_button = Button(self.plotOptionsFrame, text='Create Plots', command=lambda: handler.create_plots( self=self, pixel=(int(self.plot_PixelLocX.get( )), int(self.plot_PixelLocY.get()))), bg=self.ACTIVEBUTTONBACKGROUND, relief=FLAT) create_plots_button.grid(row=4, column=2) def build_radio_button_set(self, root, label: str, buttons: dict, variable): radio_frame = func.buildInnerLabelFrame(obj=self, root=root, label=label) for key in buttons: Radiobutton(radio_frame, text=key, variable=variable, value=buttons[key], bg=self.ACTIVEBACKGROUND, bd=0, highlightthickness=0).pack() return radio_frame def create_progress_bar(self): self.progressbar = Progressbar(self.root, orient=HORIZONTAL, length=500, mode='determinate') self.progressbar.pack(pady=10) def remove_progress_bar(self): self.progressbar.pack_forget() self.progressbar = None def update_progress_bar(self, iteration: int, total: int): progress = int(100 * (iteration / total)) self.progressbar['value'] = progress self.root.update_idletasks()
class GameWindow: def __init__(self, master, char): self.settingBox = Frame(master, height=450, width=1000, background="white") self.settingBox.pack(side=TOP) self.settingBox.pack_propagate(0) self.battleOptionsBox = Frame(self.settingBox, height=450, width=200, background="grey") self.battleOptionsBox.pack(side=LEFT) self.battleOptionsBox.pack_propagate(0) self.settingBoxCanvas = Canvas(self.settingBox, height=450, width=596) self.settingBoxCanvas.pack(side=LEFT) self.settingBoxCanvas.pack_propagate(0) self.canvasImg = PhotoImage(file="cave.png") self.background = self.settingBoxCanvas.create_image( 300, 225, image=self.canvasImg) self.rightMenuBox = Frame(self.settingBox, height=450, width=200, background="grey") self.rightMenuBox.pack(side=RIGHT) self.rightMenuBox.pack_propagate(0) self.bottomFrame = Frame(master, height=150, width=1000, background="green") self.bottomFrame.pack(side=BOTTOM) self.playerHealthArea = Frame(self.bottomFrame, height=150, width=200, background="grey") self.playerHealthArea.pack(side=LEFT) self.playerHealthArea.pack_propagate(0) self.textArea = Frame(self.bottomFrame, height=150, width=600, background="black") self.textArea.pack(side=LEFT) self.textArea.pack_propagate(0) self.firstLineText = Label(self.textArea, text="", font=("helvetica", 20), fg="white", bg="black") self.firstLineText.pack(side=TOP) self.secondLineText = Label(self.textArea, text="", font=("helvetica", 20), fg="white", bg="black") self.secondLineText.pack() self.thirdLineText = Label(self.textArea, text="", font=("helvetica", 20), fg="white", bg="black") self.thirdLineText.pack() self.enemyHealthArea = Frame(self.bottomFrame, height=150, width=200, background="grey") self.enemyHealthArea.pack(side=LEFT) self.enemyHealthArea.pack_propagate(0) self.playerHealthTitle = Label(self.playerHealthArea, text="Health", font=("Helvetica", 25), bg="grey") self.playerHealthTitle.pack(side=TOP) self.playerHealthText = Label(self.playerHealthArea, text=str(char.health) + " / " + str(char.maxHealth), font=("Helvetica", 20), bg="Grey") self.playerHealthText.pack() self.healthBarVar = IntVar() self.healthBarVar.set(char.health) self.playerHealthBar = Progressbar(self.playerHealthArea, orient=HORIZONTAL, length=100, variable=self.healthBarVar, maximum=char.maxHealth) self.playerHealthBar.pack() self.testHealthButton = Button( self.playerHealthArea, text="test", command=lambda: self.decreaseHealth(char)) self.testHealthButton.pack() self.mainMenu = Menu() master.config(menu=self.mainMenu) self.fileMenu = Menu() self.mainMenu.add_cascade(label="File", menu=self.fileMenu) self.fileMenu.add_command(label="Save...", command=lambda: self.saveCharacter(char)) self.fileMenu.add_command(label="Open...", command=lambda: self.openCharacter(char)) self.fileMenu.add_separator() self.fileMenu.add_command(label="Exit", command=master.quit) def saveCharacter( self, CHARACTER ): # saves the current character object w/ all its attributes to a pickle file characterFile = open("character.pickle", "wb") pickle.dump(CHARACTER, characterFile) def openCharacter( self, CHARACTER ): # retrieves the pickle file and sets the current character object's attributes to that of the saved char. characterFile = open("character.pickle", "rb") savedCharacter = pickle.load(characterFile) CHARACTER.XP = savedCharacter.XP CHARACTER.level = savedCharacter.level CHARACTER.health = savedCharacter.health CHARACTER.maxHealth = savedCharacter.maxHealth CHARACTER.inventory = savedCharacter.inventory CHARACTER.weapon = savedCharacter.weapon CHARACTER.armor = savedCharacter.health CHARACTER.attackValue = savedCharacter.attackValue CHARACTER.defenseValue = savedCharacter.defenseValue self.updateHealthBar(CHARACTER) def displayEnemy(self, ENEMY, charact): self.enemyHealthTitle = Label(self.enemyHealthArea, text=ENEMY.name + " Health", font=("Helvetica", 20), bg="grey") self.enemyHealthTitle.pack(side=TOP) self.enemyImage = self.settingBoxCanvas.create_image(300, 225, image=ENEMY.image) self.enemyHealthText = Label(self.enemyHealthArea, text=str(ENEMY.health) + " / " + str(ENEMY.maxHealth), font=("Helvetica", 20), bg="Grey") self.enemyHealthText.pack() self.enemyHealthBarVar = IntVar() self.enemyHealthBarVar.set(ENEMY.health) self.enemyHealthBar = Progressbar(self.enemyHealthArea, orient=HORIZONTAL, length=100, variable=self.enemyHealthBarVar, maximum=ENEMY.maxHealth) self.enemyHealthBar.pack() self.testEnemyHealthButton = Button( self.enemyHealthArea, text="test", command=lambda: ENEMY.attack(charact, self)) self.testEnemyHealthButton.pack() def hideEnemy(self): self.enemyHealthText.pack_forget() self.enemyHealthTitle.pack_forget() self.enemyHealthBar.pack_forget() self.testEnemyHealthButton.pack_forget() self.settingBoxCanvas.delete(self.enemyImage) def decreaseHealth(self, CHARACTER): if CHARACTER.health > 0: CHARACTER.health -= 1 self.updateHealthBar(CHARACTER) def updateHealthBar(self, CHARACTER): if isinstance(CHARACTER, Character): self.healthBarVar.set(CHARACTER.health) self.playerHealthText.config(text=str(CHARACTER.health) + " / " + str(CHARACTER.maxHealth)) elif isinstance(CHARACTER, Enemy): self.enemyHealthBarVar.set(CHARACTER.health) self.enemyHealthText.config(text=str(CHARACTER.health) + " / " + str(CHARACTER.maxHealth)) def displayText(self, text): self.firstLineText.config(text='') self.secondLineText.config(text='') self.thirdLineText.config(text='') if len(text) > 40: count = 0 self.firstLine = '' self.secondLine = '' self.thirdLine = "" self.firstLineFull = False self.secondLineFull = False for i in text: count += 1 if count <= 38: self.firstLine = self.firstLine + i elif count > 38 and i != " " and not self.firstLineFull: self.firstLine = self.firstLine + i elif count > 38 and i == " ": self.firstLineFull = True if self.firstLineFull and not self.secondLineFull and count < 90: self.secondLine = self.secondLine + i elif self.firstLineFull and count > 80 and i != " " and not self.secondLineFull: self.secondLine = self.secondLine + i elif count > 85 and i == " ": self.secondLineFull = True if count > 90 and self.firstLineFull and self.secondLineFull: self.thirdLine = self.thirdLine + i else: self.firstLine = text self.secondLine = '' self.thirdLine = "" self.firstLineText.config(text=self.firstLine) self.secondLineText.config(text=self.secondLine) self.thirdLineText.config(text=self.thirdLine) def displayBattleMenu(self, char, ENEMY, master): self.battleMenuTitle = Label(self.battleOptionsBox, text="Battle Menu", font=("helvetica", 28), bg="grey") self.battleMenuTitle.pack(side=TOP) self.attackButton = Button( self.battleOptionsBox, text="Attack", width=8, font=("helvetica", 20), pady=2, command=lambda: char.attack(ENEMY, self, master)) self.attackButton.pack() self.attackButton.bind("<Enter>", self.attackDescription) self.defendButton = Button( self.battleOptionsBox, text="Defend", width=8, font=("helvetica", 20), pady=2, command=lambda: char.defend(ENEMY, self, master)) self.defendButton.pack() self.defendButton.bind("<Enter>", self.defendDescription) self.useItemButton = Button( self.battleOptionsBox, text="Use Item", width=8, font=("helvetica", 20), pady=2, command=lambda: self.displayCharacterInventory( char, ENEMY, master)) self.useItemButton.pack() self.useItemButton.bind("<Enter>", self.useItemDescription) self.magicButton = Button(self.battleOptionsBox, text="Magic", width=8, font=("helvetica", 20), pady=2) self.magicButton.pack() self.magicButton.bind("<Enter>", self.magicDescription) self.fleeButton = Button( self.battleOptionsBox, text="Flee", width=8, font=("helvetica", 20), pady=2, command=lambda: char.flee(ENEMY, self, master)) self.fleeButton.pack() self.fleeButton.bind("<Enter>", self.fleeDescription) def hideBattleMenu(self): self.useItemButton.pack_forget() self.attackButton.pack_forget() self.magicButton.pack_forget() self.fleeButton.pack_forget() self.defendButton.pack_forget() self.battleMenuTitle.pack_forget() def displayCharacterInventory(self, CHARACTER, ENEMY, master): print(CHARACTER.inventory) self.hideBattleMenu() self.inventoryTitle = Label(self.battleOptionsBox, text="Inventory", font=("helvetica", 28), bg="grey") self.inventoryTitle.pack(side=TOP) for key in CHARACTER.inventory: if key == "Gold" and (CHARACTER.inventory["Gold"])["Amount"] > 0: self.goldButton = Button( self.battleOptionsBox, text="x" + str( (CHARACTER.inventory["Gold"])["Amount"]) + " Gold", width=8, font=("helvetica", 20), pady=2, command=lambda: self.displayText( "What are you gonna do, pay him off?")) self.goldButton.pack() self.goldButton.bind( "<Enter>", lambda e: self.displayText( (CHARACTER.inventory["Gold"])["Description"])) if key == "Stick" and (CHARACTER.inventory["Stick"])["Amount"] > 0: self.stickButton = Button( self.battleOptionsBox, text="x" + str( (CHARACTER.inventory["Stick"])["Amount"]) + " Stick", width=8, font=("helvetica", 20), pady=2, command=lambda: self.displayText( "This is a stick... what could you possibly accomplish with this?" )) self.stickButton.pack() self.stickButton.bind( "<Enter>", lambda e: self.displayText( (CHARACTER.inventory["Stick"])["Description"])) if key == "Health Potion" and ( CHARACTER.inventory["Health Potion"])["Amount"] > 0: self.potionButton = Button( self.battleOptionsBox, text="x" + str( (CHARACTER.inventory["Health Potion"])["Amount"]) + " Health \nPotions", width=8, font=("helvetica", 20), pady=4, command=lambda: CHARACTER.usePotion(self, ENEMY, master)) self.potionButton.pack() self.potionButton.bind( "<Enter>", lambda e: self.displayText( (CHARACTER.inventory["Health Potion"])["Description"])) self.backToBattleMenuButton = Button( self.battleOptionsBox, text="Back", font=("helvetica", 20), pady=2, command=lambda: self.backToBattleMenu(CHARACTER, ENEMY, master)) self.backToBattleMenuButton.pack(side=BOTTOM) def displayCharacterXPBar(self, CHARACTER): self.XPBarVar = IntVar() self.XPBarVar.set(CHARACTER.XP) self.CharacterXPBar = Progressbar(self.textArea, orient=HORIZONTAL, length=500, variable=self.XPBarVar, maximum=(CHARACTER.level * 10)) self.xpTitle = Label(self.textArea, text="%s/%s XP" % (str(CHARACTER.XP), str(CHARACTER.level * 10)), font=('Helvetica', 20), bg="Black", fg="White") self.xpTitle.pack(side=LEFT, padx=10) self.CharacterXPBar.pack(side=RIGHT, padx=10) def hideCharacterXPBar(self): self.CharacterXPBar.pack_forget() self.xpTitle.pack_forget() def hideCharacterInventory(self): self.goldButton.pack_forget() self.potionButton.pack_forget() self.stickButton.pack_forget() self.inventoryTitle.pack_forget() self.backToBattleMenuButton.pack_forget() def backToBattleMenu(self, CHARACTER, ENEMY, master): self.hideCharacterInventory() self.displayBattleMenu(CHARACTER, ENEMY, master) def attackDescription(self, event): self.displayText("Attack the enemy with your weapon.") def defendDescription(self, event): self.displayText("Ready yourself to defend against the enemy.") def useItemDescription(self, event): self.displayText("Open your inventory and use an Item.") def magicDescription(self, event): self.displayText("Open your spell list, if you have unlocked magic.") def fleeDescription(self, event): self.displayText("Attempt to flee from the battle.")
def makeModel(window): ProblemSelect = page(window, 'Problem Type') ProblemSelect.pack() problemType = StringVar(value="Text (Classification) -- Default") continueVar = BooleanVar() explanationBox = Label(ProblemSelect.contentFrame) problemTypeChoices = { 'Numbers (Regression)': 'Numerical data with continuous numerical output e.g. stock market data', 'Numbers (Classification)': 'Numerical data with fixed outputs e.g even and odd numbers', 'Text (Regression)': 'Text data with continuous numerical output e.g sentiment analysis', 'Text (Classification) -- Default': 'Text data with fixed outputs e.g spam filtering. Default option' } for choice, description in problemTypeChoices.items(): option = Radiobutton(ProblemSelect.contentFrame, text=choice, variable=problemType, value=choice, command=lambda description=description: explanationBox.config(text=description)) option.grid(column=0, sticky='w', padx=5, pady=5) map(lambda x: x.deselect(), list(ProblemSelect.contentFrame.children.values())) list(ProblemSelect.contentFrame.children.values())[-1].invoke() explanationBox.grid(column=1, row=3, sticky='e') nxtBtn = Button(ProblemSelect.contentFrame, text="next", command=lambda: continueVar.set(True)) nxtBtn.grid(column=1, columnspan=2, padx=10, ipadx=30, ipady=5) ProblemSelect.wait_variable(continueVar) ProblemSelect.pack_forget() # select which columns to use DataCollecting = page(window, 'Select Training Data') DataCollecting.pack() # load data fileNotLoaded = True counter = 0 while fileNotLoaded: if counter == 10: messagebox.showerror(title='Error', message=retryError) sys.exit() try: counter += 1 filename = askopenfilename(title='Choose Training Data', filetypes=dataFiletypes) if path.splitext(filename)[1].lower() == '.csv': trainingDataDF = read_csv(filename) else: trainingDataDF = read_excel(filename) # If you didn't clean your data, I'm just going to destroy it. Serves you right. trainingDataDF = trainingDataDF.apply( lambda x: x.interpolate(method='pad')) trainingDataDF = trainingDataDF.dropna(how='any') if len(trainingDataDF.index) < 50: raise ValueError( ': Not enough data. Have to have at least 50 samples of data.\n' 'If you think you have enough, it might be because there were' 'invalid values that were automatically taken out.') except Exception as e: messagebox.showerror(title='Error', message=str(type(e)).split('\'')[1] + str(e)) continue fileNotLoaded = False # listbox with all the column names columnListbox = ScrollingListbox(DataCollecting.contentFrame, 20) columnListbox.grid(column=0, row=0, rowspan=8, padx=10, pady=10, sticky='ns') for columName in trainingDataDF.columns: columnListbox.listbox.insert('end', columName) featureListbox = ScrollingListbox(DataCollecting.contentFrame) featureListbox.grid(column=2, row=0, rowspan=4, padx=10, pady=10) featureAddButton = Button( DataCollecting.contentFrame, text='Add >>>', command=lambda: addToListBox(columnListbox, featureListbox)) featureAddButton.grid(column=1, row=1) featureRemoveButton = Button( DataCollecting.contentFrame, text='<<< Remove', command=lambda: deleteFromListBox(featureListbox)) featureRemoveButton.grid(column=1, row=2) targetListbox = ScrollingListbox(DataCollecting.contentFrame) targetListbox.grid(column=2, row=4, rowspan=4, padx=10, pady=10) targetAddButton = Button( DataCollecting.contentFrame, text='Add >>>', command=lambda: addToListBox(columnListbox, targetListbox)) targetAddButton.grid(column=1, row=5) targetRemoveButton = Button( DataCollecting.contentFrame, text='<<< Remove', command=lambda: deleteFromListBox(targetListbox)) targetRemoveButton.grid(column=1, row=6) collectDataButton = Button( DataCollecting.contentFrame, text='Create', command=lambda: continueVar.set(True) if len(featureListbox.listbox.get(0, 'end')) > 0 and len( targetListbox.listbox.get(0, 'end') ) > 0 else messagebox.showwarning( title='Warning', message='You must have at least one feature and one target')) collectDataButton.grid(column=2, row=8, pady=20, ipadx=20) DataCollecting.wait_variable(continueVar) DataCollecting.pack_forget() creating = page(window, 'Creating') creating.pack() progress = Progressbar(creating.contentFrame) progress.pack() progress.config(mode='indeterminate') progress.start() sleep(2) featureColumnNames = featureListbox.listbox.get(0, 'end') targetColumnNames = targetListbox.listbox.get(0, 'end') featureTrain = trainingDataDF[list(featureColumnNames)] targetTrain = trainingDataDF[list(targetColumnNames)] featureEncoder = LabelEncoder() targetEncoder = LabelEncoder() if 'Text' in problemType.get(): featureEncoder.fit( array(list( set(featureTrain.to_numpy().flatten().tolist()))).reshape( -1, 1).ravel()) featureTrain = featureTrain.applymap( lambda x: featureEncoder.transform(array(x).reshape(1, 1))[0]) if 'Classification' in problemType.get(): targetEncoder.fit( array(list( set(targetTrain.to_numpy().flatten().tolist()))).reshape( -1, 1).ravel()) targetTrain = targetTrain.applymap( lambda x: targetEncoder.transform(array(x).reshape(1, 1))[0]) model = chooseAlgorithm(problemType.get(), featureTrain, targetTrain) progress.stop() progress.pack_forget() modelname = str(model.__class__).split('.')[-1][:-2] filename = modelname + ' ' + datetime.now().strftime("%Y-%m-%d-%H-%M-%S") fileNotLoaded = True counter = 0 while fileNotLoaded: if counter == 10: messagebox.showerror(title='Error', message=retryError) sys.exit() try: counter += 1 filepath = asksaveasfilename( initialfile=filename, defaultextension='.mlmc', filetypes=[('Edward Machine Learning Creater Model', '*.emlcm') ], title='Save As') dump([ model, problemType.get(), featureEncoder, targetEncoder, featureTrain.columns, targetTrain.columns ], filepath, 5) except Exception as e: messagebox.showerror(title='Error', message=str(type(e)).split('\'')[1] + str(e)) continue fileNotLoaded = False backButton = Button( creating.contentFrame, text='Back to Home Page', font=('Helvetica', 30), command=lambda: [continueVar.set(True), creating.destroy(), HomePage(window)]) backButton.pack(pady=20) quitButton = Button( creating.contentFrame, text='Quit', font=('Helvetica', 30), command=lambda: [continueVar.set(True), window.destroy()]) quitButton.pack(pady=20) creating.wait_variable(continueVar)
class CalibrationDialog(BeeDialog): _main_window = None #: tk.Tk _hive = None #: Hive _bar = None #: Progressbar _close_enabled = True _button_box = None #: Frame _start_button = None _calibration = None _humidity = None _yes_button = None _no_button = None _header = None _expected_weight_label = None #: : tk.Label _expected_weight_field = None #: : tk.Entry _expected_weight_box = None _weight_display = None _temp_display = None def __init__(self, main_window: tk.Tk, hive: Hive): self._main_window = main_window self._hive = hive super().__init__(parent=main_window, title="Waage kalibrieren", width=310, height=120) def _init_expected_weight_box(self): self._expected_weight_box = Frame(self) self._expected_weight_label = Label(self._expected_weight_box, text='Gewicht (g)', font=('Arial', 10), anchor='e', wraplength=100, background='#ffffcc') self._expected_weight_label.grid(column=0, row=0, sticky='e') self._expected_weight_field = Entry(self._expected_weight_box, font=('Arial', 8), width="20") self._expected_weight_field.grid(column=1, row=0) def open(self): pass def cancel(self, event=None): if self._close_enabled: super().cancel(event) def body(self, master): self._calibration = HiveCalibration() self._header = Label(master, text="") self._bar = Progressbar(master, length=210) self._init_expected_weight_box() self._weight_display = Label(master, text="") self._temp_display = Label(master, text="") self._prepare_tara() def _prepare_tara(self): self._header.config( text='Drücken Sie "Start" um die Waage\n zu tarieren.') self._header.pack() def _standard_buttons(self): self._button_box = Frame(self) self._button_box.pack() self._start_button = Button(self._button_box, text="Start", width=10, command=self._calc_offset, default=ACTIVE) self._start_button.pack(side=LEFT, padx=5, pady=5) w = Button(self._button_box, text="Abbrechen", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) def _yes_no_buttons(self): self._yes_no_button_box = Frame(self) self._yes_button = Button(self._yes_no_button_box, text="Ja", width=10, command=self._satisfied, default=ACTIVE) self._yes_button.pack(side=LEFT, padx=5, pady=5) self._no_button = Button(self._yes_no_button_box, text="Nein", width=10, command=self._not_satisfied) self._no_button.pack(side=LEFT, padx=5, pady=5) def init_calc_offset(self): pass def _satisfied(self): DbAccess.update_hive_calibration(self._calibration) self._close_enabled = True self.cancel() def _not_satisfied(self): self._start_button.config(command=self._calc_offset) self._calibration = HiveCalibration() self._yes_no_button_box.pack_forget() self._temp_display.pack_forget() self._weight_display.pack_forget() self._prepare_tara() self._button_box.pack() self.update_idletasks() def buttonbox(self): self._standard_buttons() self._yes_no_buttons() '''add standard button box. override if you do not want the standard buttons ''' ''' w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) w = Button(box, text="Cancel", width=10, command=self.cancel) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) ''' def _progress(self, i, maximum=15): self._bar['value'] = int(210 / (maximum - i)) self.update_idletasks() def _calc_reference_unit(self, event=None): expected_weight_string = self._expected_weight_field.get() print('calc-reference-unit.expected_weight_string: ', expected_weight_string) expected = int(expected_weight_string) print('calc-reference-unit.expected: ', expected) self._calibration.entity_id = self._hive.get_id() self._humidity = None self._bar['value'] = 0 self._bar.pack() self.update_idletasks() try: self._close_enabled = False self._button_box.pack_forget() self._close_enabled = False self._bar.pack() self.update_idletasks() pins = self._hive.get_weight().get_bcm().split(",") data_pin = pins[0] clk_pin = pins[1] print('data_pin ' + data_pin) print('clk_pin ' + clk_pin) hx = HX711(int(data_pin), int(clk_pin), gain=128) hx.set_reading_format("LSB", "MSB") print('_offset:', self._calibration.offset) hx.set_offset(self._calibration.offset) self._calibration.value_per_gram = hx.calc_reference_unit( lambda i: self._progress(i, 10), expected) print('reference_unit -> ', self._calibration.value_per_gram) self._calc_temp() clean() self._start_button.config(command=self._check_weight) self._header.config( text='Drücken Sie Start um das Gewicht\nzu überprüfen.') self._button_box.pack() self._bar.pack_forget() self._expected_weight_box.pack_forget() self._weight_display.pack() self._temp_display.pack() self.update_idletasks() self._close_enabled = True except Exception as e: print('Error ', e) clean() self._calibration.offset = None self._close_enabled = True def _calc_temp(self): temp_sensor = self._hive.get_temperature_outside() if temp_sensor.get_bcm() == '' or temp_sensor.get_product() == '': return if temp_sensor.get_product() == 'DHT22': self._humidity, self._calibration.temp = dht.read_retry( dht.DHT22, int(temp_sensor.get_bcm())) print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format( self._calibration.temp, self._humidity)) elif temp_sensor.get_product() == 'DHT11': self._humidity, self._temp = dht.read_retry( dht.DHT11, int(temp_sensor.get_bcm())) print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format( self._calibration.temp, self._humidity)) else: print('Unsupported product ', temp_sensor.get_product()) def _check_weight(self): try: self._close_enabled = False pins = self._hive.get_weight().get_bcm().split(",") data_pin = pins[0] clk_pin = pins[1] hx = HX711(int(data_pin), int(clk_pin), gain=128) hx.set_reading_format("LSB", "MSB") print('_reference_unit:', self._calibration.value_per_gram) hx.set_reference_unit(self._calibration.value_per_gram) hx.reset() print('_offset:', self._calibration.offset) hx.set_offset(self._calibration.offset) val = hx.get_weight(5) print('value -> ', val) self._header.config(text='Sind Sie mit dem Ergebnis\nzufrieden?') self._weight_display.config( text=('Gewicht: {0:0.1f}g'.format(val))) if self._calibration.temp is not None: self._temp_display.config( text=('Temp: {0:0.1f}°C'.format(self._calibration.temp))) else: self._temp_display.config(text='') print('reference_unit -> ', self._calibration.value_per_gram) clean() self._button_box.pack_forget() self._yes_no_button_box.pack() self.update_idletasks() self._close_enabled = True except Exception as e: print('Error ', e) clean() self._calibration.offset = None self._close_enabled = True def _calc_offset(self, event=None): self._calibration.offset = None try: self._button_box.pack_forget() self._close_enabled = False self._bar.pack() self.update_idletasks() pins = self._hive.get_weight().get_bcm().split(",") data_pin = pins[0] clk_pin = pins[1] print('data_pin ' + data_pin) print('clk_pin ' + clk_pin) hx = HX711(int(data_pin), int(clk_pin), gain=128) hx.set_reading_format("LSB", "MSB") self._calibration.offset = hx.calc_offset( lambda i: self._progress(i)) print('offset -> ', self._calibration.offset) clean() self._start_button.config(command=self._calc_reference_unit) self._header.config(text='Geben Sie ein Gewicht auf die Waage.') self._expected_weight_box.pack() self._button_box.pack() self._bar.pack_forget() self.update_idletasks() except Exception as e: print('Fehler', e) clean() self._close_enabled = True self._calibration.offset = None