class KRCCModule: __metaclass__ = ABCMeta def __init__(self): self._terminate = BooleanVar(False) self._id = StringVar(False) @property def terminate(self): return self._terminate.get() @terminate.setter def terminate(self, value): self._terminate.set(value) @property def id(self): return self._id.get() @id.setter def id(self, value): self._id.set(value) @abstractproperty def name(self): pass @abstractmethod def run(self): pass
def __init__(self, client): # Basic setup super(Preferences, self).__init__() self.client = client # Setup the variables used self.echo_input = BooleanVar() self.echo_input.set(self.client.config['UI'].getboolean('echo_input')) self.echo_input.trace("w", self.echo_handler) self.logging = BooleanVar() self.logging.set(self.client.config['logging'].getboolean('log_session')) self.logging.trace('w', self.logging_handler) self.log_dir = self.client.config['logging']['log_directory'] # Build the actual window and widgets prefs = Toplevel(self) prefs.wm_title("Preferences") echo_input_label = Label(prefs, text="Echo Input:") logging_label = Label(prefs, text='Log to file:') echo_checkbox = Checkbutton(prefs, variable=self.echo_input) logging_checkbox = Checkbutton(prefs, variable=self.logging) logging_button_text = 'Choose file...' if self.log_dir == "" else self.log_dir logging_button = Button(prefs, text=logging_button_text, command=self.logging_pick_location) # Pack 'em in. echo_input_label.grid(row=0, column=0) echo_checkbox.grid(row=0, column=1) logging_label.grid(row=1, column=0) logging_checkbox.grid(row=1, column=1) logging_button.grid(row=1, column=2)
def test_invalid_value_domain(self): v = BooleanVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(ValueError): v.get()
def __init__(self, modelXbrl, tabWin, lang): super(ViewRenderedGrid, self).__init__(modelXbrl, tabWin, "Rendering", True, lang) self.newFactItemOptions = ModelInstanceObject.NewFactItemOptions(xbrlInstance=modelXbrl) self.factPrototypes = [] self.zOrdinateChoices = None # context menu Boolean vars self.ignoreDimValidity = BooleanVar(value=True) self.xAxisChildrenFirst = BooleanVar(value=True) self.yAxisChildrenFirst = BooleanVar(value=False)
def __init__(self, modelXbrl, tabWin, lang): super(ViewRenderedGrid, self).__init__(modelXbrl, tabWin, "Rendering", True, lang) self.newFactItemOptions = ModelInstanceObject.NewFactItemOptions(xbrlInstance=modelXbrl) self.factPrototypes = [] self.zOrdinateChoices = None # context menu Boolean vars self.options = self.modelXbrl.modelManager.cntlr.config.setdefault("viewRenderedGridOptions", {}) self.ignoreDimValidity = BooleanVar(value=self.options.setdefault("ignoreDimValidity",True)) self.xAxisChildrenFirst = BooleanVar(value=self.options.setdefault("xAxisChildrenFirst",True)) self.yAxisChildrenFirst = BooleanVar(value=self.options.setdefault("yAxisChildrenFirst",False))
def validateTableInfosetMenuEntender(cntlr, validateMenu): # Extend menu with an item for the save infoset plugin cntlr.modelManager.generateTableInfoset = cntlr.config.setdefault("generateTableInfoset",False) from tkinter import BooleanVar generateTableInfoset = BooleanVar(value=cntlr.modelManager.generateTableInfoset) def setTableInfosetOption(*args): cntlr.config["generateTableInfoset"] = cntlr.modelManager.generateTableInfoset = generateTableInfoset.get() generateTableInfoset.trace("w", setTableInfosetOption) validateMenu.add_checkbutton(label=_("Generate table infosets (instead of diffing them)"), underline=0, variable=generateTableInfoset, onvalue=True, offvalue=False)
def __init__(self, root): '''Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. ''' self.root = root # need for report_error() self.patvar = StringVar(root, '') # search pattern self.revar = BooleanVar(root, False) # regular expression? self.casevar = BooleanVar(root, False) # match case? self.wordvar = BooleanVar(root, False) # match whole word? self.wrapvar = BooleanVar(root, True) # wrap around buffer? self.backvar = BooleanVar(root, False) # search backwards?
def __init__(self, modelXbrl, tabWin, lang): super(ViewRenderedGrid, self).__init__(modelXbrl, tabWin, "Table", True, lang) self.newFactItemOptions = ModelInstanceObject.NewFactItemOptions(xbrlInstance=modelXbrl) self.factPrototypes = [] self.aspectEntryObjectIdsNode = {} self.aspectEntryObjectIdsCell = {} self.factPrototypeAspectEntryObjectIds = defaultdict(set) self.zOrdinateChoices = None # context menu Boolean vars self.options = self.modelXbrl.modelManager.cntlr.config.setdefault("viewRenderedGridOptions", {}) self.openBreakdownLines = self.options.setdefault("openBreakdownLines", 5) # ensure there is a default entry self.ignoreDimValidity = BooleanVar(value=self.options.setdefault("ignoreDimValidity",True)) self.xAxisChildrenFirst = BooleanVar(value=self.options.setdefault("xAxisChildrenFirst",True)) self.yAxisChildrenFirst = BooleanVar(value=self.options.setdefault("yAxisChildrenFirst",False))
class Preferences(Frame): def __init__(self, client): # Basic setup super(Preferences, self).__init__() self.client = client # Setup the variables used self.echo_input = BooleanVar() self.echo_input.set(self.client.config['UI'].getboolean('echo_input')) self.echo_input.trace("w", self.echo_handler) self.logging = BooleanVar() self.logging.set(self.client.config['logging'].getboolean('log_session')) self.logging.trace('w', self.logging_handler) self.log_dir = self.client.config['logging']['log_directory'] # Build the actual window and widgets prefs = Toplevel(self) prefs.wm_title("Preferences") echo_input_label = Label(prefs, text="Echo Input:") logging_label = Label(prefs, text='Log to file:') echo_checkbox = Checkbutton(prefs, variable=self.echo_input) logging_checkbox = Checkbutton(prefs, variable=self.logging) logging_button_text = 'Choose file...' if self.log_dir == "" else self.log_dir logging_button = Button(prefs, text=logging_button_text, command=self.logging_pick_location) # Pack 'em in. echo_input_label.grid(row=0, column=0) echo_checkbox.grid(row=0, column=1) logging_label.grid(row=1, column=0) logging_checkbox.grid(row=1, column=1) logging_button.grid(row=1, column=2) def logging_pick_location(self): location = askdirectory(initialdir="%UserProfile%\Documents\\") self.client.config['logging']['log_directory'] = location self.write_config() def echo_handler(self, arg1, arg2, mode): pprint(self.echo_input.get()) self.client.config['UI']['echo_input'] = 'yes' if self.echo_input.get() else 'no' self.write_config() def logging_handler(self, arg1, arg2, mode): self.client.config['logging']['log_session'] = 'yes' if self.logging.get else 'no' self.write_config() def write_config(self, file='config.ini'): self.client.config.write(open(file, 'w'))
def __init__(self, title="", message="", button="Ok", image=None, checkmessage="", style="clam", **options): """ Create a messagebox with one button and a checkbox below the button: parent: parent of the toplevel window title: message box title message: message box text button: message displayed on the button image: image displayed at the left of the message checkmessage: message displayed next to the checkbox **options: other options to pass to the Toplevel.__init__ method """ Tk.__init__(self, **options) self.resizable(False, False) self.title(title) s = Style(self) s.theme_use(style) if image: Label(self, text=message, wraplength=335, font="Sans 11", compound="left", image=image).grid(row=0, padx=10, pady=(10, 0)) else: Label(self, text=message, wraplength=335, font="Sans 11").grid(row=0, padx=10, pady=(10, 0)) b = Button(self, text=button, command=self.destroy) b.grid(row=2, padx=10, pady=10) self.var = BooleanVar(self) c = Checkbutton(self, text=checkmessage, variable=self.var) c.grid(row=1, padx=10, pady=0, sticky="e") self.grab_set() b.focus_set() self.wait_window(self)
def init_widgets(self): # file selector self.btn_file_select = Button(self, text="Select file", command=self.on_select) self.btn_file_select.grid(column=0, row=0, columnspan=2) # filename self.filename, self.e_filename, self.l_filename = make_entry(self, "File name: ", 1) # delimiter self.delimiter, self.e_delimiter, self.l_delimiter = make_entry(self, "Delimiter: ", 2) # has_header self.l_has_header = ttk.Label(self, text="Has header: ") self.l_has_header.grid(column=0, row=3, sticky=W) self.has_header = BooleanVar() self.e_has_header = ttk.Checkbutton(self, variable=self.has_header) self.e_has_header.grid(column=1, row=3, sticky=W) # sheet_name self.sheet_name, self.e_sheet_name, self.l_sheet_name = make_entry(self, "Sheet name: ", 4) # x_offset self.x_offset, self.e_x_offset, self.l_x_offset = make_entry(self, "X offset: ", 5) # y_offset self.y_offset, self.e_y_offset, self.l_y_offset = make_entry(self, "Y offset: ", 6)
def build_widgets(self): "Build the various widgets that will be used in the program." # Create processing frame widgets. self.processing_frame = LabelFrame(self, text='Processing Mode:') self.mode_var = StringVar(self, 'encode') self.decode_button = Radiobutton(self.processing_frame, text='Decode Cipher-Text', command=self.handle_radiobuttons, value='decode', variable=self.mode_var) self.encode_button = Radiobutton(self.processing_frame, text='Encode Plain-Text', command=self.handle_radiobuttons, value='encode', variable=self.mode_var) self.freeze_var = BooleanVar(self, False) self.freeze_button = Checkbutton(self.processing_frame, text='Freeze Key & Primer', command=self.handle_checkbutton, offvalue=False, onvalue=True, variable=self.freeze_var) # Create encoding frame widgets. self.encoding_frame = LabelFrame(self, text='Encoding Options:') self.chain_size_label = Label(self.encoding_frame, text='Chain Size:') self.chain_size_entry = Entry(self.encoding_frame) self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:') self.plain_text_entry = Entry(self.encoding_frame) # Create input frame widgets. self.input_frame = LabelFrame(self, text='Input Area:') self.input_text = ScrolledText(self.input_frame, **self.TEXT) # Create output frame widgets. self.output_frame = LabelFrame(self, text='Output Area:') self.output_text = ScrolledText(self.output_frame, **self.TEXT)
def init_widgets(self): # file selector self.btn_file_select=Button(self, text="Select file",command=self.on_select) self.btn_file_select.grid(column=0, row=0, columnspan=2) # filename self.filename, self.e_filename, self.l_filename = make_entry(self,"File name: ", 1) # delimiter self.delimiter, self.e_delimiter, self.l_delimiter = make_entry(self,"Delimiter: ", 2) # has_header self.l_has_header = ttk.Label(self, text="Has header: ") self.l_has_header.grid(column=0, row=3, sticky=W) self.has_header = BooleanVar() self.e_has_header = ttk.Checkbutton(self, variable=self.has_header) self.e_has_header.grid(column=1, row=3, sticky=W) # csv_dialect self.csv_dialect, self.e_csv_dialect, self.l_csv_dialect = make_entry(self,"CSV dialect: ", 4) # quoting self.quoting, self.e_quoting, self.l_quoting = make_entry(self, "Quoting: ", 5) # escapechar self.escapechar, self.e_escapechar, self.l_escapechar = make_entry(self, "Escape character: ", 6) # lineterminator self.lineterminator, self.e_lineterminator, self.l_lineterminator = make_entry(self, "Line terminator: ", 7) # quotechar self.quotechar, self.e_quotechar, self.l_quotechar = make_entry(self, "Quote character: ", 8) # skipinitialspace self.skipinitialspace, self.e_skipinitialspace, self.l_skipinitialspace = make_entry(self, "Skip initial space: ", 9)
def __init__(self, _master, _mapping = None, _on_get_source_references = None, _on_get_destination_references = None, _on_select = None): super(FrameMapping, self).__init__(_master) # Add monitored variables. self.is_key = BooleanVar() self.src_reference = StringVar() self.src_datatype = StringVar() self.curr_data = StringVar() self.result_cast_to = StringVar() self.preview = StringVar() self.dest_reference = StringVar() self.on_get_source_references = _on_get_source_references self.on_get_destination_references = _on_get_destination_references self.on_select = _on_select self.init_widgets() self.mapping = _mapping if _mapping is not None: self.mapping_to_gui()
def initData(self): self.browseInitialDir = def_initialDir self.recentFile = def_recentFile self.menuOutputAudio = StringVar() self.menuOutputAudio.set(def_menuOutputAudio) self.menuVideoRefresh = BooleanVar() self.menuVideoRefresh.set(def_menuVideoRefresh) self.menuBgBlack = BooleanVar() self.menuBgBlack.set(def_menuBgBlack) self.maxRecentVideos = def_maxRecentVideos self.moreOptions = def_moreOptions self.playProcess = None
def addValidateMenuTools(cntlr, validateMenu, name, map_name): # Extend menu with an item for the save infoset plugin attr_name = 'validate{}'.format(name.strip()) attr_value = cntlr.config.setdefault(attr_name, False) setattr(cntlr.modelManager, attr_name, attr_value) #cntlr.modelManager.validateDQC = cntlr.config.setdefault("validateDQC",False) from tkinter import BooleanVar validate_var = BooleanVar(value=getattr(cntlr.modelManager, attr_name)) def setValidateXuleOption(*args): setattr(cntlr.modelManager, attr_name, validate_var.get()) cntlr.config[attr_name] = getattr(cntlr.modelManager, attr_name) validate_var.trace("w", setValidateXuleOption) validateMenu.add_checkbutton(label=_("{} Rules".format(name)), underline=0, variable=validate_var, onvalue=True, offvalue=False) xuleRegisterValidators(name, map_name, validate_var)
def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) # Set window title self.wm_title('Plastey Configurator') # Create GUI driven variables self._mode = BooleanVar() self._base = BooleanVar() self._comm = BooleanVar() self._pass = StringVar() self._addressed = StringVar() self._connected = StringVar() self._this_host = StringVar() self._this_port = StringVar() self._other_host = StringVar() self._other_port = StringVar() # Create GUI self._build_gui() # Set default values for GUI driven variables self._mode.set(MODE_SINGLE_PLAYER) self._base.set(BASE_OPENED_GEOMETRY) self._comm.set(COMM_SOCKET_SERVER) self._pass.set('') self._addressed.set(ADDR_HAVE_ADDRESS if check(COMM_THIS_HOST) else ADDR_NO_ADDRESS) self._connected.set(CONN_NOT_CONNECTED) self._this_host.set(COMM_THIS_HOST) self._this_port.set(COMM_THIS_PORT) self._other_host.set(COMM_THIS_HOST) self._other_port.set(COMM_OTHER_PORT) # Follow changes on password self._pass.trace('w', self._on_bind_address) # Create folder structures if they don't exists yet makedirs(FILE_TEMPORARY_FOLDER, exist_ok=True) makedirs(FILE_PERMANENT_FOLDER, exist_ok=True) makedirs(FILE_TEMP_SAVE_FOLDER, exist_ok=True) makedirs(FILE_AUTO_SAVE_FOLDER, exist_ok=True)
def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.pack(fill=BOTH, expand=True) self.parent.title("youtube-dl GUI") # Initialise variables self._extract_audio = BooleanVar() self._video_url = StringVar() self._output_path = StringVar() # Initialise self._logger = LogWindow(self) self._init_ui()
def __init__(self, pype, toplevel=False, filename=False, num_sequences=10, run_tag=''): ''' ''' self.pype = pype self.toplevel = toplevel self.keep_runningVar = BooleanVar(value=True) self.extend_runVar = BooleanVar(value=False) self.run_typeVar = StringVar(value="/tmp/") self.run_tagVar = StringVar(value=run_tag) self.num_sequencesVar = IntVar(value=num_sequences) self.sequence_spacingVar = DoubleVar(value=0) self.len_sequenceVar = DoubleVar() self.stateVar = StringVar(value='done') self.conf_filename = StringVar(value='') self.params = {} self.runthread = multiprocessing.Process() self._GetParamFuncs() if toplevel: self._BuildGui()
def test_invalid_value_domain(self): false = 0 if self.root.wantobjects() else "0" v = BooleanVar(self.root, name="name") with self.assertRaises(TclError): v.set("value") self.assertEqual(self.root.globalgetvar("name"), false) self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() self.root.globalsetvar("name", "1.0") with self.assertRaises(ValueError): v.get()
def __init__(self, root, engine, flist): """Create search dialog for searching for a phrase in the file system. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: globvar: Value of Text Entry widget for path to search. recvar: Boolean value of Checkbutton widget for traversing through subdirectories. """ SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root)
def __createWidgets(self): """ @ brief create the widgets """ Label(self, text="input dictionary tree: ").grid(row=0, column=0, sticky=W) self.dict_with_label = BooleanVar() Checkbutton(self, text="label edge", variable=self.dict_with_label).grid(row=0, column=0, sticky=E) self.source_text = Text(self, width=40, wrap=WORD) self.source_text.grid(row=1, column=0, sticky=W) Button(self, text="visual tree", command=self.__submitSource).grid(row=2, column=0, sticky=W) Button(self, text="clear", command=self.__clearText).grid(row=2, column=0, sticky=E)
def test_get(self): v = BooleanVar(self.root, True, "name") self.assertIs(v.get(), True) self.root.globalsetvar("name", "0") self.assertIs(v.get(), False) self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1) self.assertIs(v.get(), True) self.root.globalsetvar("name", 0) self.assertIs(v.get(), False) self.root.globalsetvar("name", "on") self.assertIs(v.get(), True)
class Application(Frame): "application frame" def __init__(self, master): """ @ brief initialize the frame with master @ params self -- new instance master -- root container """ super(Application, self).__init__(master) self.grid() self.__createWidgets() def __createWidgets(self): """ @ brief create the widgets """ Label(self, text="input dictionary tree: ").grid(row=0, column=0, sticky=W) self.dict_with_label = BooleanVar() Checkbutton(self, text="label edge", variable=self.dict_with_label).grid(row=0, column=0, sticky=E) self.source_text = Text(self, width=40, wrap=WORD) self.source_text.grid(row=1, column=0, sticky=W) Button(self, text="visual tree", command=self.__submitSource).grid(row=2, column=0, sticky=W) Button(self, text="clear", command=self.__clearText).grid(row=2, column=0, sticky=E) def __submitSource(self): "listener for visual button" source = self.source_text.get("1.0", END) if "" != source: current_view = Draw(self) current_view.initDot() current_view.setSource(source, self.dict_with_label.get()) current_view.show() def __clearText(self): "clear button callback" self.source_text.delete(0.0, END)
def __init__(self, pype, toplevel=False, **runargs): ''' ''' self.pype = pype self.runargs = runargs self.toplevel = toplevel self.sweep_result = {} self.powerVar = DoubleVar(value=20) #dBm self.set_power_BoolVar = BooleanVar(value=True) self.start_freq_Var = DoubleVar(value=26350) #MHz self.stop_freq_Var = DoubleVar(value=26600) #MHz self.start_search_freq_Var = DoubleVar(value=26450) #MHz self.stop_search_freq_Var = DoubleVar(value=26510) #MHz self.sweep_time_Var = DoubleVar(value=15) #s self.num_points_Var = IntVar(value=400) #ms self.spanVar = DoubleVar(value=100) self.stepVar = DoubleVar(value=4) #self.fit_channel_Var = StringVar(value='xdata') self.result_str_Var = StringVar(value='') self._BuildGui()
def test_default(self): v = BooleanVar(self.root) self.assertIs(v.get(), False)
def build_parsing_book_groups(self): """ Функция отвечающая за наполнение подвкладки "Парсинг по группам" вкладки "Парсинг" :return: """ left_frame = ttk.Frame(self.parsing_book_groups, relief='solid', borderwidth=1, padding=1) right_frame = ttk.Frame(self.parsing_book_groups, padding=5) left_frame.grid(row=0, column=0, sticky='NSWE', padx=3, pady=3) right_frame.grid(row=0, column=1, sticky='NSWE', padx=3, pady=3) lbl_progress = ttk.Label(self.parsing_book_groups, font=fonts.H6_FONT) progressbar = ttk.Progressbar(self.parsing_book_groups, orient='vertical', mode='determinate', maximum=PROGRESSBAR_MAX, value=0) lbl_progress.grid(row=1, column=0, columnspan=2, pady=5, sticky='SWE') progressbar.grid(row=2, column=0, columnspan=2, pady=5, sticky='SWE') #####################---------LEFT_FRAME---------##################### var_easy_parse = BooleanVar() var_easy_parse.set(0) # row 0 lbl_count = ttk.Label(left_frame, font=fonts.H1_FONT, text='Количество: 0') # row 1 check_easy_parse = ttk.Checkbutton( left_frame, variable=var_easy_parse, text='Отключить сбор доп. данных(Дальнейший парсинг по выборке ' 'недоступен)', onvalue=1, offvalue=0) # row 2 txt_groups = Text(left_frame, wrap='word', font=fonts.TEXT_FONT, foreground=styles.FOREGROUND_TEXT, background=styles.BACKGROUND_TEXT) # row 3 lbl_warning = ttk.Label( left_frame, foreground='#e10000', font=fonts.H6_FONT, text='Вводите исключительно ссылки на группы. И вводите через ' '"Enter"\nСкопировать Ctrl + C. Вставить Ctrl + V. Не иначе!') #####################---------RIGHT_FRAME---------##################### btn_parse = ttk.Button(right_frame, text='Парсить') btn_up_count = ttk.Button(right_frame, text='Обновить кол-во', cursor='exchange') btn_paste = ttk.Button(right_frame, text='Вставить из буфера') btn_show_all = ttk.Button(right_frame, text='Все записи') widgets = { 'right_frame': right_frame, 'left_frame': left_frame, 'lbl_count': lbl_count, 'var_easy_parse': var_easy_parse, 'txt_groups': txt_groups, 'lbl_progress': lbl_progress, 'btn_paste': btn_paste, 'progressbar': progressbar } ####################-------------GRID-------------#################### # left_frame # row 0 lbl_count.grid(row=0, column=0, sticky='NSWE') # row 1 check_easy_parse.grid(row=1, column=0, sticky='SWE', pady=7) # row 2 txt_groups.grid(row=2, column=0, sticky='NSWE') # row 3 lbl_warning.grid(row=3, column=0, sticky='SWE') # right_frame # row 0 btn_parse.grid(row=0, column=0, sticky='NWE', pady=5) # row 1 btn_up_count.grid(row=1, column=0, sticky='NWE') # row 2 btn_paste.grid(row=2, column=0, sticky='NWE', pady=5) # row 3 btn_show_all.grid(row=3, column=0, sticky='NWE') left_frame.rowconfigure(2, weight=1) left_frame.columnconfigure(0, weight=1) right_frame.columnconfigure(0, weight=1) self.parsing_book_groups.rowconfigure(0, weight=1) self.parsing_book_groups.columnconfigure(0, weight=9) self.parsing_book_groups.columnconfigure(1, weight=1) btn_show_all.bind('<Button-1>', lambda event: TreeViewWindow(method='view')) btn_up_count.bind( '<Button-1>', lambda event: FunctionsForWindows. update_label_count_group(widgets)) btn_paste.bind( '<Button-1>', lambda event: paste_into_widget(widget=txt_groups, text=True)) btn_parse.bind( '<Button-1>', lambda event: FunctionsForWindows().parsing_groups(widgets))
def test_get(self): v = BooleanVar(self.root, True, "name") self.assertAlmostEqual(True, v.get()) self.root.globalsetvar("name", "0") self.assertAlmostEqual(False, v.get())
class SensorControl(Tk): def __init__(self, screenName=None, baseName=None, useTk=1, sync=0, use=None): super().__init__(screenName=screenName, baseName=baseName, useTk=useTk, sync=sync, use=use) ####################################################################### # Attributes ---------------------------------------------------------- self.age = ['User', 'User'] self.sex = ['User', 'User'] self.height = ['User', 'User'] self.weight = ['User', 'User'] self.is_streaming = False self.is_displaying = False self.frame_count = 0 self.time_stamp_tmp = 0 self.depth_frame_tmp = 0 self.rgb_frame_tmp = 0 self.activity = StringVar() self.activity1 = StringVar() self.sensor_ignore = BooleanVar() self.buffer_ignore = BooleanVar() self.debug_mode = BooleanVar() # Clients self.kinect_client = PahoMqtt(BROKER, "KINECT", c_msg="kinect") self.kinect_client.loop_start() self.sound_client = PahoMqtt(BROKER, "SOUND", c_msg="sound") self.sound_client.loop_start() self.clients = list() dis = 0 for i, item in enumerate(SENSORS): if item[2]: self.clients.append( PahoMqtt(BROKER, f"{item[1]}", c_msg=item[0])) self.clients[i - dis].subscribe(item[0]) self.clients[i - dis].loop_start() else: dis += 1 # Attributes ---------------------------------------------------------- ####################################################################### # Tk widgets ---------------------------------------------------------- self.title("Control") self.resizable(0, 0) self.configure(bg='white') # Sensor Frame 1 self.sensor_frame1 = LabelFrame(self, text="Sensor control", background='white') self.sensor_frame1.pack(side=LEFT, fill="y") self.sensor_state = list() for item in self.clients: self.sensor_state.append( Label(self.sensor_frame1, text=f"SENSOR {item.info}", background='white', font=("default", 15, 'bold'))) self.sensor_state[-1].grid(row=len(self.sensor_state), column=0) self.start_btn = ttk.Button(self.sensor_frame1, text="Refresh", command=self.refresh) self.start_btn.grid(row=len(self.clients) + 1, column=0) # Stream Frame 2 self.sensor_frame2 = LabelFrame(self, text="Person 1", background='white') self.sensor_frame2.pack(side=LEFT, fill="y") self.user_age = Label(self.sensor_frame2, text="Age", background='white', font=("default", 10, 'bold')) self.user_age.grid(row=0, column=0) self.age_label = Label(self.sensor_frame2, text=self.age[0], background='white', font=("default", 10, 'bold')) self.age_label.grid(row=0, column=1) self.user_sex = Label(self.sensor_frame2, text="Sex", background='white', font=("default", 10, 'bold')) self.user_sex.grid(row=1, column=0) self.sex_label = Label(self.sensor_frame2, text=self.sex[0], background='white', font=("default", 10, 'bold')) self.sex_label.grid(row=1, column=1) self.user_height = Label(self.sensor_frame2, text="Height", background='white', font=("default", 10, 'bold')) self.user_height.grid(row=2, column=0) self.height_label = Label(self.sensor_frame2, text=self.height[0], background='white', font=("default", 10, 'bold')) self.height_label.grid(row=2, column=1) self.user_weight = Label(self.sensor_frame2, text="Weight", background='white', font=("default", 10, 'bold')) self.user_weight.grid(row=3, column=0) self.weight_label = Label(self.sensor_frame2, text=self.weight[0], background='white', font=("default", 10, 'bold')) self.weight_label.grid(row=3, column=1) self.activity_menu = ttk.Combobox(self.sensor_frame2, value=ACTIVITIES, textvariable=self.activity) self.activity_menu.current(0) self.activity_menu.config(state="readonly", width=15) self.activity_menu.bind("<<ComboboxSelected>>") self.activity_menu.grid(row=4, column=0, columnspan=2, pady=5) self.stream_start_btn = ttk.Button(self.sensor_frame2, text="Stream start", command=self.stream_start, width=11) self.stream_start_btn.grid(row=5, column=0, padx=2, pady=2) self.stream_stop_btn = ttk.Button(self.sensor_frame2, text="Stream stop", command=self.stream_stop, width=11) self.stream_stop_btn["state"] = DISABLED self.stream_stop_btn.grid(row=5, column=1, padx=2, pady=2) self.stream_reset_btn = ttk.Button( self.sensor_frame2, text="Stream reset", command=lambda: self.stream_reset(delete=True), width=11) self.stream_reset_btn["state"] = DISABLED self.stream_reset_btn.grid(row=7, column=1, padx=2, pady=2) self.stream_save_btn = ttk.Button(self.sensor_frame2, text="Stream save", command=self.stream_save, width=11) self.stream_save_btn["state"] = DISABLED self.stream_save_btn.grid(row=7, column=0, padx=2, pady=2) self.act_start_btn = ttk.Button(self.sensor_frame2, text="Activity start", command=lambda: self.activity_start(0), width=11) self.act_start_btn["state"] = DISABLED self.act_start_btn.grid(row=6, column=0, padx=2, pady=5) self.act_end_btn = ttk.Button(self.sensor_frame2, text="Activity end", command=lambda: self.activity_end(0), width=11) self.act_end_btn["state"] = DISABLED self.act_end_btn.grid(row=6, column=1, padx=2, pady=5) ################################################################################### # Stream Frame 3 self.sensor_frame3 = LabelFrame(self, text="Person 2", background='white') self.sensor_frame3.pack(side=LEFT, fill="y") self.user1_age = Label(self.sensor_frame3, text="Age", background='white', font=("default", 10, 'bold')) self.user1_age.grid(row=0, column=0) self.age1_label = Label(self.sensor_frame3, text=self.age[1], background='white', font=("default", 10, 'bold')) self.age1_label.grid(row=0, column=1) self.user1_sex = Label(self.sensor_frame3, text="Sex", background='white', font=("default", 10, 'bold')) self.user1_sex.grid(row=1, column=0) self.sex1_label = Label(self.sensor_frame3, text=self.sex[1], background='white', font=("default", 10, 'bold')) self.sex1_label.grid(row=1, column=1) self.user1_height = Label(self.sensor_frame3, text="Height", background='white', font=("default", 10, 'bold')) self.user1_height.grid(row=2, column=0) self.height1_label = Label(self.sensor_frame3, text=self.height[1], background='white', font=("default", 10, 'bold')) self.height1_label.grid(row=2, column=1) self.user1_weight = Label(self.sensor_frame3, text="Weight", background='white', font=("default", 10, 'bold')) self.user1_weight.grid(row=3, column=0) self.weight1_label = Label(self.sensor_frame3, text=self.weight[1], background='white', font=("default", 10, 'bold')) self.weight1_label.grid(row=3, column=1) self.activity1_menu = ttk.Combobox(self.sensor_frame3, value=ACTIVITIES1, textvariable=self.activity1) self.activity1_menu.current(0) self.activity1_menu.config(state="readonly", width=15) self.activity1_menu.bind("<<ComboboxSelected>>") self.activity1_menu.grid(row=4, column=0, columnspan=2, pady=5) self.act_start_btn1 = ttk.Button( self.sensor_frame3, text="Activity start", command=lambda: self.activity_start(1), width=11) self.act_start_btn1["state"] = DISABLED self.act_start_btn1.grid(row=5, column=0, padx=2, pady=5) self.act_end_btn1 = ttk.Button(self.sensor_frame3, text="Activity end", command=lambda: self.activity_end(1), width=11) self.act_end_btn1["state"] = DISABLED self.act_end_btn1.grid(row=5, column=1, padx=2, pady=5) ################################################################################### # Menu menubar = Menu(self) tool = Menu(menubar, tearoff=0) tool.add_command(label="Insert user info", command=self.user_info) tool.add_command(label="Display kinect", command=self.disp_kinect) tool.add_checkbutton(label="Ignore sensor error", onvalue=1, offvalue=0, variable=self.sensor_ignore) tool.add_checkbutton(label="Ignore buffer error", onvalue=1, offvalue=0, variable=self.buffer_ignore) tool.add_checkbutton(label="debug mode", onvalue=1, offvalue=0, variable=self.debug_mode) tool.add_command(label="Close sensors", command=self.close) menubar.add_cascade(label="Tools", menu=tool) self.config(menu=menubar) # Tk widgets ---------------------------------------------------------- ####################################################################### # Sensor controls ----------------------------------------------------- self.azure = PyK4A() self.azure.start() self.stream_reset() self.get_video() self.stream_video() self.stream_depth() self.set_state() self.refresh() # Main loop ----------------------------------------------------------- self.mainloop() # Main loop ----------------------------------------------------------- ####################################################################### def get_video(self): img = self.azure.get_capture() time_stamp = img.color_timestamp_usec delta = time_stamp - self.time_stamp_tmp self.time_stamp_tmp = time_stamp if self.is_streaming: print(delta) if np.any(img.color): if delta < 33400: pass else: print('stream dropping 33400') self.video_stream.append(self.rgb_frame_tmp) self.depth_stream.append(self.depth_frame_tmp) self.depth_frame_tmp = img.depth self.rgb_frame_tmp = img.color self.video_stream.append(self.rgb_frame_tmp) self.depth_stream.append(self.depth_frame_tmp) else: print('stream dropping') self.after(30, self.get_video) def stream_video(self): if self.is_streaming: if self.video_stream.__len__() > 0: self.frame_count += 1 img_color = self.video_stream.pop(0) img_color = img_color[:, :, 2::-1].astype(np.uint8) img_color = img_color[:, :, 2::-1] self.rgb_out.write(img_color) elif self.video_stream.__len__() == 0: pass self.after(VIDEO_SPEED, self.stream_video) def stream_depth(self): if self.is_streaming: if self.depth_stream.__len__() > 0: img_depth = self.depth_stream.pop(0) cv2.normalize(img_depth, img_depth, 0, 255, cv2.NORM_MINMAX) img_depth = cv2.cvtColor(img_depth, cv2.COLOR_GRAY2RGB) img_depth = img_depth.astype(np.uint8) self.depth_out.write(img_depth) elif self.depth_stream.__len__() == 0: pass self.after(VIDEO_SPEED, self.stream_depth) def activity_start(self, index): label = None if index == 0: label = f'0 {self.activity.get()} start' self.act_end_btn['state'] = NORMAL self.act_start_btn['state'] = DISABLED elif index == 1: label = f'1 {self.activity1.get()} start' self.act_end_btn1['state'] = NORMAL self.act_start_btn1['state'] = DISABLED for client in self.clients: client.label = f'{label}' self.activity_list.append(label) msg = f'{ACTIVITIE_START}-{label}' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) self.video_activity_time.append([self.frame_count, label]) self.stream_stop_btn['state'] = DISABLED self.stream_start_btn['state'] = DISABLED self.stream_save_btn['state'] = DISABLED self.stream_reset_btn['state'] = DISABLED def activity_end(self, index): label = None if index == 0: label = f'0 {self.activity.get()} end' self.act_end_btn['state'] = DISABLED self.act_start_btn['state'] = NORMAL elif index == 1: label = f'1 {self.activity1.get()} end' self.act_end_btn1['state'] = DISABLED self.act_start_btn1['state'] = NORMAL for client in self.clients: client.label = f'{label}' msg = f'{ACTIVITIE_STOP}-{label}' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) self.video_activity_time.append([self.frame_count, label]) self.stream_stop_btn['state'] = NORMAL self.stream_start_btn['state'] = DISABLED self.stream_save_btn['state'] = DISABLED self.stream_reset_btn['state'] = DISABLED def stream_start(self): sen_count = 0 for i in range(len(self.clients)): if self.clients[i].sensor_ready: sen_count += 1 else: if self.sensor_ignore.get(): sen_count += 1 else: messagebox.showwarning("Sensor Error", f"{SENSOR_ERROR}-{i+1}") if sen_count == len(self.clients) and self.age[0] != 'User': if not self.clients[0].is_started: self.start_sec = dt.today() self.date = self.start_sec.strftime(DATE_FORMAT) self.time = self.start_sec.strftime(TIME_FORMAT) self.time_path = \ f"{SAVE_PATH}/{self.date}/{self.time}" os.makedirs(f'{CACHE_PATH}/{self.date}/{self.time}') self.srt = open( f"{CACHE_PATH}/{self.date}/{self.time}/k3_rgb.srt", "w+") self.rgb_out = cv2.VideoWriter( f"{CACHE_PATH}/{self.date}/{self.time}/k3_rgb.avi", cv2.VideoWriter_fourcc(*'DIVX'), FPS, AZURE_KINECT_RGB_SIZE) self.depth_out = cv2.VideoWriter( f"{CACHE_PATH}/{self.date}/{self.time}/k3_depth.avi", cv2.VideoWriter_fourcc(*'DIVX'), FPS, AZURE_KINECT_DEPTH_SIZE) self.is_streaming = True for client in self.clients: client.stream_init(f'{CACHE_PATH}/{self.date}/{self.time}') else: self.is_streaming = True for client in self.clients: client.is_streaming = True msg = f'{START}-{self.time_path}' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) self.stream_start_btn['state'] = DISABLED self.stream_start_btn['text'] = "Resume stream" self.stream_stop_btn['state'] = NORMAL self.stream_reset_btn['state'] = DISABLED self.stream_save_btn['state'] = DISABLED self.act_end_btn['state'] = DISABLED self.act_start_btn['state'] = NORMAL self.act_end_btn1['state'] = DISABLED self.act_start_btn1['state'] = NORMAL else: messagebox.showerror('ERROR', f'Insert user info or check sensors') self.is_streaming = False self.stream_stop(send=False) # self.stream_reset(delete=True) def stream_stop(self, send=True): self.is_streaming = False for client in self.clients: client.is_streaming = False if send: self.stop_sec = dt.today() msg = f'{STOP}-?' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) self.stream_stop_btn['state'] = DISABLED self.stream_start_btn['state'] = NORMAL self.stream_save_btn['state'] = NORMAL self.stream_reset_btn['state'] = NORMAL self.act_end_btn['state'] = DISABLED self.act_start_btn['state'] = DISABLED self.act_end_btn1['state'] = DISABLED self.act_start_btn1['state'] = DISABLED def stream_save(self): msg = f'{SAVE}-{self.time_path}' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) for index, item in enumerate(self.video_activity_time): time = round(item[0] * 33.333) label = item[1] s_h, s_m, s_s, ms = get_time_1(time) s_s_t = str((s_s + SUB_DURATION) % 60).zfill(2) s_m_t = str((s_m + (s_s + SUB_DURATION) // 60)).zfill(2) s_h_t = str( (s_h + ((s_m + (s_s + SUB_DURATION) // 60) // 60))).zfill(2) s_h = str(s_h).zfill(2) s_m = str(s_m).zfill(2) s_s = str(s_s).zfill(2) self.srt.writelines([ f"{(index+1)*2-1}\n", f"{s_h}:{s_m}:{s_s},{ms} --> {s_h_t}:{s_m_t}:{s_s_t},{ms}\n", f"{label}\n", "\n" ]) self.srt.close() self.rgb_out.release() self.depth_out.release() try: os.makedirs(f'{SAVE_PATH}/{self.date}') except FileExistsError: pass move(f'{CACHE_PATH}/{self.date}/{self.time}', f'{SAVE_PATH}/{self.date}') usr_info = open(f'{SAVE_PATH}/{self.date}/{self.time}/user_info.csv', "w+", newline='') writer = csv.writer(usr_info) with usr_info: writer.writerow([self.age, self.sex, self.height, self.weight]) rmtree(f'{CACHE_PATH}/{self.date}') self.summary() self.stream_reset() def stream_reset(self, delete=False): try: msg = f'{RESET}-{self.time_path}' self.sound_client.publish(topic='sound', msg=msg, qos=0) self.kinect_client.publish(topic='kinect', msg=msg, qos=0) except AttributeError: pass self.stream_start_btn['text'] = "Stream start" self.stream_reset_btn['state'] = DISABLED self.stream_save_btn['state'] = DISABLED self.stream_stop_btn['state'] = DISABLED self.stream_start_btn['state'] = NORMAL self.act_start_btn['state'] = DISABLED self.act_start_btn['state'] = DISABLED self.video_stream = list() self.depth_stream = list() self.activity_list = list() self.video_activity_time = [] for client in self.clients: client.is_started = False try: del (self.rgb_out) del (self.depth_out) except AttributeError: pass if delete: try: os.remove(f'{CACHE_PATH}/{self.date}/{self.time}/k3_rgb.avi') os.remove(f'{CACHE_PATH}/{self.date}/{self.time}/k3_depth.avi') os.remove(f'{CACHE_PATH}/{self.date}/{self.time}/k3_rgb.srt') for client in self.clients: os.remove( f'{CACHE_PATH}/{self.date}/{self.time}/sensor_{client.info}.csv' ) rmtree(f'{CACHE_PATH}/{self.date}') except Exception as e: if self.debug_mode.get(): print(str(e)) else: pass def summary(self): os.system("clear") print("---- RESULT SUMMARY ----") print( f"start time: {self.start_sec.strftime(TIME_FORMAT)} ---> end time: {self.stop_sec.strftime(TIME_FORMAT)}" ) print(f"Duration: {get_time_date(self.start_sec, self.stop_sec)}") print("\n----------------------------------------------------") print("Activities performed:") for index, label in enumerate(self.activity_list): spaces = [" " for i in range(index)] space = "".join(spaces) print(f"{space}{index+1}: {label}") print("----------------------------------------------------") def user_info(self): user = UserInfo(self) self.wait_window(user.win) self.age = user.age self.sex = user.sex self.weight = user.weight self.height = user.height try: self.age_label['text'] = user.age[0] self.sex_label['text'] = user.sex[0] self.height_label['text'] = str(user.height[0]) self.weight_label['text'] = str(user.weight[0]) except Exception: self.age1_label['text'] = 'User' self.sex1_label['text'] = 'User' self.height1_label['text'] = 'User' self.weight1_label['text'] = 'User' try: self.age1_label['text'] = str(user.age[1]) self.sex1_label['text'] = user.sex[1] self.height1_label['text'] = str(user.height[1]) self.weight1_label['text'] = str(user.weight[1]) except Exception: self.age1_label['text'] = 'User' self.sex1_label['text'] = 'User' self.height1_label['text'] = 'User' self.weight1_label['text'] = 'User' del (user) def refresh(self): for i in range(len(self.clients)): if self.clients[i].sensor_ready: self.sensor_state[i]["foreground"] = 'green' else: self.sensor_state[i]["foreground"] = 'red' def set_state(self): for client in self.clients: if client.counter != client.counter_temp: client.counter_temp = client.counter client.death_counter = 0 if self.debug_mode.get(): print(f'[INFO] SENSOR-{client.info} is working') else: print(f'[WARNING] SENSOR-{client.info} is not responding') client.death_counter += 1 client.sensor_ready = False if client.death_counter > 8: messagebox.showerror('ERROR', f'SENSOR {client.info} DEAD') self.after(1000, self.set_state) def disp_kinect(self): if self.is_displaying: self.is_displaying = False msg = f'{STOP}-?' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) else: self.is_displaying = True msg = f'{PLAY}-?' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0) def close(self): msg = f'{QUIT}-?' self.kinect_client.publish(topic='kinect', msg=msg, qos=0) self.sound_client.publish(topic='sound', msg=msg, qos=0)
c1 = '{:02x}'.format(abs(z - 238)) self.c.after((i * delay // 4 + z + hold), lambda c1=c1, i=i: update_color(c1, i)) for f in range(count): for z in range(1, 238, 5): self.c.after((hold * 2) * f, lambda z=z: color_loops(z)) if __name__ == "__main__": root = Tk() root.grid() c = Canvas(root, width=wid, height=200) c.grid() fnt = font.Font(family="Courier", size=50) in_progress = BooleanVar(False) wtf = dicey_string(c, words[0], wid // 2, 100, fnt) def two(event): wtf.a_wave(event, 20, 4, wav, "^", words[randrange(4)]) wtf.c_fade(None, 20, 1) c.bind_all( "1", lambda event: wtf.a_wave(event, 20, 4, wav, "^", words[randrange(4)])) c.bind_all( "2", lambda event: wtf.a_wave(event, 20, 3, tsu, "~", words[randrange(4)])) c.bind_all("3", lambda event: wtf.a_tw(event, 50, words[randrange(4)])) c.bind_all("4", lambda event: wtf.change_string(event, words[randrange(4)]))
class MainWindow: image_index = 0 ImageCount = 0 canvas = None lock = False Image_list = [] x1, x2, y1, y2 = (0, 0, 0, 0) def autoPositing(self): if self.isInnerCircle == True: #------------------------ cw = self.img_org.size[0] // 2 #width ch = self.img_org.size[1] // 2 r = 90 box = (cw - r, ch - r, cw + r * 2, ch + r) img_center = self.img_org.crop(box) #self.canvas.create_rectangle(box) img_center = img_center.filter(ImageFilter.MedianFilter(5)) img_center = img_center.convert("L") #img_center.show() w = img_center.size[0] #x h = img_center.size[1] #y img_center = np.array(img_center) small = 640 * 255 small_x = 0 small_y = 0 for i in range(h): s = sum(img_center[i, :]) if s < small: small = s small_y = i small = 640 * 255 for j in range(w): s = sum(img_center[:, j]) if s < small: small = s small_x = j #------------------------ small_x += cw - r small_y += ch - r self.inner_x.set(small_x) self.inner_y.set(small_y) #print(small,small_x,small_y) #----------------------------- self.updateInterface(innercironly=True) else: self.dr = self.outside_d.get() - self.inner_d.get() self.outside_d.set(self.inner_d.get() + self.dr) self.outside_x.set(self.inner_x.get()) self.outside_y.set(self.inner_y.get()) self.recovercox() self._DrawCircle(moving=False, update=True) def recovercox(self): if self.isInnerCircle == True: self.x1 = self.inner_x.get() - self.inner_d.get() // 2 self.y1 = self.inner_y.get() - self.inner_d.get() // 2 self.x2 = self.inner_x.get() + self.inner_d.get() // 2 self.y2 = self.inner_y.get() + self.inner_d.get() // 2 else: self.x1 = self.outside_x.get() - self.outside_d.get() // 2 self.y1 = self.outside_y.get() - self.outside_d.get() // 2 self.x2 = self.outside_x.get() + self.outside_d.get() // 2 self.y2 = self.outside_y.get() + self.outside_d.get() // 2 def updateInterface(self, block=None, innercironly=False): self.lock = False index = 0 if block != None: for vi in self.variable_list[1:]: vi.set(block[index]) index += 1 self.isInnerCircle = True self.recovercox() self._DrawCircle(moving=False, update=True) if innercironly == False: self.isInnerCircle = False self.recovercox() self._DrawCircle(moving=False, update=True) self.canvas.update() #--------------------- self.processChooseInner() def autoTurn(self): data = 'start' count = -1 pic_num = self.myio.len_filelist while (data != None and count < pic_num): count += 1 self.processRButton() data = self.myio.pickoneDB(self.filename) print(("You have finished %d pictures") % (count)) def processRButton(self): #print("RButton") self.lock = False self.filename = self.myio.nextfilename() self.showPicture(self.filename) self.currentfile.set(self.filename) data = self.myio.pickoneDB(self.filename) #print(data) if data != None: self.updateInterface(data[1:]) else: self.processChooseInner() self.autoPositing() def unknownError(self): tkinter.messagebox.showerror("unknownError", "Please resetart this script!!!") def processLButton(self): print("LButton") self.lock = False filename = self.myio.lastfilename() self.showPicture(filename) self.currentfile.set(filename) data = self.myio.pickoneDB(filename) if data != None: self.updateInterface(data[1:]) def processChooseInner(self): self.radio_innerCircle.select() self.radio_outsideCircle.deselect() self.isInnerCircle = True self.recovercox() def processChooseOutside(self): self.radio_innerCircle.deselect() self.radio_outsideCircle.select() self.isInnerCircle = False self.autoPositing() def processSave(self): filename = self.currentfile.get() block = [vi.get() for vi in self.variable_list[1:]] self.myio.processSaveDB(filename, block) #--------------draw a circle------- idraw = ImageDraw.Draw(self.img_org) r = block[0] // 2 x = block[1] y = block[2] innercirobx = [x - r, y - r, x + r, y + r] r = block[3] // 2 x = block[4] y = block[5] outsidecirobx = [x - r, y - r, x + r, y + r] for i in range(2): idraw.ellipse(innercirobx, outline='white') innercirobx = self.inc_r(innercirobx) idraw.ellipse(outsidecirobx, outline='white') outsidecirobx = self.inc_r(outsidecirobx) outputname = 'output_image/' + os.path.split( self.currentfile.get())[-1] #print(outputname) self.img_org.save(outputname) #---------------------------------- self.processRButton() def Press(self, event): self.x1 = event.x self.y1 = event.y def showPicture(self, filename): self.img_org = Image.open(filename) self.h = self.img_org.height self.w = self.img_org.width if self.isContrastEnh: box = (0, 0, self.w, self.h) img = self.img_org.crop(box) contrast = ImageEnhance.Contrast(img) contrast_img = contrast.enhance(2.0) self.img = ImageTk.PhotoImage(contrast_img) else: self.img = ImageTk.PhotoImage(self.img_org) if self.canvas.find_withtag('img'): self.canvas.delete('img') self.canvas.create_image(self.w // 2, self.h // 2, image=self.img) self.canvas.update() def _DrawCircle(self, moving=True, update=False): ch = 'inner' if self.isInnerCircle == False: ch = 'outside' if update: self.canvas.delete(ch) d = self.x2 - self.x1 if not self.canvas.find_withtag(ch): self.canvas.create_oval(self.x1, self.y1, self.x1 + d, self.y1 + d, outline='white', tags=ch, width=2) elif moving: self.canvas.delete(ch) if self.isInnerCircle: self.inner_d.set(d) self.inner_x.set(self.x1 + d // 2) self.inner_y.set(self.y1 + d // 2) else: self.outside_d.set(d) self.outside_x.set(self.x1 + d // 2) self.outside_y.set(self.y1 + d // 2) def Release(self, event): self._DrawCircle(moving=False, update=True) def Draw(self, event): self.x2 = event.x self.y2 = event.y self._DrawCircle() def PressKey(self, event): key = event.keysym if self.lock == False: self.lock = True self.recovercox() if key == 'w': self.y1 -= 2 self.y2 -= 2 elif key == 's': self.y1 += 2 self.y2 += 2 elif key == 'a': self.x1 -= 2 self.x2 -= 2 elif key == 'd': self.x1 += 2 self.x2 += 2 elif key == 'q': self.x2 -= 2 self.y2 -= 2 elif key == 'e': self.x2 += 2 self.y2 += 2 elif key == 'space': if self.isInnerCircle == True: self.processChooseOutside() else: self.processSave() self._DrawCircle(moving=False, update=True) def openFolder(self): filenameforReading = askdirectory() self.myio = MyIO(filenameforReading) #self.processRButton() self.autoTurn() def openCsv(self): tkinter.messagebox.showerror("error", "under construction") def openDatabase(self): filenameforReading = askopenfilename() print(filenameforReading) if self.myio != None: self.myio.setdb_path(filenameforReading) self.autoTurn() def outputcsv(self): data = self.myio.pickallDB() outputname = 'data.csv' with open(outputname, 'a+') as csvfile: f_csv = csv.writer(csvfile) for row in data: f_csv.writerow(row) def inc_r(self, box): r = [-1, -1, 1, 1] for i in range(4): box[i] += r[i] return box def outputpic(self): data = self.myio.pickallDB() names = self.myio.pickallDB(True) name_set = set(names) index = 0 for row in data: #--------------draw a circle------- filename = self.myio.filelist[index] pic_name = os.path.split(filename)[-1] if pic_name not in name_set: index += 1 continue self.img_org = Image.open(filename) idraw = ImageDraw.Draw(self.img_org) r = row[1] // 2 x = row[2] y = row[3] innercirobx = [x - r, y - r, x + r, y + r] r = row[4] // 2 x = row[5] y = row[6] outsidecirobx = [x - r, y - r, x + r, y + r] for i in range(2): idraw.ellipse(innercirobx, outline='white') innercirobx = self.inc_r(innercirobx) idraw.ellipse(outsidecirobx, outline='white') outsidecirobx = self.inc_r(outsidecirobx) outputname = 'output_image/' + os.path.split(row[0])[-1] print(outputname) self.img_org.save(outputname) index += 1 #---------------------------------- def AlterDBFName(self): self.myio.alterAllFNameDB() def ContrastEnh(self): if self.isContrastEnh == False: self.isContrastEnh = True else: self.isContrastEnh = False self.showPicture(self.currentfile.get()) def __init__(self): self.myio = None self.isContrastEnh = False window = Tk() window.title("Assist Tool") leftICO = PhotoImage(file="ICO/left.gif") rightICO = PhotoImage(file="ICO/right.gif") SaveICO = PhotoImage(file="ICO/Save.gif") self.inner_x = IntVar() self.inner_y = IntVar() self.inner_d = IntVar() self.outside_x = IntVar() self.outside_y = IntVar() self.outside_d = IntVar() self.currentfile = StringVar() self.variable_list = [ self.currentfile, self.inner_d, self.inner_x, self.inner_y, self.outside_d, self.outside_x, self.outside_y ] self.h = 480 self.w = 640 self.isInnerCircle = BooleanVar() self.isInnerCircle.set(True) frame_left = Frame(window) frame_left.grid(row=1, column=1) frame_right = Frame(window) frame_right.grid(row=1, column=2) frame_bottom = Frame(window) frame_bottom.grid(row=2, column=1) frame_right_1 = Frame(frame_right) frame_right_1.grid(row=1, column=1) frame_right_2 = Frame(frame_right) frame_right_2.grid(row=2, column=1) frame_right_3 = Frame(frame_right) frame_right_3.grid(row=3, column=1) frame_right_4 = Frame(frame_right) frame_right_4.grid(row=4, column=1) frame_right_5 = Frame(frame_right) frame_right_5.grid(row=5, column=1) #------------------banging--------- self.canvas = Canvas(frame_left) self.canvas["width"] = self.w self.canvas["height"] = self.h self.canvas.pack() self.canvas.bind('<Button-1>', self.Press) self.canvas.bind('<B1-Motion>', self.Draw) self.canvas.bind('<ButtonRelease-1>', self.Release) window.bind('<Key>', self.PressKey) #-------------show background picture----- self.currentfile.set("ICO/rabbit640480.jpg") self.showPicture("ICO/rabbit640480.jpg") #--------------show filename self.label_filename = Label(frame_bottom, textvariable=self.currentfile) self.label_filename.pack() #-------------control button Button(frame_right_2, image=leftICO, command=self.processLButton).pack(side=LEFT) Button(frame_right_2, image=rightICO, command=self.processRButton).pack(side=LEFT) #-------------show info of inner circle self.radio_innerCircle = Radiobutton(frame_right_3, text="Inner Circle", command=self.processChooseInner, variable=self.isInnerCircle, value=True) self.radio_innerCircle.grid(row=1, column=2) Label(frame_right_3, text="d").grid(row=2, column=1) self.inner_d.set(70) self.dr = 102 self.entry_inner_d = Entry(frame_right_3, textvariable=self.inner_d) self.entry_inner_d.grid(row=2, column=2) Label(frame_right_3, text="x").grid(row=3, column=1) self.entry_inner_x = Entry(frame_right_3, textvariable=self.inner_x) self.entry_inner_x.grid(row=3, column=2) Label(frame_right_3, text="y").grid(row=4, column=1) self.entry_inner_y = Entry(frame_right_3, textvariable=self.inner_y) self.entry_inner_y.grid(row=4, column=2) #------------show info of outside circle self.radio_outsideCircle = Radiobutton( frame_right_4, text="Outside Circle", command=self.processChooseOutside, variable=self.isInnerCircle, value=False) self.radio_outsideCircle.grid(row=1, column=2) Label(frame_right_4, text="d").grid(row=2, column=1) self.entry_outside_d = Entry(frame_right_4, textvariable=self.outside_d) self.entry_outside_d.grid(row=2, column=2) Label(frame_right_4, text="x").grid(row=3, column=1) self.entry_outside_x = Entry(frame_right_4, textvariable=self.outside_x) self.entry_outside_x.grid(row=3, column=2) Label(frame_right_4, text="y").grid(row=4, column=1) self.entry_outside_y = Entry(frame_right_4, textvariable=self.outside_y) self.entry_outside_y.grid(row=4, column=2) #-------------Save button self.radio_isContrastEnh = Checkbutton( frame_right_5, text="Contrast Enhance", command=self.ContrastEnh).pack() #self.radio_isContrastEnh.deselect() Button(frame_right_5, image=SaveICO, command=self.processSave).pack() #--------------menubar menubar = Menu(window) window.config(menu=menubar) openMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Open", menu=openMenu) openMenu.add_command(label="Folder", command=self.openFolder) openMenu.add_command(label="sqlite3 database", command=self.openDatabase) openMenu.add_command(label="csv file", command=self.openCsv) AlterMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Alter", menu=AlterMenu) AlterMenu.add_command(label="Alter db fName", command=self.AlterDBFName) outputMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Output", menu=outputMenu) outputMenu.add_command(label="csv file", command=self.outputcsv) outputMenu.add_command(label="picture", command=self.outputpic) #-------------finally--------- self.radio_innerCircle.select() if os.path.exists('output_image') == False: os.mkdir('output_image') window.mainloop()
def __init__(self): self._terminate = BooleanVar(False) self._id = StringVar(False)
def setUpClass(cls): cls.tracers = configdialog.VarTrace() cls.iv = IntVar(root) cls.bv = BooleanVar(root)
def init_pf(self): def load_file(): f = filedialog.askopenfilename() self.pf_file.set(f) def analyze_pf(): if self.pf_filter.get(): pf = picketfence.PicketFence(self.pf_file.get(), filter=3) else: pf = picketfence.PicketFence(self.pf_file.get()) atol = self.pf_atol.get() if self.pf_atol.get() == 0 else None pickets = self.pf_pickets.get() if self.pf_pickets.get( ) == 0 else None hd = self.pf_hdmlc.get() pf.analyze( tolerance=self.pf_tol.get(), action_tolerance=atol, hdmlc=hd, num_pickets=pickets, ) fname = osp.join(self.pf_file.get().replace('.dcm', '.pdf')) pf.publish_pdf(fname) self.pf_pdf.set(fname) utilities.open_path(fname) self.pf_tab = Frame(self.notebook) self.pf_filter = BooleanVar(value=False) self.pf_file = StringVar() self.pf_tol = DoubleVar(value=0.5) self.pf_atol = DoubleVar(value=0.25) self.pf_pickets = IntVar(value=10) self.pf_hdmlc = BooleanVar(value=False) self.pf_pdf = StringVar() Checkbutton(self.pf_tab, text='Apply median filter', variable=self.pf_filter).grid(column=1, row=3) Button(self.pf_tab, text='Load File...', command=load_file).grid(column=1, row=1) Label(self.pf_tab, text='File:').grid(column=1, row=2) Label(self.pf_tab, textvariable=self.pf_file).grid(column=2, row=3) Label(self.pf_tab, text='Tolerance (mm):').grid(column=1, row=4) Entry(self.pf_tab, width=7, textvariable=self.pf_tol).grid(column=2, row=4) Label(self.pf_tab, text='Action Tolerance (mm):').grid(column=1, row=5) Entry(self.pf_tab, width=7, textvariable=self.pf_atol).grid(column=2, row=5) Label(self.pf_tab, text='Number of pickets:').grid(column=1, row=6) Entry(self.pf_tab, width=7, textvariable=self.pf_pickets).grid(column=2, row=6) Checkbutton(self.pf_tab, text='HD-MLC?', variable=self.pf_hdmlc).grid(column=1, row=7) Button(self.pf_tab, text='Analyze', command=analyze_pf).grid(column=1, row=8) Label( self.pf_tab, text= 'Analysis will analyze the file according to the settings, \nsave a PDF in the same directory as the original file location and then open it.' ).grid(column=1, row=9) self.notebook.add(self.pf_tab, text='Picket Fence') for child in self.pf_tab.winfo_children(): child.grid_configure(padx=10, pady=5)
class EarthquakeGUI: def _quit(self): # Quit program quit() # win will exist when this function is called Tk.destroy(self) exit() def _refreshData(self): logging.debug("") t1 = datetime.now() JSONdata = getWebData(urlData) t2 = datetime.now() tdweb = t2 - t1 if JSONdata: hList = loadHeaderInfo(JSONdata) logging.info(f"Web Retrieval - {hList['count']:,} " f"records in {tdweb.total_seconds(): .3}s") eList = loadList(JSONdata) eList = self.sortData(eList) self.updateHeaderFields(hList) self.updateFields(eList, self.summarySelected.current()) else: messagebox.showerror( "USGS File error", "Error retrieving " "data from USGS web site. Check console for error.") logging.error("Error retrieving file") def _comboCallbackFunc(self, event, data): logging.debug("") # When combo box changes, updated data with new selection self.updateFields(data, self.summarySelected.current()) def _webCallbackFunc(self, data): logging.debug("") webbrowser.open_new(data) def getNewData(self, timeString): logging.debug("") global urlData x = urlData.find("summary/") y = urlData.find(".geojson") logging.debug(urlData[x + 8:y]) urlData = str(urlData.replace(urlData[x + 8:y], timeString, 1)) logging.debug(urlData) self._refreshData() # When combo box changes, updated data with new selection # self.updateFields(data, self.summarySelected.current()) # return urlData def updateComboBoxData(self, data): logging.debug("") dropdownlist = [] self.summarySelected.delete(0) if len(data) > 0: for n, _ in enumerate(data): mag = f"{data[n][1]:.1f}" mmi = f"{data[n][8]:.3f}" dropdownlist.append(mag + " - " + mmi + " - " + str(data[n][2])) self.summarySelected["values"] = dropdownlist self.summarySelected.current(0) self.summarySelected.bind( "<<ComboboxSelected>>", lambda event, arg=data: self._comboCallbackFunc(event, arg), ) else: self.summarySelected["values"] = dropdownlist self.summarySelected.set("") def sortData(self, data): logging.debug(f"{self.sortOption.get()}") try: if self.sortOption.get() == '2': s_eList = sorted(data, key=lambda x: (x[8], x[1], x[7]), reverse=True) else: s_eList = sorted(data, key=lambda x: (x[1], x[7]), reverse=True) eList = s_eList[:] except: logging.error("Error sorting list - most likely bad data") self.updateComboBoxData(eList) return eList def __init__(self, data, header): self.win = Tk() self.win.title("USGS Current Earthquake Data") self.checked = BooleanVar() self.checked.trace("w", self.mark_checked) self.sortOption = StringVar() self.sortOption.set("1") self.sortOption.trace("w", self.mark_sortOption) # ----- Menu Bar - Create the Menu Bar ------------------------- menuBar = Menu() self.win.config(menu=menuBar) fileMenu = Menu(menuBar, tearoff=False) dataMenu = Menu(menuBar, tearoff=False) optionsMenu = Menu(menuBar, tearoff=False) helpMenu = Menu(menuBar, tearoff=False) menuBar.add_cascade(menu=fileMenu, label="File") menuBar.add_cascade(menu=dataMenu, label="Data") menuBar.add_cascade(menu=optionsMenu, label="Options") menuBar.add_cascade(menu=helpMenu, label="Help") # ----- Menu Bar - Create the File Menu ------------------------ fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) # ----- Menu Bar - Create the Options Menu --------------------- sortSubMenu = Menu(optionsMenu, tearoff=False) optionsMenu.add_cascade(menu=sortSubMenu, label="Sort") sortSubMenu.add_radiobutton(label="Sort by Magnitude", value="1", variable=self.sortOption) sortSubMenu.add_radiobutton( label="Sort by Predictive damage or Shake(MMI)", value="2", variable=self.sortOption) # ----- Menu Bar - Create the Data Menu------------------------- dataMenu.add_command(label="Refresh current Data source", command=self._refreshData) dataMenu.add_separator() dataSubMenu = Menu(dataMenu, tearoff=False) dataMenu.add_cascade(menu=dataSubMenu, label="New Data Source") # ----- Menu Bar - Create the Data submenu --------------------- d1 = [ ["Significant", "significant"], ["Magnitude 4.5+", "4.5"], ["Magnitude 2.5+", "2.5"], ["Magnitude 1.0+", "1.0"], ["All Earthquakes+", "all"], ] d2 = [ ["hour", "hour"], ["day", "day"], ["7 days", "week"], ["30 days", "month"], ] for i in range(len(d2)): for j in range(len(d1)): s1 = str(d1[j][0] + ", past " + d2[i][0]) s2 = str(d1[j][1] + "_" + d2[i][1]) dataSubMenu.add_command( label=s1, command=lambda widget=s2: self.getNewData(widget)) if j == (len(d1) - 1) and i != (len(d2) - 1): dataSubMenu.add_separator() # ----- Set up frames and subframes to store widgets ----------- self.mainFrame = ttk.LabelFrame() self.headings_frame = ttk.LabelFrame(self.mainFrame) self.headings_frame.grid(row=0) self.selection_frame = ttk.LabelFrame(self.headings_frame, text="selection frame") self.selection_frame.configure(text=header["title"]) self.selection_frame.grid(column=0, columnspan=2, row=0, sticky="NW") self.file_frame = ttk.LabelFrame(self.headings_frame, text="File Info") self.file_frame.grid(column=2, row=0, rowspan=3, sticky="NW") self.details_frame = ttk.LabelFrame(self.mainFrame) self.details_frame.grid(row=1) self.summary_frame = ttk.LabelFrame(self.details_frame, text="Event Details") self.summary_frame.grid(row=0, columnspan=2) self.location_frame = ttk.LabelFrame(self.details_frame, text="Event Location") self.location_frame.grid(row=1, column=0, sticky="NW") self.time_frame = ttk.LabelFrame(self.details_frame, text="Time of Event") self.time_frame.grid(row=1, column=1, sticky="NW") ttk.Label(self.selection_frame).grid(column=0, row=0, sticky="W") # ----- Set up combo box and data to populate it --------------- self.summarySelected = ttk.Combobox(self.selection_frame, width=85, state="readonly") self.summarySelected.grid(column=0, row=1) self.updateComboBoxData(data) # ----- Add File widget - File delta --------------------------- self.fileDelta = StringVar() fileDeltaEntry = ttk.Label(self.file_frame, width=25, textvariable=self.fileDelta, state="readonly") fileDeltaEntry.grid(column=1, row=0, columnspan=2, sticky="W") # ----- Add File widget - File Time ---------------------------- ttk.Label(self.file_frame, text="File Time:").grid(column=0, row=1, sticky="E") self.fileTime = StringVar() fileTimeEntry = ttk.Label(self.file_frame, width=25, textvariable=self.fileTime, state="readonly") fileTimeEntry.grid(column=1, row=1, sticky="W") # ----- Add File widget - Event count -------------------------- ttk.Label(self.file_frame, text="Count:").grid(column=0, row=2, sticky="E") self.fileCount = StringVar() fileCountEntry = ttk.Label(self.file_frame, width=25, textvariable=self.fileCount, state="readonly") fileCountEntry.grid(column=1, row=2, sticky="W") # ----- Add Summary widget - Magnitude ------------------------- ttk.Label(self.summary_frame, text="Magnitude:").grid(column=0, row=0, sticky="E") self.mag = StringVar() magEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.mag, state="readonly") magEntry.grid(column=1, row=0, sticky="W") # ----- Add Summary widget - Alert ----------------------------- ttk.Label(self.summary_frame, text="Alert:").grid(column=2, row=0, sticky="E") self.alert = StringVar() alertEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.alert, state="readonly") alertEntry.grid(column=3, row=0, sticky="W") # ----- Add Summary widget - Shake ----------------------------- ttk.Label(self.summary_frame, text="Shake (MMI):").grid(column=4, row=0, sticky="E") self.shake = StringVar() shakeEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.shake, state="readonly") shakeEntry.grid(column=5, row=0, sticky="W") # ----- Add Summary widget - Report Felt ----------------------- ttk.Label(self.summary_frame, text="Reported felt:").grid(column=6, row=0, sticky="E") self.felt = StringVar() feltEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.felt, state="readonly") feltEntry.grid(column=7, row=0, sticky="W") # ----- Add Summary widget - Url/More Info --------------------- ttk.Label(self.summary_frame, text="More info:").grid(column=0, row=1, sticky="E") self.urlName = StringVar() self.urlEntry = ttk.Button(self.summary_frame) self.urlEntry.grid(column=1, row=1, columnspan=8, sticky="W") # ----- Add Location widget - Place ---------------------------- ttk.Label(self.location_frame, text="Place:").grid(column=0, row=4, sticky="E") self.place = StringVar() locEntry = ttk.Label(self.location_frame, width=45, textvariable=self.place, state="readonly") locEntry.grid(column=1, row=4, sticky="W") # ----- Add Location widget - Latitude ------------------------- ttk.Label(self.location_frame, text="Latitude:").grid(column=0, row=10, sticky="E") self.lat = StringVar() latEntry = ttk.Label(self.location_frame, width=25, textvariable=self.lat, state="readonly") latEntry.grid(column=1, row=10, sticky="W") # ----- Add Location widget - Longitude ------------------------ ttk.Label(self.location_frame, text="Longitude:").grid(column=0, row=11, sticky="E") self.lon = StringVar() longEntry = ttk.Label(self.location_frame, width=25, textvariable=self.lon, state="readonly") longEntry.grid(column=1, row=11, sticky="W") # ----- Add Location widget - Depth ---------------------------- ttk.Label(self.location_frame, text="Depth:").grid(column=0, row=12, sticky="E") self.depth = StringVar() depthEntry = ttk.Label(self.location_frame, width=25, textvariable=self.depth, state="readonly") depthEntry.grid(column=1, row=12, sticky="W") # ----- Add Time widget - Event delta -------------------------- self.deltaEntry = StringVar() deltaEntry = ttk.Label(self.time_frame, width=25, textvariable=self.deltaEntry, state="readonly") deltaEntry.grid(column=1, row=0, sticky="W") # ----- Add Time widget - Event Time --------------------------- ttk.Label(self.time_frame, text="Time:").grid(column=0, row=1, sticky="E") self.time = StringVar() timeEntry = ttk.Label(self.time_frame, width=25, textvariable=self.time, state="readonly") timeEntry.grid(column=1, row=1, sticky="W") # ----- Add Time widget - Event Local Time --------------------- ttk.Label(self.time_frame, text="Your local time:").grid(column=0, row=2, sticky="E") self.tz = StringVar() tzEntry = ttk.Label(self.time_frame, width=25, textvariable=self.tz, state="readonly") tzEntry.grid(column=1, row=2, sticky="W") # ----- Add padding around fields self.mainFrame.grid_configure(padx=8, pady=4) for child in self.mainFrame.winfo_children(): child.grid_configure(padx=8, pady=4) for grandChild in child.winfo_children(): grandChild.grid_configure(padx=8, pady=4) for widget in grandChild.winfo_children(): widget.grid_configure(padx=8, pady=4) # ----- Call funtion to update fields -------------------------- data = self.sortData(data) self.updateHeaderFields(header) self.updateFields(data, self.summarySelected.current()) def mark_checked(self, *args): logging.debug("") print(self.checked.get()) def mark_sortOption(self, *args): logging.debug("") print(self.sortOption.get()) JSONdata = getDataFile() if not JSONdata: self._refreshData() else: hList = loadHeaderInfo(JSONdata) eList = loadList(JSONdata) eList = self.sortData(eList) self.updateHeaderFields(hList) self.updateFields(eList, self.summarySelected.current()) def updateHeaderFields(self, header): # Update header fields for the file logging.debug("") global urlData urlData = header["url"] self.selection_frame.configure(text=header["title"]) self.fileCount.set(header["count"]) utc_time = datetime.utcfromtimestamp(header["timeStamp"] / 1000).replace(tzinfo=pytz.utc) self.fileTime.set(utc_time.strftime("%Y-%m-%d %H:%M:%S %Z")) self.fileDelta.set(deltaTime(self, utc_time)) def updateFields(self, data, rec): logging.debug("") if len(data) > 0: # Update fields in the display from the data record self.mag.set(f"{data[rec][1]:.1f}") self.place.set(data[rec][2]) utc_time = datetime.utcfromtimestamp(data[rec][3] / 1000).replace(tzinfo=pytz.utc) self.time.set(utc_time.strftime("%Y-%m-%d %H:%M:%S %Z")) current_tz = utc_time.astimezone(get_localzone()) self.tz.set(current_tz.strftime("%Y-%m-%d %H:%M:%S %Z")) self.urlName.set(data[rec][5]) self.felt.set(data[rec][6]) self.alert.set(data[rec][7]) self.shake.set(f"{data[rec][8]:.3f}") tmpLat = data[rec][10] if tmpLat == 0: self.lat.set("{} \xb0".format(tmpLat)) elif tmpLat > 0: self.lat.set("{} \xb0 N".format(tmpLat)) else: tmpLat *= -1 self.lat.set("{} \xb0 S".format(tmpLat)) tmpLong = data[rec][9] if tmpLong == 0: self.lon.set("{} \xb0".format(tmpLong)) elif tmpLong > 0: self.lon.set("{} \xb0 E".format(tmpLong)) else: tmpLong *= -1 self.lon.set("{} \xb0 W".format(tmpLong)) self.depth.set("{} km".format(data[rec][11])) # self.lon.set(data[rec][5]) self.deltaEntry.set(deltaTime(self, utc_time)) else: self.mag.set(None) self.place.set(None) self.time.set(None) self.tz.set(None) self.urlName.set(None) self.felt.set(None) self.alert.set(None) self.shake.set(None) self.lat.set(None) self.lon.set(None) self.depth.set(None) self.deltaEntry.set(None) self.urlEntry.config( text=self.urlName.get(), command=lambda arg=self.urlName.get(): self._webCallbackFunc(arg))
def __init__(self, tk, args): Frame.__init__(self, tk) # empty string for platform's default settings locale.setlocale(locale.LC_ALL, '') self.master = tk tk.title(APP_TITLE) tk.resizable(False, False) try: if WINDOWS: tk.iconbitmap("200x200/icon.ico") else: tk.iconbitmap("@200x200/icon.xbm") except Exception as e: print(e) atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_entry = Entry(self.middleFrameLeft) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameStyleLabel.grid(row=0, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=0, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_entry.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None: self.auto_play(args)
class BattleshipsDemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) # empty string for platform's default settings locale.setlocale(locale.LC_ALL, '') self.master = tk tk.title(APP_TITLE) tk.resizable(False, False) try: if WINDOWS: tk.iconbitmap("200x200/icon.ico") else: tk.iconbitmap("@200x200/icon.xbm") except Exception as e: print(e) atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_entry = Entry(self.middleFrameLeft) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameStyleLabel.grid(row=0, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=0, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_entry.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(APP_TITLE + " (Not Logged In)") self.cancel_game() self.bot_id = 'housebot-competition' self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = '******' res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + APP_TITLE) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_entry.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) self.balance['text'] += ' sat' def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': BATTLESHIPS_GAME_TYPE_ID } url = BASE_URL + GET_LIST_OF_GAME_STYLES_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): self.game_styles_listbox.insert( index, GAME_STYLE_LISTBOX_TEXT.format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() self.find_game() if self.game_cancelled: break self.play_game() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" opponent_id = self.specify_opponent_entry.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = BASE_URL + OFFER_GAME_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) game_style_details = self.game_styles_listbox.get('active').split( " | ") title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += format(' / Land: ' + game_style_details[6].split(" ")[2] + '%') title += format(' / Deals: ' + game_style_details[5].split(" ")[1]) title += format(' / ' + game_style_details[7]) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = battleships_move.calculateMove(game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = BASE_URL + MAKE_MOVE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = BASE_URL + POLL_FOR_GAME_STATE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) def cancel_game(self): if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = BASE_URL + CANCEL_GAME_OFFER_EXTENSION BattleshipsDemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- resultText Message object no longer exists") @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
class StealerApp: def __init__(self): self.initial_dir = get_path() self.root = Tk(className="osu! Utility Program") row_names = ["title_row", "dir_row", "check_row", "mode_row", "button_row"] # for maintainability rows = {row: index for index, row in enumerate(row_names)} Label(master=self.root, text="osu! Map Tool", font=("Verdana", 18)).grid(row=rows["title_row"], column=0, columnspan=3, sticky=W + E) Label(master=self.root, text="Osu! songs folder:").grid(row=rows["dir_row"], sticky=W) self._dir_entry = Entry(master=self.root) self._dir_entry.grid(row=rows["dir_row"], column=1) Button(self.root, text="Browse...", command=self.select_dir).grid(row=rows["dir_row"], column=2, sticky=W) Button(master=self.root, text="Create a shareable beatmap file", command=self.create_steal_file).grid(row=rows["button_row"], column=0) Button(master=self.root, text="Download from file", command=self.steal_beatmaps).grid(row=rows["button_row"], column=1) Button(master=self.root, text="Just Delete", command=self.delete_maps).grid(row=rows["button_row"], column=2) Label(master=self.root, text="Download flags:").grid(row=rows["check_row"], column=0, sticky=W) self._download_video = BooleanVar(master=self.root, value=False) Checkbutton(master=self.root, text="Delete video", variable=self._download_video, onvalue=False, offvalue=True).grid(row=rows["check_row"], column=1, sticky=W) Label(master=self.root, text="Game Modes To Download:").grid(row=rows["mode_row"], column=0, sticky=W) self.std = BooleanVar(master=self.root, value=True) Checkbutton(master=self.root, text="osu! standard", variable=self.std, onvalue=True, offvalue=False).grid(row=rows["mode_row"], column=1, sticky=W) self.mania = BooleanVar(master=self.root, value=False) Checkbutton(master=self.root, text="Mania", variable=self.mania, onvalue=True, offvalue=False).grid(row=rows["mode_row"], column=2, sticky=W) self.ctb = BooleanVar(master=self.root, value=False) Checkbutton(master=self.root, text="Catch The Beat", variable=self.ctb, onvalue=True, offvalue=False).grid(row=rows["mode_row"], column=3, sticky=W) self.taiko = BooleanVar(master=self.root, value=False) Checkbutton(master=self.root, text="Taiko", variable=self.taiko, onvalue=True, offvalue=False).grid(row=rows["mode_row"], column=4, sticky=W) @property def download_video(self): return self._download_video.get() def needs_songs_dir(fun): @wraps(fun) def songs_dir_checked_function(self, *args, **kwargs): if check_path(self.songs_dir): return fun(self, *args, **kwargs) else: showinfo(parent=self.root, message="Please enter your osu song folder first!") return songs_dir_checked_function @property def songs_dir(self): return self._dir_entry.get() @songs_dir.setter def songs_dir(self, value): self._dir_entry.delete(0, END) self._dir_entry.insert(0, value) def run(self): self.root.mainloop() def select_dir(self): self.songs_dir = askdirectory(title="Osu! Songs Folder", initialdir=self.initial_dir) def button_callback(fun): @wraps(fun) def on_click(self): t = Thread(target=partial(fun, self)) t.start() return on_click @button_callback @needs_songs_dir def create_steal_file(self): showinfo(parent=self.root, title="File select", message="Select where to save the beatmap file") beatmap_file_path = asksaveasfilename(parent=self.root, filetypes=[("Txt File", "*.txt")], initialdir=self.initial_dir, title="Your beatmap file", initialfile="beatmaps.txt") beatmap_file_path = force_txt_ext(beatmap_file_path) if check_path(beatmap_file_path) and path is not '.txt': create_steal_file(beatmap_file_path, self.songs_dir) showinfo(parent=self.root, title="Done!", message="Finished creating sharable beatmap file, the file should be waiting for you after you close this window\nGive this to other people for them to download your beatmaps!") self.root.destroy() @button_callback @needs_songs_dir def steal_beatmaps(self): showinfo(parent=self.root, title="beatmap file", message="Please select the file you want to steal from") other_beatmap = askopenfilename(parent=self.root, title="Beatmap file to steal from", initialdir=self.initial_dir, filetypes=[("Txt File", "*.txt")]) if check_path(other_beatmap): my_beatmaps = steal(self.songs_dir) try: download_beatmaps(my_beatmaps, other_beatmap, self.songs_dir, self.download_video) self.delete_maps() except ConnectionError: showinfo(parent=self.root, title="No internet", message="It seems like you aren't connected to the Internet.\nPlease connect and try again") self.root.destroy() else: showinfo(parent=self.root, title="Done!", message="Finished downloading the beatmaps you didn't already have!") self.root.destroy() @button_callback @needs_songs_dir def delete_maps(self): delete(self.songs_dir, {"std": self.std.get(), "mania": self.mania.get(), "ctb": self.ctb.get(), "taiko": self.taiko.get()}, self.download_video) showinfo(parent=self.root, title="Done!", message="Finished removing all videos and other game modes!") showinfo(parent=self.root, title="Done!", message="RECOMMENDED: refresh your osu! by clicking F5 while in song selection") self.root.destroy()
def __init__(self, parent, master=None, title="", prompt="", opts=None, radio=True, yesno=True, list=False): if not opts: opts = [] self.win = Toplevel(parent) self.win.protocol("WM_DELETE_WINDOW", self.quit) if parent: self.win.geometry( "+%d+%d" % (parent.winfo_rootx() + 50, parent.winfo_rooty() + 50)) self.parent = parent self.master = master self.options = opts self.radio = radio self.win.title(title) if list: self.win.configure(bg=BGCOLOR) tkfixedfont = tkFont.nametofont("TkFixedFont") if 'fontsize_fixed' in self.parent.options and self.parent.options[ 'fontsize_fixed']: tkfixedfont.configure( size=self.parent.options['fontsize_fixed']) self.content = ReadOnlyText(self.win, wrap="word", padx=3, bd=2, height=10, relief="sunken", font=tkfixedfont, bg=BGLCOLOR, highlightbackground=BGLCOLOR, width=46, takefocus=False) self.content.pack(fill=tkinter.BOTH, expand=1, padx=10, pady=5) self.content.insert("1.0", prompt) else: Label(self.win, text=prompt, justify='left').pack(fill=tkinter.BOTH, expand=1, padx=10, pady=5) self.sv = StringVar(parent) self.sv = IntVar(parent) self.sv.set(1) if self.options: if radio: self.value = opts[0] for i in range(min(9, len(self.options))): txt = self.options[i] val = i + 1 # bind keyboard numbers 1-9 (at most) to options selection, i.e., press 1 to select option 1, 2 to select 2, etc. self.win.bind(str(val), (lambda e, x=val: self.sv.set(x))) Radiobutton(self.win, text="{0}: {1}".format(val, txt), padx=20, indicatoron=True, variable=self.sv, command=self.getValue, value=val).pack(padx=10, anchor=W) else: self.check_values = {} # show 0, check 1, return 2 for i in range(min(9, len(self.options))): txt = self.options[i][0] self.check_values[i] = BooleanVar(self.parent) self.check_values[i].set(self.options[i][1]) Checkbutton(self.win, text=self.options[i][0], padx=20, variable=self.check_values[i]).pack(padx=10, anchor=W) box = Frame(self.win) if list: box.configure(bg=BGCOLOR) if yesno: YES = _("Yes") NO = _("No") else: YES = _("Ok") NO = _("Cancel") c = Button(box, text=NO, width=10, command=self.cancel, pady=2) c.pack(side=LEFT, padx=5, pady=5) o = Button(box, text=YES, width=10, default='active', command=self.ok, pady=2) o.pack(side=LEFT, padx=5, pady=5) if list: for b in [c, o]: b.configure(bg=BGCOLOR, highlightbackground=BGCOLOR) box.pack() self.win.bind('<Return>', (lambda e, o=o: o.invoke())) self.win.bind('<Control-w>', self.Ok) self.win.bind('<Escape>', (lambda e, c=c: c.invoke())) # self.choice.focus_set() logger.debug('parent: {0}'.format(parent)) self.win.focus_set() self.win.transient(parent) self.win.wait_window(self.win)
def test_set(self): true = 1 if self.root.wantobjects() else "1" false = 0 if self.root.wantobjects() else "0" v = BooleanVar(self.root, name="name") v.set(True) self.assertEqual(self.root.globalgetvar("name"), true) v.set("0") self.assertEqual(self.root.globalgetvar("name"), false) v.set(42) self.assertEqual(self.root.globalgetvar("name"), true) v.set(0) self.assertEqual(self.root.globalgetvar("name"), false) v.set("on") self.assertEqual(self.root.globalgetvar("name"), true)
class ViewRenderedGrid(ViewWinGrid.ViewGrid): def __init__(self, modelXbrl, tabWin, lang): super(ViewRenderedGrid, self).__init__(modelXbrl, tabWin, "Rendering", True, lang) self.newFactItemOptions = ModelInstanceObject.NewFactItemOptions(xbrlInstance=modelXbrl) self.factPrototypes = [] self.zOrdinateChoices = None # context menu Boolean vars self.options = self.modelXbrl.modelManager.cntlr.config.setdefault("viewRenderedGridOptions", {}) self.ignoreDimValidity = BooleanVar(value=self.options.setdefault("ignoreDimValidity",True)) self.xAxisChildrenFirst = BooleanVar(value=self.options.setdefault("xAxisChildrenFirst",True)) self.yAxisChildrenFirst = BooleanVar(value=self.options.setdefault("yAxisChildrenFirst",False)) def close(self): super(ViewRenderedGrid, self).close() if self.modelXbrl: for fp in self.factPrototypes: fp.clear() self.factPrototypes = None def loadTablesMenu(self): tblMenuEntries = {} tblRelSet = self.modelXbrl.relationshipSet("Table-rendering") for tblLinkroleUri in tblRelSet.linkRoleUris: for tableAxisArcrole in (XbrlConst.euTableAxis, XbrlConst.tableBreakdown, XbrlConst.tableBreakdown201301, XbrlConst.tableAxis2011): tblAxisRelSet = self.modelXbrl.relationshipSet(tableAxisArcrole, tblLinkroleUri) if tblAxisRelSet and len(tblAxisRelSet.modelRelationships) > 0: # table name modelRoleTypes = self.modelXbrl.roleTypes.get(tblLinkroleUri) if modelRoleTypes is not None and len(modelRoleTypes) > 0: roledefinition = modelRoleTypes[0].definition if roledefinition is None or roledefinition == "": roledefinition = os.path.basename(tblLinkroleUri) for table in tblAxisRelSet.rootConcepts: # add table to menu if there's any entry tblMenuEntries[roledefinition] = tblLinkroleUri break self.tablesMenu.delete(0, self.tablesMenuLength) self.tablesMenuLength = 0 self.tblELR = None for tblMenuEntry in sorted(tblMenuEntries.items()): tbl,elr = tblMenuEntry self.tablesMenu.add_command(label=tbl, command=lambda e=elr: self.view(viewTblELR=e)) self.tablesMenuLength += 1 if self.tblELR is None: self.tblELR = elr # start viewing first ELR def viewReloadDueToMenuAction(self, *args): if not self.blockMenuEvents: # update config (config saved when exiting) self.options["ignoreDimValidity"] = self.ignoreDimValidity.get() self.options["xAxisChildrenFirst"] = self.xAxisChildrenFirst.get() self.options["yAxisChildrenFirst"] = self.yAxisChildrenFirst.get() self.view() def view(self, viewTblELR=None, newInstance=None): startedAt = time.time() self.blockMenuEvents += 1 if newInstance is not None: self.modelXbrl = newInstance # a save operation has created a new instance to use subsequently clearZchoices = False if viewTblELR: # specific table selection self.tblELR = viewTblELR clearZchoices = True else: # first or subsequenct reloading (language, dimensions, other change) clearZchoices = self.zOrdinateChoices is None if clearZchoices: # also need first time initialization self.loadTablesMenu() # load menus (and initialize if first time viewTblELR = self.tblELR if not self.tblELR: return # no table to display if clearZchoices: self.zOrdinateChoices = {} # remove old widgets self.viewFrame.clearGrid() tblAxisRelSet, xTopStructuralNode, yTopStructuralNode, zTopStructuralNode = resolveAxesStructure(self, viewTblELR) if tblAxisRelSet: #print("tbl hdr width rowHdrCols {0}".format(self.rowHdrColWidth)) self.gridTblHdr.tblHdrWraplength = 200 # to adjust dynamically during configure callbacks self.gridTblHdr.tblHdrLabel = \ gridHdr(self.gridTblHdr, 0, 0, (self.modelTable.genLabel(lang=self.lang, strip=True) or # use table label, if any self.roledefinition), anchor="nw", #columnspan=(self.dataFirstCol - 1), #rowspan=(self.dataFirstRow), wraplength=200) # in screen units #wraplength=sum(self.rowHdrColWidth)) # in screen units zAspects = defaultdict(set) self.zAxis(1, zTopStructuralNode, zAspects, clearZchoices) xStructuralNodes = [] self.xAxis(self.dataFirstCol, self.colHdrTopRow, self.colHdrTopRow + self.colHdrRows - 1, xTopStructuralNode, xStructuralNodes, self.xAxisChildrenFirst.get(), True, True) self.yAxis(1, self.dataFirstRow, yTopStructuralNode, self.yAxisChildrenFirst.get(), True, True) for fp in self.factPrototypes: # dereference prior facts if fp is not None: fp.clear() self.factPrototypes = [] self.bodyCells(self.dataFirstRow, yTopStructuralNode, xStructuralNodes, zAspects, self.yAxisChildrenFirst.get()) # data cells #print("body cells done") self.modelXbrl.profileStat("viewTable_" + os.path.basename(viewTblELR), time.time() - startedAt) #self.gridView.config(scrollregion=self.gridView.bbox(constants.ALL)) self.blockMenuEvents -= 1 def zAxis(self, row, zStructuralNode, zAspects, clearZchoices): if zStructuralNode is not None: gridBorder(self.gridColHdr, self.dataFirstCol, row, TOPBORDER, columnspan=2) gridBorder(self.gridColHdr, self.dataFirstCol, row, LEFTBORDER) gridBorder(self.gridColHdr, self.dataFirstCol, row, RIGHTBORDER, columnspan=2) label = zStructuralNode.header(lang=self.lang) hdr = gridHdr(self.gridColHdr, self.dataFirstCol, row, label, anchor="w", columnspan=2, wraplength=200, # in screen units objectId=zStructuralNode.objectId(), onClick=self.onClick) if zStructuralNode.choiceStructuralNodes: # combo box valueHeaders = [''.ljust(zChoiceStructuralNode.indent * 4) + # indent if nested choices (zChoiceStructuralNode.header(lang=self.lang) or '') for zChoiceStructuralNode in zStructuralNode.choiceStructuralNodes] combobox = gridCombobox( self.gridColHdr, self.dataFirstCol + 2, row, values=valueHeaders, selectindex=zStructuralNode.choiceNodeIndex, columnspan=2, comboboxselected=self.onComboBoxSelected) combobox.zStructuralNode = zStructuralNode combobox.zChoiceOrdIndex = row - 1 combobox.objectId = hdr.objectId = zStructuralNode.objectId() gridBorder(self.gridColHdr, self.dataFirstCol + 3, row, RIGHTBORDER) if zStructuralNode.childStructuralNodes: for zStructuralNode in zStructuralNode.childStructuralNodes: self.zAxis(row + 1, zStructuralNode, zAspects, clearZchoices) else: # nested-nost element, aspects process inheritance for aspect in aspectModels[self.aspectModel]: for ruleAspect in aspectRuleAspects.get(aspect, (aspect,)): if zStructuralNode.hasAspect(ruleAspect): #implies inheriting from other z axes if ruleAspect == Aspect.DIMENSIONS: for dim in (zStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList): zAspects[dim].add(zStructuralNode) else: zAspects[ruleAspect].add(zStructuralNode) def onComboBoxSelected(self, *args): combobox = args[0].widget self.zOrdinateChoices[combobox.zStructuralNode._definitionNode] = \ combobox.zStructuralNode.choiceNodeIndex = combobox.valueIndex self.view() # redraw grid def xAxis(self, leftCol, topRow, rowBelow, xParentStructuralNode, xStructuralNodes, childrenFirst, renderNow, atTop): if xParentStructuralNode is not None: parentRow = rowBelow noDescendants = True rightCol = leftCol widthToSpanParent = 0 sideBorder = not xStructuralNodes if atTop and sideBorder and childrenFirst: gridBorder(self.gridColHdr, self.dataFirstCol, 1, LEFTBORDER, rowspan=self.dataFirstRow) for xStructuralNode in xParentStructuralNode.childStructuralNodes: if not xStructuralNode.isRollUp: noDescendants = False rightCol, row, width, leafNode = self.xAxis(leftCol, topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, # nested items before totals childrenFirst, childrenFirst, False) if row - 1 < parentRow: parentRow = row - 1 #if not leafNode: # rightCol -= 1 nonAbstract = not xStructuralNode.isAbstract if nonAbstract: width += 100 # width for this label, in screen units widthToSpanParent += width label = xStructuralNode.header(lang=self.lang, returnGenLabel=isinstance(xStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))) if childrenFirst: thisCol = rightCol sideBorder = RIGHTBORDER else: thisCol = leftCol sideBorder = LEFTBORDER if renderNow: columnspan = (rightCol - leftCol + (1 if nonAbstract else 0)) gridBorder(self.gridColHdr, leftCol, topRow, TOPBORDER, columnspan=columnspan) gridBorder(self.gridColHdr, leftCol, topRow, sideBorder, columnspan=columnspan, rowspan=(rowBelow - topRow + 1) ) gridHdr(self.gridColHdr, leftCol, topRow, label if label else " ", anchor="center", columnspan=(rightCol - leftCol + (1 if nonAbstract else 0)), rowspan=(row - topRow + 1) if leafNode else 1, wraplength=width, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) if nonAbstract: for i, role in enumerate(self.colHdrNonStdRoles): gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, xStructuralNode.header(role=role, lang=self.lang), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) ''' was if self.colHdrDocRow: gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, xStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) if self.colHdrCodeRow: gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - 1, xStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code"), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) ''' gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, BOTTOMBORDER) xStructuralNodes.append(xStructuralNode) if nonAbstract: rightCol += 1 if renderNow and not childrenFirst: self.xAxis(leftCol + (1 if nonAbstract else 0), topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, childrenFirst, True, False) # render on this pass leftCol = rightCol if atTop and sideBorder and not childrenFirst: gridBorder(self.gridColHdr, rightCol - 1, 1, RIGHTBORDER, rowspan=self.dataFirstRow) return (rightCol, parentRow, widthToSpanParent, noDescendants) def yAxis(self, leftCol, row, yParentStructuralNode, childrenFirst, renderNow, atLeft): if yParentStructuralNode is not None: nestedBottomRow = row if atLeft: gridBorder(self.gridRowHdr, self.rowHdrCols + len(self.rowHdrNonStdRoles), # was: self.rowHdrDocCol + self.rowHdrCodeCol, self.dataFirstRow, RIGHTBORDER, rowspan=self.dataRows) gridBorder(self.gridRowHdr, 1, self.dataFirstRow + self.dataRows - 1, BOTTOMBORDER, columnspan=(self.rowHdrCols + len(self.rowHdrNonStdRoles))) # was: self.rowHdrDocCol + self.rowHdrCodeCol)) for yStructuralNode in yParentStructuralNode.childStructuralNodes: if not yStructuralNode.isRollUp: nestRow, nextRow = self.yAxis(leftCol + 1, row, yStructuralNode, # nested items before totals childrenFirst, childrenFirst, False) isAbstract = (yStructuralNode.isAbstract or (yStructuralNode.childStructuralNodes and not isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord)))) isNonAbstract = not isAbstract label = yStructuralNode.header(lang=self.lang, returnGenLabel=isinstance(yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))) topRow = row if childrenFirst and isNonAbstract: row = nextRow if renderNow: columnspan = self.rowHdrCols - leftCol + 1 if isNonAbstract or nextRow == row else None gridBorder(self.gridRowHdr, leftCol, topRow, LEFTBORDER, rowspan=(nestRow - topRow + 1) ) gridBorder(self.gridRowHdr, leftCol, topRow, TOPBORDER, columnspan=(1 if childrenFirst and nextRow > row else columnspan)) if childrenFirst and row > topRow: gridBorder(self.gridRowHdr, leftCol + 1, row, TOPBORDER, columnspan=(self.rowHdrCols - leftCol)) depth = yStructuralNode.depth gridHdr(self.gridRowHdr, leftCol, row, label if label is not None else " ", anchor=("w" if isNonAbstract or nestRow == row else "center"), columnspan=columnspan, rowspan=(nestRow - row if isAbstract else None), # wraplength is in screen units wraplength=(self.rowHdrColWidth[depth] if isAbstract else self.rowHdrWrapLength - sum(self.rowHdrColWidth[0:depth])), #minwidth=self.rowHdrColWidth[leftCol], minwidth=(16 if isNonAbstract and nextRow > topRow else None), objectId=yStructuralNode.objectId(), onClick=self.onClick) if isNonAbstract: for i, role in enumerate(self.rowHdrNonStdRoles): isCode = "code" in role docCol = self.dataFirstCol - len(self.rowHdrNonStdRoles) + i gridBorder(self.gridRowHdr, docCol, row, TOPBORDER) gridBorder(self.gridRowHdr, docCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, docCol, row, yStructuralNode.header(role=role, lang=self.lang), anchor="c" if isCode else "w", wraplength=40 if isCode else 100, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) ''' was: if self.rowHdrDocCol: docCol = self.dataFirstCol - 1 - self.rowHdrCodeCol gridBorder(self.gridRowHdr, docCol, row, TOPBORDER) gridBorder(self.gridRowHdr, docCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, docCol, row, yStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang), anchor="w", wraplength=100, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) if self.rowHdrCodeCol: codeCol = self.dataFirstCol - 1 gridBorder(self.gridRowHdr, codeCol, row, TOPBORDER) gridBorder(self.gridRowHdr, codeCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, codeCol, row, yStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code"), anchor="center", wraplength=40, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) # gridBorder(self.gridRowHdr, leftCol, self.dataFirstRow - 1, BOTTOMBORDER) ''' if isNonAbstract: row += 1 elif childrenFirst: row = nextRow if nestRow > nestedBottomRow: nestedBottomRow = nestRow + (isNonAbstract and not childrenFirst) if row > nestedBottomRow: nestedBottomRow = row #if renderNow and not childrenFirst: # dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, True, False) # render on this pass if not childrenFirst: dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, renderNow, False) # render on this pass return (nestedBottomRow, row) def bodyCells(self, row, yParentStructuralNode, xStructuralNodes, zAspects, yChildrenFirst): if yParentStructuralNode is not None: rendrCntx = getattr(self.modelXbrl, "rendrCntx", None) # none for EU 2010 tables dimDefaults = self.modelXbrl.qnameDimensionDefaults for yStructuralNode in yParentStructuralNode.childStructuralNodes: if yChildrenFirst: row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspects, yChildrenFirst) if not yStructuralNode.isAbstract: yAspects = defaultdict(set) for aspect in aspectModels[self.aspectModel]: for ruleAspect in aspectRuleAspects.get(aspect, (aspect,)): if yStructuralNode.hasAspect(ruleAspect): if ruleAspect == Aspect.DIMENSIONS: for dim in (yStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList): yAspects[dim].add(yStructuralNode) else: yAspects[ruleAspect].add(yStructuralNode) gridSpacer(self.gridBody, self.dataFirstCol, row, LEFTBORDER) # data for columns of row ignoreDimValidity = self.ignoreDimValidity.get() for i, xStructuralNode in enumerate(xStructuralNodes): xAspects = defaultdict(set) for aspect in aspectModels[self.aspectModel]: for ruleAspect in aspectRuleAspects.get(aspect, (aspect,)): if xStructuralNode.hasAspect(ruleAspect): if ruleAspect == Aspect.DIMENSIONS: for dim in (xStructuralNode.aspectValue(Aspect.DIMENSIONS) or emptyList): xAspects[dim].add(xStructuralNode) else: xAspects[ruleAspect].add(xStructuralNode) cellAspectValues = {} matchableAspects = set() for aspect in _DICT_SET(xAspects.keys()) | _DICT_SET(yAspects.keys()) | _DICT_SET(zAspects.keys()): aspectValue = inheritedAspectValue(self, aspect, xAspects, yAspects, zAspects, xStructuralNode, yStructuralNode) if dimDefaults.get(aspect) != aspectValue: # don't include defaulted dimensions cellAspectValues[aspect] = aspectValue matchableAspects.add(aspectModelAspect.get(aspect,aspect)) #filterable aspect from rule aspect cellDefaultedDims = _DICT_SET(dimDefaults) - _DICT_SET(cellAspectValues.keys()) priItemQname = cellAspectValues.get(Aspect.CONCEPT) concept = self.modelXbrl.qnameConcepts.get(priItemQname) conceptNotAbstract = concept is None or not concept.isAbstract from arelle.ValidateXbrlDimensions import isFactDimensionallyValid value = None objectId = None justify = None fp = FactPrototype(self, cellAspectValues) if conceptNotAbstract: # reduce set of matchable facts to those with pri item qname and have dimension aspects facts = self.modelXbrl.factsByQname[priItemQname] if priItemQname else self.modelXbrl.factsInInstance for aspect in matchableAspects: # trim down facts with explicit dimensions match or just present if isinstance(aspect, QName): aspectValue = cellAspectValues.get(aspect, None) if isinstance(aspectValue, ModelDimensionValue): if aspectValue.isExplicit: dimMemQname = aspectValue.memberQname # match facts with this explicit value else: dimMemQname = None # match facts that report this dimension elif isinstance(aspectValue, QName): dimMemQname = aspectValue # match facts that have this explicit value else: dimMemQname = None # match facts that report this dimension facts = facts & self.modelXbrl.factsByDimMemQname(aspect, dimMemQname) for fact in facts: if (all(aspectMatches(rendrCntx, fact, fp, aspect) for aspect in matchableAspects) and all(fact.context.dimMemberQname(dim,includeDefaults=True) in (dimDefaults[dim], None) for dim in cellDefaultedDims)): if yStructuralNode.hasValueExpression(xStructuralNode): value = yStructuralNode.evalValueExpression(fact, xStructuralNode) else: value = fact.effectiveValue objectId = fact.objectId() justify = "right" if fact.isNumeric else "left" break if (conceptNotAbstract and (value is not None or ignoreDimValidity or isFactDimensionallyValid(self, fp))): if objectId is None: objectId = "f{0}".format(len(self.factPrototypes)) self.factPrototypes.append(fp) # for property views gridCell(self.gridBody, self.dataFirstCol + i, row, value, justify=justify, width=12, # width is in characters, not screen units objectId=objectId, onClick=self.onClick) else: fp.clear() # dereference gridSpacer(self.gridBody, self.dataFirstCol + i, row, CENTERCELL) gridSpacer(self.gridBody, self.dataFirstCol + i, row, RIGHTBORDER) gridSpacer(self.gridBody, self.dataFirstCol + i, row, BOTTOMBORDER) row += 1 if not yChildrenFirst: row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspects, yChildrenFirst) return row def onClick(self, event): objId = event.widget.objectId if objId and objId[0] == "f": viewableObject = self.factPrototypes[int(objId[1:])] else: viewableObject = objId self.modelXbrl.viewModelObject(viewableObject) self.modelXbrl.modelManager.cntlr.currentView = self def cellEnter(self, *args): self.blockSelectEvent = 0 self.modelXbrl.modelManager.cntlr.currentView = self def cellLeave(self, *args): self.blockSelectEvent = 1 def cellSelect(self, *args): if self.blockSelectEvent == 0 and self.blockViewModelObject == 0: self.blockViewModelObject += 1 #self.modelXbrl.viewModelObject(self.nodeToObjectId[self.treeView.selection()[0]]) #self.modelXbrl.viewModelObject(self.treeView.selection()[0]) self.blockViewModelObject -= 1 def viewModelObject(self, modelObject): if self.blockViewModelObject == 0: self.blockViewModelObject += 1 ''' try: if isinstance(modelObject, ModelObject.ModelRelationship): conceptId = modelObject.toModelObject.objectId() elif isinstance(modelObject, ModelObject.ModelFact): conceptId = self.modelXbrl.qnameConcepts[modelObject.qname].objectId() else: conceptId = modelObject.objectId() #node = self.objectIdToNode[conceptId] node = conceptId if self.treeView.exists(node): self.treeView.see(node) self.treeView.selection_set(node) except KeyError: self.treeView.selection_set(()) ''' self.blockViewModelObject -= 1 def saveInstance(self, newFilename=None): if (not self.newFactItemOptions.entityIdentScheme or # not initialized yet not self.newFactItemOptions.entityIdentValue or not self.newFactItemOptions.startDateDate or not self.newFactItemOptions.endDateDate): if not getNewFactItemOptions(self.modelXbrl.modelManager.cntlr, self.newFactItemOptions): return # new instance not set # newFilename = None # only used when a new instance must be created if self.modelXbrl.modelDocument.type != ModelDocument.Type.INSTANCE and newFilename is None: newFilename = self.modelXbrl.modelManager.cntlr.fileSave(view=self, fileType="xbrl") if not newFilename: return # saving cancelled # continue saving in background thread = threading.Thread(target=lambda: self.backgroundSaveInstance(newFilename)) thread.daemon = True thread.start() def backgroundSaveInstance(self, newFilename=None): cntlr = self.modelXbrl.modelManager.cntlr if newFilename and self.modelXbrl.modelDocument.type != ModelDocument.Type.INSTANCE: self.modelXbrl.modelManager.showStatus(_("creating new instance {0}").format(os.path.basename(newFilename))) self.modelXbrl.modelManager.cntlr.waitForUiThreadQueue() # force status update self.modelXbrl.createInstance(newFilename) # creates an instance as this modelXbrl's entrypoing instance = self.modelXbrl cntlr.showStatus(_("Saving {0}").format(instance.modelDocument.basename)) cntlr.waitForUiThreadQueue() # force status update newCntx = ModelXbrl.AUTO_LOCATE_ELEMENT newUnit = ModelXbrl.AUTO_LOCATE_ELEMENT # check user keyed changes for bodyCell in self.gridBody.winfo_children(): if isinstance(bodyCell, gridCell) and bodyCell.isChanged: value = bodyCell.value objId = bodyCell.objectId if objId: if objId[0] == "f": factPrototypeIndex = int(objId[1:]) factPrototype = self.factPrototypes[factPrototypeIndex] concept = factPrototype.concept entityIdentScheme = self.newFactItemOptions.entityIdentScheme entityIdentValue = self.newFactItemOptions.entityIdentValue periodType = factPrototype.concept.periodType periodStart = self.newFactItemOptions.startDateDate if periodType == "duration" else None periodEndInstant = self.newFactItemOptions.endDateDate qnameDims = factPrototype.context.qnameDims prevCntx = instance.matchContext( entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, qnameDims, [], []) if prevCntx is not None: cntxId = prevCntx.id else: # need new context newCntx = instance.createContext(entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, concept.qname, qnameDims, [], [], afterSibling=newCntx) cntxId = newCntx.id # new context if concept.isNumeric: if concept.isMonetary: unitMeasure = qname(XbrlConst.iso4217, self.newFactItemOptions.monetaryUnit) unitMeasure.prefix = "iso4217" # want to save with a recommended prefix decimals = self.newFactItemOptions.monetaryDecimals elif concept.isShares: unitMeasure = XbrlConst.qnXbrliShares decimals = self.newFactItemOptions.nonMonetaryDecimals else: unitMeasure = XbrlConst.qnXbrliPure decimals = self.newFactItemOptions.nonMonetaryDecimals prevUnit = instance.matchUnit([unitMeasure],[]) if prevUnit is not None: unitId = prevUnit.id else: newUnit = instance.createUnit([unitMeasure],[], afterSibling=newUnit) unitId = newUnit.id attrs = [("contextRef", cntxId)] if concept.isNumeric: attrs.append(("unitRef", unitId)) attrs.append(("decimals", decimals)) value = Locale.atof(self.modelXbrl.locale, value, str.strip) newFact = instance.createFact(concept.qname, attributes=attrs, text=value) bodyCell.objectId = newFact.objectId() # switch cell to now use fact ID if self.factPrototypes[factPrototypeIndex] is not None: self.factPrototypes[factPrototypeIndex].clear() self.factPrototypes[factPrototypeIndex] = None #dereference fact prototype else: # instance fact, not prototype fact = self.modelXbrl.modelObject(objId) if fact.concept.isNumeric: value = Locale.atof(self.modelXbrl.locale, value, str.strip) if fact.value != value: if fact.concept.isNumeric and fact.isNil != (not value): fact.isNil = not value if value: # had been nil, now it needs decimals fact.decimals = (self.newFactItemOptions.monetaryDecimals if fact.concept.isMonetary else self.newFactItemOptions.nonMonetaryDecimals) fact.text = value XmlValidate.validate(instance, fact) bodyCell.isChanged = False # clear change flag instance.saveInstance(newFilename) # may override prior filename for instance from main menu cntlr.showStatus(_("Saved {0}").format(instance.modelDocument.basename), clearAfter=3000)
def queryContainers(): containers = [] bgC = "lavender" top = Tk() top.config(bg = bgC) L1 = Label(top, text="Please enter the containers to run on, and\nwhat day their current RVs are", bg = bgC, padx = 20) L1.config(font=("serif", 16)) L1.grid(row=0, column=0, sticky=constants.W+constants.E) S1=Scrollbar(top, orient='vertical') S1.grid(row=1, column=1, sticky=constants.N + constants.S) S2=Scrollbar(top, orient='horizontal') S2.grid(row=2, column=0, sticky=constants.E + constants.W) T1 = Text(top, height = 20, width = 97, xscrollcommand = S2.set, yscrollcommand=S1.set, wrap = constants.NONE) T1.grid(row=1, column=0) T1.insert("end", "ALL") f1 = Frame(top) f1.grid(row=4, column=0) checkHeadless = BooleanVar() checkHeadless.set(True) cb = Checkbutton(f1, text="Run in background?", variable=checkHeadless, bg="brown1", font=("serif", 12)) cb.grid(row=0, column=0, pady=(10,0), padx = 20) checkDelivery = BooleanVar() cb = Checkbutton(f1, text="Delivery RVs?", variable=checkDelivery, bg="brown1", font=("serif", 12)) cb.grid(row=0, column=1, pady=(10,0), padx = 20) checkallowSameDayAsETA = BooleanVar() cb = Checkbutton(f1, text="Try for RVs for the same\nday as ETA?", variable=checkallowSameDayAsETA, bg="brown1", font=("serif", 12)) cb.grid(row=0, column=2, pady=(10,0), padx = 20) checkMalport = BooleanVar() cb = Checkbutton(f1, text="Malport?", variable=checkMalport, bg="brown1", font=("serif", 12)) cb.grid(row=0, column=3, pady=(10,0), padx = 20) def callbackCont(): if date.get()=="": popUpOKLeft("Please select the day the current RV is on") else: if T1.get("1.0", constants.END).strip()=="": popUpOKLeft("Please list the target containers or RV #s (for deliveries)") else: containers.append(T1.get("1.0", constants.END).splitlines()) top.destroy() dates=[] daysForward = "" if datetime.now().weekday()<2: daysForward = 3 else: daysForward = 5 if (datetime.now().hour>7 and datetime.now().minute>46) or datetime.now().hour>8: daysForward+=1 for i in range(daysForward): dates.append(getDaysForward(i, True)) date=StringVar() f = Frame(top) f.grid(row=3, column=0) for dateStr in dates: Radiobutton(f, text=dateStr, variable=date, value=dateStr, indicatoron=0, bg="royal blue", font = ("serif", 16)).pack(side="left") MyButton = Button(top, text="OK", command=callbackCont) MyButton.grid(row=5, column=0, sticky=constants.W+constants.E, padx = 20, pady = 10) MyButton.config(font=("serif", 30), bg="green") top.update() w = top.winfo_width() # width for the Tk root h = top.winfo_height() # height for the Tk root ws = top.winfo_screenwidth() # width of the screen hs = top.winfo_screenheight() # height of the screen x = (ws/2) - (w/2) y = (hs/2) - (h/2) top.geometry('%dx%d+%d+%d' % (w, h, x, y)) top.update() top.lift() top.attributes('-topmost',True) top.after_idle(top.attributes,'-topmost',False) moveTo(MyButton.winfo_width()/2 + MyButton.winfo_rootx(), MyButton.winfo_height()/2 + MyButton.winfo_rooty()) top.mainloop() return containers[0], date.get(), checkHeadless.get(), checkDelivery.get(), checkallowSameDayAsETA.get(), checkMalport.get()
def BooleanVar(self, value): return BooleanVar(self.root, value=value)
def queryDatesAndTimes(allConts, malport): dates=[] returnDates = [] dateButtons = [] dateValues=[] returnTimes = [] timeButtons = [] timeValues=[] today = datetime.now() daysForward = "" if today.weekday()<2: daysForward = 3 else: daysForward = 5 for i in range(daysForward+1): thisDay = getDaysForward(i, True) if thisDay: dates.append(thisDay) bgC = "lavender" top = Tk() top.config(bg = bgC) L1 = Label(top, text="Please select the acceptable dates/times\nfor the new RVs\n(Hold shift to select all since last selection)", bg = bgC, padx = 20) L1.config(font=("serif", 16)) L1.grid(row=0, column=0, sticky=constants.W+constants.E, columnspan = 2) start = [0] i=1 def selectstart(start, chkbuttons, event): start[0]= chkbuttons.index(event.widget) def selectrange(start, chkbuttons, event): startLocal = start[0] end = chkbuttons.index(event.widget) sl = slice(min(startLocal, end)+1, max(startLocal, end)) for cb in chkbuttons[sl]: cb.toggle() start[0] = startLocal for date in dates: check = BooleanVar() checkButton = Checkbutton(top, text=date, variable=check, bg="royal blue", font=("serif", 12)) checkButton.grid(row=i, column=0, sticky=constants.W+constants.E, pady=0) # if malport: # checkButton.grid(columnspan=2) if i>1 and allConts: check.set(True) i+=1 checkButton.bind("<Button-1>", lambda event: selectstart(start, dateButtons, event)) checkButton.bind("<Shift-Button-1>", lambda event: selectrange(start, dateButtons, event)) dateButtons.append(checkButton) dateValues.append((check, date)) if not malport: time_Order = ["04", "05","06","07","08","09","10","11","12","13","14","16","18","19","20", "00"] else: # time_Order = ["06","11","14","16","18", "00"] # f=open(r"C:\Automation\CNPort.txt", 'r') time_Order=[] # f=open(r"J:\LOCAL DEPARTMENT\Automation - DO NOT MOVE\Malport Hours.txt", 'r') f=open(r"C:\Automation\Malport Hours.txt", 'r') # read = f.readline() # m = re.search("username: *", read) # username = read[m.end():].rstrip() read = f.readline() while read != "": if read == "\n": continue else: read = read.strip() if len(read)==1: read = "0"+read if len(read)==2: read+=":00" if len(read)==4 and not ":" in read: read=read[:2]+":"+read[2:] elif len(read)==4: read = "0"+read time_Order.append(read) read = f.readline() f.close() # time_Order = ["06","08","10","12","14","16","18","20", "00"] for i in range(len(time_Order)): check=BooleanVar() if len(time_Order[i])==2: cb = Checkbutton(text=time_Order[i]+":00",padx=0,pady=0,bd=0, variable=check, bg="dark violet", font=("serif", 12)) else: cb = Checkbutton(text=time_Order[i],padx=0,pady=0,bd=0, variable=check, bg="dark violet", font=("serif", 12)) cb.grid(row = i+1, column = 1, sticky=constants.W+constants.E+constants.N+constants.S) cb.bind("<Button-1>", lambda event: selectstart(start, timeButtons, event)) cb.bind("<Shift-Button-1>", lambda event: selectrange(start, timeButtons, event)) timeValues.append((check, time_Order[i])) timeButtons.append(cb) def callbackDates(): for button, date in dateValues: if button.get(): returnDates.append(date) if len(returnDates)<1: popUpOKLeft("Please select target dates for the new RV(s)") for button, time in timeValues: if button.get(): returnTimes.append(time) top.destroy() MyButton = Button(top, text="OK", command=callbackDates) MyButton.grid(row=i+2, column=0, sticky=constants.W+constants.E, padx = 20, pady = (0,20), columnspan = 2) MyButton.config(font=("serif", 30), bg="green") top.update() w = top.winfo_width() # width for the Tk root h = top.winfo_height() # height for the Tk root ws = top.winfo_screenwidth() # width of the screen hs = top.winfo_screenheight() # height of the screen x = (ws/2) - (w/2) y = (hs/2) - (h/2) top.geometry('%dx%d+%d+%d' % (w, h, x, y)) top.update() top.lift() top.attributes('-topmost',True) top.after_idle(top.attributes,'-topmost',False) if not malport: moveTo(MyButton.winfo_width()/2 + MyButton.winfo_rootx(), MyButton.winfo_height()/2 + MyButton.winfo_rooty()) top.mainloop() # if not malport: if len(returnTimes)<1: returnTimes = ["04", "05","06","07","08","09","10","11","12","13","14","16"] # else: # if len(returnTimes)<1: # returnTimes = ["06","08","10","12","14","16"] # else: # returnTimes = ["00"] return returnDates, returnTimes
def __init__(self): self.myio = None self.isContrastEnh = False window = Tk() window.title("Assist Tool") leftICO = PhotoImage(file="ICO/left.gif") rightICO = PhotoImage(file="ICO/right.gif") SaveICO = PhotoImage(file="ICO/Save.gif") self.inner_x = IntVar() self.inner_y = IntVar() self.inner_d = IntVar() self.outside_x = IntVar() self.outside_y = IntVar() self.outside_d = IntVar() self.currentfile = StringVar() self.variable_list = [ self.currentfile, self.inner_d, self.inner_x, self.inner_y, self.outside_d, self.outside_x, self.outside_y ] self.h = 480 self.w = 640 self.isInnerCircle = BooleanVar() self.isInnerCircle.set(True) frame_left = Frame(window) frame_left.grid(row=1, column=1) frame_right = Frame(window) frame_right.grid(row=1, column=2) frame_bottom = Frame(window) frame_bottom.grid(row=2, column=1) frame_right_1 = Frame(frame_right) frame_right_1.grid(row=1, column=1) frame_right_2 = Frame(frame_right) frame_right_2.grid(row=2, column=1) frame_right_3 = Frame(frame_right) frame_right_3.grid(row=3, column=1) frame_right_4 = Frame(frame_right) frame_right_4.grid(row=4, column=1) frame_right_5 = Frame(frame_right) frame_right_5.grid(row=5, column=1) #------------------banging--------- self.canvas = Canvas(frame_left) self.canvas["width"] = self.w self.canvas["height"] = self.h self.canvas.pack() self.canvas.bind('<Button-1>', self.Press) self.canvas.bind('<B1-Motion>', self.Draw) self.canvas.bind('<ButtonRelease-1>', self.Release) window.bind('<Key>', self.PressKey) #-------------show background picture----- self.currentfile.set("ICO/rabbit640480.jpg") self.showPicture("ICO/rabbit640480.jpg") #--------------show filename self.label_filename = Label(frame_bottom, textvariable=self.currentfile) self.label_filename.pack() #-------------control button Button(frame_right_2, image=leftICO, command=self.processLButton).pack(side=LEFT) Button(frame_right_2, image=rightICO, command=self.processRButton).pack(side=LEFT) #-------------show info of inner circle self.radio_innerCircle = Radiobutton(frame_right_3, text="Inner Circle", command=self.processChooseInner, variable=self.isInnerCircle, value=True) self.radio_innerCircle.grid(row=1, column=2) Label(frame_right_3, text="d").grid(row=2, column=1) self.inner_d.set(70) self.dr = 102 self.entry_inner_d = Entry(frame_right_3, textvariable=self.inner_d) self.entry_inner_d.grid(row=2, column=2) Label(frame_right_3, text="x").grid(row=3, column=1) self.entry_inner_x = Entry(frame_right_3, textvariable=self.inner_x) self.entry_inner_x.grid(row=3, column=2) Label(frame_right_3, text="y").grid(row=4, column=1) self.entry_inner_y = Entry(frame_right_3, textvariable=self.inner_y) self.entry_inner_y.grid(row=4, column=2) #------------show info of outside circle self.radio_outsideCircle = Radiobutton( frame_right_4, text="Outside Circle", command=self.processChooseOutside, variable=self.isInnerCircle, value=False) self.radio_outsideCircle.grid(row=1, column=2) Label(frame_right_4, text="d").grid(row=2, column=1) self.entry_outside_d = Entry(frame_right_4, textvariable=self.outside_d) self.entry_outside_d.grid(row=2, column=2) Label(frame_right_4, text="x").grid(row=3, column=1) self.entry_outside_x = Entry(frame_right_4, textvariable=self.outside_x) self.entry_outside_x.grid(row=3, column=2) Label(frame_right_4, text="y").grid(row=4, column=1) self.entry_outside_y = Entry(frame_right_4, textvariable=self.outside_y) self.entry_outside_y.grid(row=4, column=2) #-------------Save button self.radio_isContrastEnh = Checkbutton( frame_right_5, text="Contrast Enhance", command=self.ContrastEnh).pack() #self.radio_isContrastEnh.deselect() Button(frame_right_5, image=SaveICO, command=self.processSave).pack() #--------------menubar menubar = Menu(window) window.config(menu=menubar) openMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Open", menu=openMenu) openMenu.add_command(label="Folder", command=self.openFolder) openMenu.add_command(label="sqlite3 database", command=self.openDatabase) openMenu.add_command(label="csv file", command=self.openCsv) AlterMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Alter", menu=AlterMenu) AlterMenu.add_command(label="Alter db fName", command=self.AlterDBFName) outputMenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Output", menu=outputMenu) outputMenu.add_command(label="csv file", command=self.outputcsv) outputMenu.add_command(label="picture", command=self.outputpic) #-------------finally--------- self.radio_innerCircle.select() if os.path.exists('output_image') == False: os.mkdir('output_image') window.mainloop()
def __init__(self, data, header): self.win = Tk() self.win.title("USGS Current Earthquake Data") self.checked = BooleanVar() self.checked.trace("w", self.mark_checked) self.sortOption = StringVar() self.sortOption.set("1") self.sortOption.trace("w", self.mark_sortOption) # ----- Menu Bar - Create the Menu Bar ------------------------- menuBar = Menu() self.win.config(menu=menuBar) fileMenu = Menu(menuBar, tearoff=False) dataMenu = Menu(menuBar, tearoff=False) optionsMenu = Menu(menuBar, tearoff=False) helpMenu = Menu(menuBar, tearoff=False) menuBar.add_cascade(menu=fileMenu, label="File") menuBar.add_cascade(menu=dataMenu, label="Data") menuBar.add_cascade(menu=optionsMenu, label="Options") menuBar.add_cascade(menu=helpMenu, label="Help") # ----- Menu Bar - Create the File Menu ------------------------ fileMenu.add_separator() fileMenu.add_command(label="Exit", command=self._quit) # ----- Menu Bar - Create the Options Menu --------------------- sortSubMenu = Menu(optionsMenu, tearoff=False) optionsMenu.add_cascade(menu=sortSubMenu, label="Sort") sortSubMenu.add_radiobutton(label="Sort by Magnitude", value="1", variable=self.sortOption) sortSubMenu.add_radiobutton( label="Sort by Predictive damage or Shake(MMI)", value="2", variable=self.sortOption) # ----- Menu Bar - Create the Data Menu------------------------- dataMenu.add_command(label="Refresh current Data source", command=self._refreshData) dataMenu.add_separator() dataSubMenu = Menu(dataMenu, tearoff=False) dataMenu.add_cascade(menu=dataSubMenu, label="New Data Source") # ----- Menu Bar - Create the Data submenu --------------------- d1 = [ ["Significant", "significant"], ["Magnitude 4.5+", "4.5"], ["Magnitude 2.5+", "2.5"], ["Magnitude 1.0+", "1.0"], ["All Earthquakes+", "all"], ] d2 = [ ["hour", "hour"], ["day", "day"], ["7 days", "week"], ["30 days", "month"], ] for i in range(len(d2)): for j in range(len(d1)): s1 = str(d1[j][0] + ", past " + d2[i][0]) s2 = str(d1[j][1] + "_" + d2[i][1]) dataSubMenu.add_command( label=s1, command=lambda widget=s2: self.getNewData(widget)) if j == (len(d1) - 1) and i != (len(d2) - 1): dataSubMenu.add_separator() # ----- Set up frames and subframes to store widgets ----------- self.mainFrame = ttk.LabelFrame() self.headings_frame = ttk.LabelFrame(self.mainFrame) self.headings_frame.grid(row=0) self.selection_frame = ttk.LabelFrame(self.headings_frame, text="selection frame") self.selection_frame.configure(text=header["title"]) self.selection_frame.grid(column=0, columnspan=2, row=0, sticky="NW") self.file_frame = ttk.LabelFrame(self.headings_frame, text="File Info") self.file_frame.grid(column=2, row=0, rowspan=3, sticky="NW") self.details_frame = ttk.LabelFrame(self.mainFrame) self.details_frame.grid(row=1) self.summary_frame = ttk.LabelFrame(self.details_frame, text="Event Details") self.summary_frame.grid(row=0, columnspan=2) self.location_frame = ttk.LabelFrame(self.details_frame, text="Event Location") self.location_frame.grid(row=1, column=0, sticky="NW") self.time_frame = ttk.LabelFrame(self.details_frame, text="Time of Event") self.time_frame.grid(row=1, column=1, sticky="NW") ttk.Label(self.selection_frame).grid(column=0, row=0, sticky="W") # ----- Set up combo box and data to populate it --------------- self.summarySelected = ttk.Combobox(self.selection_frame, width=85, state="readonly") self.summarySelected.grid(column=0, row=1) self.updateComboBoxData(data) # ----- Add File widget - File delta --------------------------- self.fileDelta = StringVar() fileDeltaEntry = ttk.Label(self.file_frame, width=25, textvariable=self.fileDelta, state="readonly") fileDeltaEntry.grid(column=1, row=0, columnspan=2, sticky="W") # ----- Add File widget - File Time ---------------------------- ttk.Label(self.file_frame, text="File Time:").grid(column=0, row=1, sticky="E") self.fileTime = StringVar() fileTimeEntry = ttk.Label(self.file_frame, width=25, textvariable=self.fileTime, state="readonly") fileTimeEntry.grid(column=1, row=1, sticky="W") # ----- Add File widget - Event count -------------------------- ttk.Label(self.file_frame, text="Count:").grid(column=0, row=2, sticky="E") self.fileCount = StringVar() fileCountEntry = ttk.Label(self.file_frame, width=25, textvariable=self.fileCount, state="readonly") fileCountEntry.grid(column=1, row=2, sticky="W") # ----- Add Summary widget - Magnitude ------------------------- ttk.Label(self.summary_frame, text="Magnitude:").grid(column=0, row=0, sticky="E") self.mag = StringVar() magEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.mag, state="readonly") magEntry.grid(column=1, row=0, sticky="W") # ----- Add Summary widget - Alert ----------------------------- ttk.Label(self.summary_frame, text="Alert:").grid(column=2, row=0, sticky="E") self.alert = StringVar() alertEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.alert, state="readonly") alertEntry.grid(column=3, row=0, sticky="W") # ----- Add Summary widget - Shake ----------------------------- ttk.Label(self.summary_frame, text="Shake (MMI):").grid(column=4, row=0, sticky="E") self.shake = StringVar() shakeEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.shake, state="readonly") shakeEntry.grid(column=5, row=0, sticky="W") # ----- Add Summary widget - Report Felt ----------------------- ttk.Label(self.summary_frame, text="Reported felt:").grid(column=6, row=0, sticky="E") self.felt = StringVar() feltEntry = ttk.Label(self.summary_frame, width=7, textvariable=self.felt, state="readonly") feltEntry.grid(column=7, row=0, sticky="W") # ----- Add Summary widget - Url/More Info --------------------- ttk.Label(self.summary_frame, text="More info:").grid(column=0, row=1, sticky="E") self.urlName = StringVar() self.urlEntry = ttk.Button(self.summary_frame) self.urlEntry.grid(column=1, row=1, columnspan=8, sticky="W") # ----- Add Location widget - Place ---------------------------- ttk.Label(self.location_frame, text="Place:").grid(column=0, row=4, sticky="E") self.place = StringVar() locEntry = ttk.Label(self.location_frame, width=45, textvariable=self.place, state="readonly") locEntry.grid(column=1, row=4, sticky="W") # ----- Add Location widget - Latitude ------------------------- ttk.Label(self.location_frame, text="Latitude:").grid(column=0, row=10, sticky="E") self.lat = StringVar() latEntry = ttk.Label(self.location_frame, width=25, textvariable=self.lat, state="readonly") latEntry.grid(column=1, row=10, sticky="W") # ----- Add Location widget - Longitude ------------------------ ttk.Label(self.location_frame, text="Longitude:").grid(column=0, row=11, sticky="E") self.lon = StringVar() longEntry = ttk.Label(self.location_frame, width=25, textvariable=self.lon, state="readonly") longEntry.grid(column=1, row=11, sticky="W") # ----- Add Location widget - Depth ---------------------------- ttk.Label(self.location_frame, text="Depth:").grid(column=0, row=12, sticky="E") self.depth = StringVar() depthEntry = ttk.Label(self.location_frame, width=25, textvariable=self.depth, state="readonly") depthEntry.grid(column=1, row=12, sticky="W") # ----- Add Time widget - Event delta -------------------------- self.deltaEntry = StringVar() deltaEntry = ttk.Label(self.time_frame, width=25, textvariable=self.deltaEntry, state="readonly") deltaEntry.grid(column=1, row=0, sticky="W") # ----- Add Time widget - Event Time --------------------------- ttk.Label(self.time_frame, text="Time:").grid(column=0, row=1, sticky="E") self.time = StringVar() timeEntry = ttk.Label(self.time_frame, width=25, textvariable=self.time, state="readonly") timeEntry.grid(column=1, row=1, sticky="W") # ----- Add Time widget - Event Local Time --------------------- ttk.Label(self.time_frame, text="Your local time:").grid(column=0, row=2, sticky="E") self.tz = StringVar() tzEntry = ttk.Label(self.time_frame, width=25, textvariable=self.tz, state="readonly") tzEntry.grid(column=1, row=2, sticky="W") # ----- Add padding around fields self.mainFrame.grid_configure(padx=8, pady=4) for child in self.mainFrame.winfo_children(): child.grid_configure(padx=8, pady=4) for grandChild in child.winfo_children(): grandChild.grid_configure(padx=8, pady=4) for widget in grandChild.winfo_children(): widget.grid_configure(padx=8, pady=4) # ----- Call funtion to update fields -------------------------- data = self.sortData(data) self.updateHeaderFields(header) self.updateFields(data, self.summarySelected.current())
def __init__(self, screenName=None, baseName=None, useTk=1, sync=0, use=None): super().__init__(screenName=screenName, baseName=baseName, useTk=useTk, sync=sync, use=use) ####################################################################### # Attributes ---------------------------------------------------------- self.age = ['User', 'User'] self.sex = ['User', 'User'] self.height = ['User', 'User'] self.weight = ['User', 'User'] self.is_streaming = False self.is_displaying = False self.frame_count = 0 self.time_stamp_tmp = 0 self.depth_frame_tmp = 0 self.rgb_frame_tmp = 0 self.activity = StringVar() self.activity1 = StringVar() self.sensor_ignore = BooleanVar() self.buffer_ignore = BooleanVar() self.debug_mode = BooleanVar() # Clients self.kinect_client = PahoMqtt(BROKER, "KINECT", c_msg="kinect") self.kinect_client.loop_start() self.sound_client = PahoMqtt(BROKER, "SOUND", c_msg="sound") self.sound_client.loop_start() self.clients = list() dis = 0 for i, item in enumerate(SENSORS): if item[2]: self.clients.append( PahoMqtt(BROKER, f"{item[1]}", c_msg=item[0])) self.clients[i - dis].subscribe(item[0]) self.clients[i - dis].loop_start() else: dis += 1 # Attributes ---------------------------------------------------------- ####################################################################### # Tk widgets ---------------------------------------------------------- self.title("Control") self.resizable(0, 0) self.configure(bg='white') # Sensor Frame 1 self.sensor_frame1 = LabelFrame(self, text="Sensor control", background='white') self.sensor_frame1.pack(side=LEFT, fill="y") self.sensor_state = list() for item in self.clients: self.sensor_state.append( Label(self.sensor_frame1, text=f"SENSOR {item.info}", background='white', font=("default", 15, 'bold'))) self.sensor_state[-1].grid(row=len(self.sensor_state), column=0) self.start_btn = ttk.Button(self.sensor_frame1, text="Refresh", command=self.refresh) self.start_btn.grid(row=len(self.clients) + 1, column=0) # Stream Frame 2 self.sensor_frame2 = LabelFrame(self, text="Person 1", background='white') self.sensor_frame2.pack(side=LEFT, fill="y") self.user_age = Label(self.sensor_frame2, text="Age", background='white', font=("default", 10, 'bold')) self.user_age.grid(row=0, column=0) self.age_label = Label(self.sensor_frame2, text=self.age[0], background='white', font=("default", 10, 'bold')) self.age_label.grid(row=0, column=1) self.user_sex = Label(self.sensor_frame2, text="Sex", background='white', font=("default", 10, 'bold')) self.user_sex.grid(row=1, column=0) self.sex_label = Label(self.sensor_frame2, text=self.sex[0], background='white', font=("default", 10, 'bold')) self.sex_label.grid(row=1, column=1) self.user_height = Label(self.sensor_frame2, text="Height", background='white', font=("default", 10, 'bold')) self.user_height.grid(row=2, column=0) self.height_label = Label(self.sensor_frame2, text=self.height[0], background='white', font=("default", 10, 'bold')) self.height_label.grid(row=2, column=1) self.user_weight = Label(self.sensor_frame2, text="Weight", background='white', font=("default", 10, 'bold')) self.user_weight.grid(row=3, column=0) self.weight_label = Label(self.sensor_frame2, text=self.weight[0], background='white', font=("default", 10, 'bold')) self.weight_label.grid(row=3, column=1) self.activity_menu = ttk.Combobox(self.sensor_frame2, value=ACTIVITIES, textvariable=self.activity) self.activity_menu.current(0) self.activity_menu.config(state="readonly", width=15) self.activity_menu.bind("<<ComboboxSelected>>") self.activity_menu.grid(row=4, column=0, columnspan=2, pady=5) self.stream_start_btn = ttk.Button(self.sensor_frame2, text="Stream start", command=self.stream_start, width=11) self.stream_start_btn.grid(row=5, column=0, padx=2, pady=2) self.stream_stop_btn = ttk.Button(self.sensor_frame2, text="Stream stop", command=self.stream_stop, width=11) self.stream_stop_btn["state"] = DISABLED self.stream_stop_btn.grid(row=5, column=1, padx=2, pady=2) self.stream_reset_btn = ttk.Button( self.sensor_frame2, text="Stream reset", command=lambda: self.stream_reset(delete=True), width=11) self.stream_reset_btn["state"] = DISABLED self.stream_reset_btn.grid(row=7, column=1, padx=2, pady=2) self.stream_save_btn = ttk.Button(self.sensor_frame2, text="Stream save", command=self.stream_save, width=11) self.stream_save_btn["state"] = DISABLED self.stream_save_btn.grid(row=7, column=0, padx=2, pady=2) self.act_start_btn = ttk.Button(self.sensor_frame2, text="Activity start", command=lambda: self.activity_start(0), width=11) self.act_start_btn["state"] = DISABLED self.act_start_btn.grid(row=6, column=0, padx=2, pady=5) self.act_end_btn = ttk.Button(self.sensor_frame2, text="Activity end", command=lambda: self.activity_end(0), width=11) self.act_end_btn["state"] = DISABLED self.act_end_btn.grid(row=6, column=1, padx=2, pady=5) ################################################################################### # Stream Frame 3 self.sensor_frame3 = LabelFrame(self, text="Person 2", background='white') self.sensor_frame3.pack(side=LEFT, fill="y") self.user1_age = Label(self.sensor_frame3, text="Age", background='white', font=("default", 10, 'bold')) self.user1_age.grid(row=0, column=0) self.age1_label = Label(self.sensor_frame3, text=self.age[1], background='white', font=("default", 10, 'bold')) self.age1_label.grid(row=0, column=1) self.user1_sex = Label(self.sensor_frame3, text="Sex", background='white', font=("default", 10, 'bold')) self.user1_sex.grid(row=1, column=0) self.sex1_label = Label(self.sensor_frame3, text=self.sex[1], background='white', font=("default", 10, 'bold')) self.sex1_label.grid(row=1, column=1) self.user1_height = Label(self.sensor_frame3, text="Height", background='white', font=("default", 10, 'bold')) self.user1_height.grid(row=2, column=0) self.height1_label = Label(self.sensor_frame3, text=self.height[1], background='white', font=("default", 10, 'bold')) self.height1_label.grid(row=2, column=1) self.user1_weight = Label(self.sensor_frame3, text="Weight", background='white', font=("default", 10, 'bold')) self.user1_weight.grid(row=3, column=0) self.weight1_label = Label(self.sensor_frame3, text=self.weight[1], background='white', font=("default", 10, 'bold')) self.weight1_label.grid(row=3, column=1) self.activity1_menu = ttk.Combobox(self.sensor_frame3, value=ACTIVITIES1, textvariable=self.activity1) self.activity1_menu.current(0) self.activity1_menu.config(state="readonly", width=15) self.activity1_menu.bind("<<ComboboxSelected>>") self.activity1_menu.grid(row=4, column=0, columnspan=2, pady=5) self.act_start_btn1 = ttk.Button( self.sensor_frame3, text="Activity start", command=lambda: self.activity_start(1), width=11) self.act_start_btn1["state"] = DISABLED self.act_start_btn1.grid(row=5, column=0, padx=2, pady=5) self.act_end_btn1 = ttk.Button(self.sensor_frame3, text="Activity end", command=lambda: self.activity_end(1), width=11) self.act_end_btn1["state"] = DISABLED self.act_end_btn1.grid(row=5, column=1, padx=2, pady=5) ################################################################################### # Menu menubar = Menu(self) tool = Menu(menubar, tearoff=0) tool.add_command(label="Insert user info", command=self.user_info) tool.add_command(label="Display kinect", command=self.disp_kinect) tool.add_checkbutton(label="Ignore sensor error", onvalue=1, offvalue=0, variable=self.sensor_ignore) tool.add_checkbutton(label="Ignore buffer error", onvalue=1, offvalue=0, variable=self.buffer_ignore) tool.add_checkbutton(label="debug mode", onvalue=1, offvalue=0, variable=self.debug_mode) tool.add_command(label="Close sensors", command=self.close) menubar.add_cascade(label="Tools", menu=tool) self.config(menu=menubar) # Tk widgets ---------------------------------------------------------- ####################################################################### # Sensor controls ----------------------------------------------------- self.azure = PyK4A() self.azure.start() self.stream_reset() self.get_video() self.stream_video() self.stream_depth() self.set_state() self.refresh() # Main loop ----------------------------------------------------------- self.mainloop()
class MainGUI: def __init__(self): self.view_bool = False self.get_data(False) self.main_init() def main_init(self): self.gui_main() def main_refresh(self, all=False): self.get_data(all) if self.order_details == {}: self.listbox.delete(*self.listbox.get_children()) self.listbox.insert("", "end", text="--", values=("All orders cleared!", )) else: simple_details = [] for id in self.order_ids: string = "" for item in self.order_details.get(id): string += f"{item[1]} {item[0]}, " simple_details.append([ id, string[:40] + "..." if len(string) > 40 else string[:len(string) - 2] ]) self.listbox.delete(*self.listbox.get_children()) for simple_detail in simple_details: self.listbox.insert("", "end", text=simple_detail[0], values=(simple_detail[1], )) def gui_main(self): # Root Window Init self.window = ThemedTk(theme="radiance") self.window.geometry("435x340") self.window.title("Restaurant Management System") self.window.configure(background="#F6F4F2") self.window.resizable(0, 0) self.view_var = BooleanVar() # Heading ttk.Label(self.window, font=("default", 19, "bold"), text="Kitchen Manager").grid(row=0, column=0, sticky="w", padx=15) ttk.Separator(self.window, orient="horizontal").grid(row=1, columnspan=2, sticky="ew") # Tree View self.listbox = ttk.Treeview(self.window) self.listbox["columns"] = ("Details") self.listbox.heading("#0", text="Order No") self.listbox.heading("#1", text="Details") self.listbox.column("#0", minwidth=0, width=100) self.listbox.column("#1", minwidth=0, width=300) self.listbox.bind('<Double-1>', self.selectItem) ttk.Style().configure("Treeview", fieldbackground="#FEFEFE", background="#FEFEFE") self.main_refresh(self.view_bool) self.listbox.grid(row=2, column=0, sticky="nse", padx=15, pady=10) self.view_all = ttk.Checkbutton(self.window, text="View all orders", variable=self.view_var, command=self.cb).grid(row=3, column=0, sticky="w", padx=15) ttk.Button(self.window, text="Quit", command=self.window.destroy).grid(row=3, column=0, sticky="e", padx=15) self.window.mainloop() def cb(self): if self.view_var.get() == True: self.view_bool = True else: self.view_bool = False self.main_refresh(self.view_bool) def gui_details(self, id): # Open Details Window self.detail = ThemedTk(theme="radiance") self.detail.geometry("335x410") self.detail.title("Details") self.detail.configure(background="#F6F4F2") self.detail.resizable(0, 0) self.id = id # Heading ttk.Label(self.detail, font=("default", 19, "bold"), text="Orders").grid(row=0, column=0, sticky="w", padx=15) ttk.Separator(self.detail, orient="horizontal").grid(row=1, columnspan=2, sticky="ew", pady=(0, 5)) # Create Default Lables ttk.Label(self.detail, font=("default", 10, "bold"), anchor="e", width=18, text="Order ID : ").grid(row=2, column=0) ttk.Label(self.detail, font=("default", 10, "bold"), anchor="e", width=18, text="Customer Name : ").grid(row=3, column=0) # Create Buttons ttk.Button(self.detail, text="Mark Done", command=lambda: self.mark_done(self.id), width=33).grid(row=5, column=0, columnspan=2) ttk.Button( self.detail, text="Previous", command=lambda: self.refresh(self.detail, "prev", self.id)).grid( row=6, column=0, sticky="w", padx=15) ttk.Button( self.detail, text="Next", command=lambda: self.refresh(self.detail, "next", self.id)).grid( row=6, column=1, sticky="e", padx=15) self.tree = ttk.Treeview(self.detail) self.tree["columns"] = ("Quantity") self.tree.heading("#0", text="Name") self.tree.heading("#1", text="Quantity") self.tree.column("#0", minwidth=0, width=230) self.tree.column("#1", minwidth=0, width=70) def mark_done(self, id): conn = sqlite3.connect("login_db.db") query = f"UPDATE orders SET delivered=1 WHERE order_no={id};" conn.execute(query) conn.commit() self.detail.destroy() self.main_refresh(self.view_bool) def selectItem(self, a): curItem = self.listbox.focus() id = self.listbox.item(curItem).get("text") if id == "--": pass else: self.gui_details(id) self.refresh(self.detail, None, id) def refresh(self, detail, fun, id): # Determine Function of Refresh else do nothing orders = self.order_ids if fun == "next": # When at end, loop back to start if orders.index(id) + 1 == len(orders): id = orders[0] else: id = orders[orders.index(id) + 1] elif fun == "prev": id = orders[orders.index(id) - 1] self.id = id # Create Changing Value Lables conn = sqlite3.connect("login_db.db") query = f"SELECT * FROM orders WHERE order_no={id}" items = conn.execute(query) converted_item = tuple(items)[0] ttk.Label(self.detail, anchor="w", width=18, text=f"{converted_item[0]}").grid(row=2, column=1, padx=3) ttk.Label(self.detail, anchor="w", width=18, text=f"{converted_item[1]}").grid(row=3, column=1, padx=3) self.tree.delete(*self.tree.get_children()) for item in self.order_details.get(id): self.tree.insert("", "end", text=item[0], values=(item[1], )) for i in range(10): self.tree.insert("", "end", text="", values=("", )) self.tree.grid(row=4, column=0, columnspan=2, padx=15, pady=10) self.detail.mainloop() def get_data(self, all): self.order_details = km.db_retrieve(all) self.order_ids = km.order_ids(all)
def var(self): if self._var is None: self._var = BooleanVar() self._var.set(self._default) else: return self._var
viewmenu = Menu(menubar, tearoff=0) #viewmenu variables and adding commands show_line_no = IntVar() show_line_no.set(1) viewmenu.add_checkbutton(label="Show Line Numbers", variable=show_line_no, command=Updatelineno) show_cursor_info = IntVar() show_cursor_info.set(1) viewmenu.add_checkbutton(label="Show Cursor Location at Bottom", variable=show_cursor_info, command=Showcursorinfobar) to_highlight_line = BooleanVar() viewmenu.add_checkbutton(label="Highlight Current Line", onvalue=1, offvalue=0, variable=to_highlight_line, command=Tohighlightline) themesmenu = Menu(viewmenu, tearoff=0) viewmenu.add_cascade(label="Themes", menu=themesmenu) color_schemes = { 'Day Light': '#000000.#FFFFFF', 'Greygarious': '#83406A.#D1D4D1', 'Aquamarine': '#5B8340.#D1E7E0', 'Bold Beige': '#4B4620.#FFF0E1', 'Cobalt Blue': '#ffffBB.#3333aa', 'Olive Green': '#D1E7E0.#5B8340',
def build_parsing_book_by_groups(self): """ Наполнение подвкладки "По критериям" вкладки "Парсинг" :return: """ ################-------------PARSING_BOOK-------------################ left_frame = ttk.Frame(self.parsing_book_by_groups, relief='solid', borderwidth=1, padding=3) right_frame = ttk.Frame(self.parsing_book_by_groups, padding=5) left_frame.grid(row=0, column=0, sticky='NSWE') right_frame.grid(row=0, column=1, sticky='NSWE') progressbar = ttk.Progressbar(self.parsing_book_by_groups, orient='horizontal', mode='determinate', maximum=PROGRESSBAR_MAX, value=0) lbl_progress = ttk.Label(self.parsing_book_by_groups, text='', font=fonts.H5_FONT) lbl_progress.grid(row=1, column=0, columnspan=2, pady=5, sticky='SWE') progressbar.grid(row=2, column=0, columnspan=2, sticky='SWE') #################-------------LEFT_FRAME-------------################# # row 0 var_need_country = BooleanVar() var_need_city_region = BooleanVar() var_city_region = BooleanVar() var_need_country.set(0) var_need_city_region.set(0) var_city_region.set(0) country_frame = ttk.Frame(left_frame, padding=4) chk_country_frame = ttk.Checkbutton(country_frame, text='', variable=var_need_country, onvalue=1, offvalue=0) lbl_country = ttk.Label(country_frame, text='Страна', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) __var_country__ = list(LIST_COUNTRIES.keys()) var_country = ttk.Combobox(country_frame, font=fonts.COMBOBOX_FONT, width=36, state='readonly') var_country['values'] = __var_country__ var_country.set(__var_country__[0]) chk_city_region = ttk.Checkbutton(country_frame, variable=var_need_city_region, onvalue=1, offvalue=0, text='') lbl_city_region = ttk.Label(country_frame, text='Город/Регион', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) rdb_city = ttk.Radiobutton(country_frame, text='Город', value=0, variable=var_city_region) rdb_region = ttk.Radiobutton(country_frame, text='Регион', value=1, variable=var_city_region) cmb_city_region = ttk.Combobox(country_frame, font=fonts.COMBOBOX_FONT, width=36, state='readonly') cmb_city_region.set('Нажмите "Настройка"') # row 1 var_need_relationship = BooleanVar() var_need_relationship.set(0) relationship_frame = ttk.Frame(left_frame, padding=4) chk_relationship_has_photo_frame = ttk.Checkbutton( relationship_frame, variable=var_need_relationship, text='', onvalue=1, offvalue=0) lbl_relationship = ttk.Label(relationship_frame, text='Семейное положение', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) var_relationship = ttk.Combobox(relationship_frame, font=fonts.COMBOBOX_FONT, width=30, state='readonly') __var_relationship__ = list(STATUS_VK_PERSON.keys()) var_relationship['values'] = __var_relationship__ var_relationship.set(__var_relationship__[0]) # row 2 var_has_photo = BooleanVar() var_photo_from = IntVar() var_photo_to = IntVar() has_photo_frame = ttk.Frame(left_frame, padding=4) lbl_has_photo = ttk.Label(has_photo_frame, text='Фотографии', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) rdb_not_has_photo = ttk.Radiobutton(has_photo_frame, variable=var_has_photo, text='Неважно', value=0) rdb_has_photo = ttk.Radiobutton(has_photo_frame, variable=var_has_photo, text='Есть фото', value=1) # row 3 var_need_old = BooleanVar() var_old_from = IntVar() var_old_to = IntVar() var_need_old.set(0) var_old_from.set(18) var_old_to.set(40) var_need_count_followers = BooleanVar() var_followers_from = IntVar() var_followers_to = IntVar() var_need_count_followers.set(0) var_followers_from.set(0) var_followers_to.set(50) count_followers_old_frame = ttk.Frame(left_frame, padding=4) chk_old = ttk.Checkbutton(count_followers_old_frame, variable=var_need_old, onvalue=1, offvalue=0, text='') lbl_old = ttk.Label(count_followers_old_frame, font=fonts.H6_FONT, text='Возраст', foreground=styles.NOTABLE_LABEL_FONT) spn_old_from = ttk.Spinbox(count_followers_old_frame, width=5, font=fonts.SPINBOX_FONT, from_=18, to=99, textvariable=var_old_from, state='readonly') lbl_old_to = ttk.Label(count_followers_old_frame, text='--', font=fonts.H6_FONT) spn_old_to = ttk.Spinbox(count_followers_old_frame, width=5, font=fonts.SPINBOX_FONT, from_=19, to=100, textvariable=var_old_to, state='readonly') chk_need_followers = ttk.Checkbutton(count_followers_old_frame, variable=var_need_count_followers, onvalue=1, offvalue=0) lbl_followers = ttk.Label(count_followers_old_frame, text='Подписчиков', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) spn_followers_from = ttk.Spinbox(count_followers_old_frame, from_=0, to=FOLLOWERS_MAX, font=fonts.SPINBOX_FONT, textvariable=var_followers_from) lbl_followers_to = ttk.Label(count_followers_old_frame, text='--', font=fonts.H6_FONT) spn_followers_to = ttk.Spinbox(count_followers_old_frame, from_=1, to=FOLLOWERS_MAX, font=fonts.SPINBOX_FONT, textvariable=var_followers_to) # row 4 var_need_last_seen = BooleanVar() var_only = BooleanVar() var_last_seen_from = IntVar() var_last_seen_to = IntVar() var_need_last_seen.set(0) var_only.set(0) var_last_seen_from.set(5) var_last_seen_to.set(10) only_last_seen_frame = ttk.Frame(left_frame, padding=4) lbl_only = ttk.Label(only_last_seen_frame, text='Онлайн', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) rdb_not_only = ttk.Radiobutton(only_last_seen_frame, text='Неважно', variable=var_only, value=0) rdb_only = ttk.Radiobutton(only_last_seen_frame, text='Онлайн сейчас', variable=var_only, value=1) chk_need_last_seen = ttk.Checkbutton(only_last_seen_frame, variable=var_need_last_seen, onvalue=1, offvalue=0) lbl_last_seen = ttk.Label(only_last_seen_frame, text='Последний раз в сети', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) spn_last_seen_from = ttk.Spinbox(only_last_seen_frame, from_=0, to=LAST_SEEN_MAX, font=fonts.SPINBOX_FONT, textvariable=var_last_seen_from, width=5) lbl_last_seen_to = ttk.Label(only_last_seen_frame, text='--', font=fonts.H6_FONT) spn_last_seen_to = ttk.Spinbox(only_last_seen_frame, from_=2, to=LAST_SEEN_MAX, font=fonts.SPINBOX_FONT, textvariable=var_last_seen_to, width=5) lbl_last_seen_day = ttk.Label(only_last_seen_frame, text='дней назад', font=fonts.H6_FONT) # row 5 var_sex = IntVar() var_sex.set(0) var_can_send_message = BooleanVar() var_can_send_message.set(0) send_message_sex_frame = ttk.Frame(left_frame, padding=4) lbl_sex = ttk.Label(send_message_sex_frame, text='Пол', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) rdb_no_sex = ttk.Radiobutton(send_message_sex_frame, variable=var_sex, value=0, text='Неважно') rdb_female = ttk.Radiobutton(send_message_sex_frame, variable=var_sex, value=1, text='Женский') rdb_male = ttk.Radiobutton(send_message_sex_frame, variable=var_sex, value=2, text='Мужской') lbl_send_message = ttk.Label(send_message_sex_frame, text='Можно отправить сообщение', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) rdb_no_matter_send_message = ttk.Radiobutton( send_message_sex_frame, variable=var_can_send_message, value=0, text='Неважно') rdb_can_send_message = ttk.Radiobutton(send_message_sex_frame, variable=var_can_send_message, value=1, text='Можно') # row 6 var_need_political = BooleanVar() var_need_political.set(0) var_need_life_main = BooleanVar() var_need_life_main.set(0) political_life_main_frame = ttk.Frame(left_frame, padding=4) chk_political = ttk.Checkbutton(political_life_main_frame, variable=var_need_political, onvalue=1, offvalue=0, text='') lbl_political = ttk.Label(political_life_main_frame, text='Политические предпочтения', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) __var_political__ = list(POLITICAL.keys()) var_political = ttk.Combobox(political_life_main_frame, font=fonts.COMBOBOX_FONT, width=25, state='readonly') var_political['value'] = __var_political__ var_political.set(__var_political__[0]) chk_life_main = ttk.Checkbutton(political_life_main_frame, variable=var_need_life_main, onvalue=1, offvalue=0, text='') lbl_life_main = ttk.Label(political_life_main_frame, text='Главное в жизни', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) __var_life_main__ = list(LIFE_MAIN.keys()) var_life_main = ttk.Combobox(political_life_main_frame, font=fonts.COMBOBOX_FONT, width=25, state='readonly') var_life_main['value'] = __var_life_main__ var_life_main.set(__var_life_main__[0]) # row 7 var_need_people_main = BooleanVar() var_need_people_main.set(0) var_need_smoking = BooleanVar() var_need_smoking.set(0) people_main_smoking_frame = ttk.Frame(left_frame, padding=4) chk_people_main = ttk.Checkbutton(people_main_smoking_frame, variable=var_need_people_main, onvalue=1, offvalue=0, text='') lbl_people_main = ttk.Label(people_main_smoking_frame, font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT, text='Главное в людях') __var_people_main__ = list(PEOPLE_MAIN.keys()) var_people_main = ttk.Combobox(people_main_smoking_frame, font=fonts.COMBOBOX_FONT, state='readonly') var_people_main['value'] = __var_people_main__ var_people_main.set(__var_people_main__[0]) chk_smoking = ttk.Checkbutton(people_main_smoking_frame, variable=var_need_smoking, onvalue=1, offvalue=0, text='') lbl_smoking = ttk.Label(people_main_smoking_frame, font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT, text='Отношение к курению') __var_smoking__ = list(SMOKING.keys()) var_smoking = ttk.Combobox(people_main_smoking_frame, font=fonts.COMBOBOX_FONT, state='readonly') var_smoking['value'] = __var_smoking__ var_smoking.set(__var_smoking__[0]) # row 8 var_need_alcohol = BooleanVar() var_need_alcohol.set(0) alcohol_frame = ttk.Frame(left_frame, padding=4) chk_alcohol = ttk.Checkbutton(alcohol_frame, variable=var_need_alcohol, onvalue=1, offvalue=0, text='') lbl_alcohol = ttk.Label(alcohol_frame, font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT, text='Отношение к алкоголю') __var_alcohol__ = list(ALCOHOL.keys()) var_alcohol = ttk.Combobox(alcohol_frame, font=fonts.COMBOBOX_FONT, state='readonly') var_alcohol['value'] = __var_alcohol__ var_alcohol.set(__var_alcohol__[0]) # row 9 var_need_entry_status = BooleanVar() var_need_entry_status.set(0) entry_status_frame = ttk.Frame(left_frame, padding=4) chk_entry_status = ttk.Checkbutton(entry_status_frame, variable=var_need_entry_status, onvalue=1, offvalue=0, text='') lbl_entry_status = ttk.Label(entry_status_frame, text='Ключевое слово в статусе', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) var_entry_status = ttk.Entry(entry_status_frame, font=fonts.INPUT_FONT) # row 10 var_need_entry_about = BooleanVar() var_need_entry_about.set(0) entry_about_frame = ttk.Frame(left_frame, padding=4) chk_entry_about = ttk.Checkbutton(entry_about_frame, variable=var_need_entry_about, onvalue=1, offvalue=0, text='') lbl_entry_about = ttk.Label(entry_about_frame, font=fonts.H6_FONT, text='Ключевое слово в "О себе"', foreground=styles.NOTABLE_LABEL_FONT) var_entry_about = ttk.Entry(entry_about_frame, font=fonts.INPUT_FONT) # row 11 var_deactivate = BooleanVar() var_deactivate.set(1) deactivate_frame = ttk.Frame(left_frame, padding=4) lbl_deactivate = ttk.Label(deactivate_frame, text='Заблокированные аккаунты', font=fonts.H6_FONT, foreground=styles.NOTABLE_LABEL_FONT) rdb_not_deactivate = ttk.Radiobutton( deactivate_frame, variable=var_deactivate, value=0, text='Оставить', ) rdb_deactivate = ttk.Radiobutton(deactivate_frame, variable=var_deactivate, value=1, text='Убрать') # right_frame btn_parse = ttk.Button(right_frame, text='Парсить') btn_choose_record = ttk.Button(right_frame, text='Выбрать') btn_settings = ttk.Button(right_frame, text='Настройка') btn_all_record = ttk.Button(right_frame, text='Все записи') entry_pk = ttk.Entry(right_frame) widgets = { 'left_frame': left_frame, 'right_frame': right_frame, 'var_need_country': var_need_country, 'var_need_relationship': var_need_relationship, 'var_need_old': var_need_old, 'var_need_city_region': var_need_city_region, 'var_need_count_followers': var_need_count_followers, 'var_need_last_seen': var_need_last_seen, 'var_need_political': var_need_political, 'var_need_people_main': var_need_people_main, 'var_need_life_main': var_need_life_main, 'var_need_smoking': var_need_smoking, 'var_need_alcohol': var_need_alcohol, 'var_need_entry_status': var_need_entry_status, 'var_need_entry_about': var_need_entry_about, 'var_country': var_country, 'var_city_region': var_city_region, 'cmb_city_region': cmb_city_region, 'var_can_send_message': var_can_send_message, 'var_relationship': var_relationship, 'var_has_photo': var_has_photo, 'var_photo_from': var_photo_from, 'var_photo_to': var_photo_to, 'var_followers_from': var_followers_from, 'var_followers_to': var_followers_to, 'var_last_seen_from': var_last_seen_from, 'var_last_seen_to': var_last_seen_to, 'var_only': var_only, 'var_sex': var_sex, 'var_entry_about': var_entry_about, 'var_entry_status': var_entry_status, 'var_political': var_political, 'var_life_main': var_life_main, 'var_people_main': var_people_main, 'var_smoking': var_smoking, 'var_alcohol': var_alcohol, 'var_old_from': var_old_from, 'var_old_to': var_old_to, 'lbl_progress': lbl_progress, 'progressbar': progressbar, 'lbl_last_seen': lbl_last_seen, 'lbl_last_seen_to': lbl_last_seen_to, 'spn_last_seen_from': spn_last_seen_from, 'spn_last_seen_to': spn_last_seen_to, 'chk_need_last_seen': chk_need_last_seen, 'var_deactivate': var_deactivate, 'lbl_last_seen_day': lbl_last_seen_day, 'entry_pk': entry_pk, } ####################-------------GRID-------------#################### # row 0 country_frame.grid(row=0, column=0, sticky='NSWE', pady=6) chk_country_frame.grid(row=0, column=0, padx=5, sticky='SW') lbl_country.grid(row=0, column=1, sticky='SW') var_country.grid(row=0, column=2, sticky='SWE', padx=7) chk_city_region.grid(row=0, column=3, sticky='SW', padx=15) lbl_city_region.grid(row=0, column=4, sticky='SW') rdb_city.grid(row=0, column=5, sticky='SW', padx=5) rdb_region.grid(row=0, column=6, sticky='SW') cmb_city_region.grid(row=0, column=7, sticky='SWE', padx=5) # row 1 count_followers_old_frame.grid(row=1, column=0, sticky='NSWE') chk_old.grid(row=0, column=0, sticky='SW', padx=5) lbl_old.grid(row=0, column=1, sticky='SW') spn_old_from.grid(row=0, column=2, sticky='SW', padx=2) lbl_old_to.grid(row=0, column=3, sticky='SW', padx=5) spn_old_to.grid(row=0, column=4, sticky='SW', padx=2) chk_need_followers.grid(row=0, column=5, sticky='SW', padx=15) lbl_followers.grid(row=0, column=6, sticky='SW') spn_followers_from.grid(row=0, column=7, sticky='SW', padx=2) lbl_followers_to.grid(row=0, column=8, sticky='SW', padx=5) spn_followers_to.grid(row=0, column=9, sticky='SW', padx=2) # row 2 relationship_frame.grid(row=2, column=0, sticky='NSWE', pady=7) chk_relationship_has_photo_frame.grid(row=0, column=0, sticky='SW', padx=5) lbl_relationship.grid(row=0, column=1, sticky='SW') var_relationship.grid(row=0, column=2, sticky='SWE', padx=10) # row 3 send_message_sex_frame.grid(row=3, column=0, sticky='NSWE') lbl_sex.grid(row=0, column=0, sticky='SW', padx=5) rdb_no_sex.grid(row=0, column=1, sticky='SW') rdb_female.grid(row=0, column=2, sticky='SW', padx=2) rdb_male.grid(row=0, column=3, sticky='SW') lbl_send_message.grid(row=0, column=4, sticky='SW', padx=10) rdb_no_matter_send_message.grid(row=0, column=5, sticky='SW') rdb_can_send_message.grid(row=0, column=6, sticky='SW', padx=2) # row 4 only_last_seen_frame.grid(row=4, column=0, sticky='NSWE') lbl_only.grid(row=0, column=0, sticky='SW', padx=5) rdb_not_only.grid(row=0, column=1, sticky='SW') rdb_only.grid(row=0, column=2, sticky='SW', padx=3) chk_need_last_seen.grid(row=0, column=3, sticky='SW', padx=5) lbl_last_seen.grid(row=0, column=4, sticky='SW', padx=5) spn_last_seen_from.grid(row=0, column=5, sticky='SW') lbl_last_seen_to.grid(row=0, column=6, sticky='SW', padx=5) spn_last_seen_to.grid(row=0, column=7, sticky='SW') lbl_last_seen_day.grid(row=0, column=8, sticky='SW', padx=2) # row 5 has_photo_frame.grid(row=5, column=0, sticky='NSWE', pady=6) lbl_has_photo.grid(row=0, column=0, sticky='SW', padx=5) rdb_not_has_photo.grid(row=0, column=1, sticky='SW') rdb_has_photo.grid(row=0, column=2, sticky='SW', padx=3) # row 6 political_life_main_frame.grid(row=6, column=0, sticky='NSWE', pady=6) chk_political.grid(row=0, column=0, sticky='SW', padx=5) lbl_political.grid(row=0, column=1, sticky='SW') var_political.grid(row=0, column=2, sticky='SW', padx=3) chk_life_main.grid(row=0, column=3, sticky='SW', padx=10) lbl_life_main.grid(row=0, column=4, sticky='SW') var_life_main.grid(row=0, column=5, sticky='SW', padx=3) # row 7 people_main_smoking_frame.grid(row=7, column=0, sticky='NSWE', pady=6) chk_people_main.grid(row=0, column=0, sticky='SW', padx=5) lbl_people_main.grid(row=0, column=1, sticky='SW') var_people_main.grid(row=0, column=2, sticky='SW', padx=3) chk_smoking.grid(row=0, column=3, sticky='SW', padx=10) lbl_smoking.grid(row=0, column=4, sticky='SW') var_smoking.grid(row=0, column=5, sticky='SW', padx=3) # row 8 alcohol_frame.grid(row=8, column=0, sticky='NSWE', pady=6) chk_alcohol.grid(row=0, column=0, sticky='SW', padx=5) lbl_alcohol.grid(row=0, column=1, sticky='SW') var_alcohol.grid(row=0, column=2, sticky='SW', padx=3) # row 9 entry_status_frame.grid(row=9, column=0, sticky='NSWE', pady=6) chk_entry_status.grid(row=0, column=0, sticky='SW', padx=5) lbl_entry_status.grid(row=0, column=1, sticky='SW') var_entry_status.grid(row=0, column=2, sticky='SWE', padx=3) # row 10 entry_about_frame.grid(row=10, column=0, sticky='NSWE', pady=6) chk_entry_about.grid(row=0, column=0, sticky='SW', padx=5) lbl_entry_about.grid(row=0, column=1, sticky='SW') var_entry_about.grid(row=0, column=2, sticky='SWE') # row 11 deactivate_frame.grid(row=11, column=0, sticky='NSWE') lbl_deactivate.grid(row=0, column=0, sticky='SW', padx=5) rdb_not_deactivate.grid(row=0, column=1, sticky='SW') rdb_deactivate.grid(row=0, column=2, sticky='SW') btn_parse.grid(row=0, column=0, sticky='SWE', pady=5) btn_choose_record.grid(row=1, column=0, sticky='SWE') btn_settings.grid(row=2, column=0, sticky='SWE', pady=5) btn_all_record.grid(row=3, column=0, sticky='SWE') self.parsing_book_by_groups.columnconfigure(0, weight=9) self.parsing_book_by_groups.columnconfigure(1, weight=1) self.parsing_book_by_groups.rowconfigure(0, weight=1) left_frame.columnconfigure(0, weight=1) entry_status_frame.columnconfigure(2, weight=1) entry_about_frame.columnconfigure(2, weight=1) btn_all_record.bind('<Button-1>', lambda event: TreeViewWindow()) btn_choose_record.bind( '<Button-1>', lambda event: TreeViewWindow( method='parse', completion_name=NAME_PARSING['by_groups'], entry_pk=entry_pk)) rdb_city.bind( '<Button-1>', lambda event: FunctionsForWindows.setting_region_city(widgets)) rdb_region.bind( '<Button-1>', lambda event: FunctionsForWindows.setting_region_city(widgets)) rdb_not_only.bind( '<Button-1>', lambda event: FunctionsForWindows.setting_only(widgets)) rdb_only.bind('<Button-1>', lambda event: FunctionsForWindows.setting_only(widgets)) btn_settings.bind( '<Button-1>', lambda event: self.function_windows. setting_before_parsing(widgets)) btn_parse.bind( '<Button-1>', lambda event: self.function_windows.parsing_by_groups(widgets))
class Dialogue(Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.style = Style() self.style.theme_use("default") self.master.title("LineChart") self.pack(fill=BOTH, expand=True) self.SSU = BooleanVar() self.SSU.set(1) self.COX1 = BooleanVar() self.COX1.set(1) self.EF1A = BooleanVar() self.EF1A.set(1) self.EF1A_variants = BooleanVar() self.EF1A_variants.set(1) self.filelabel = StringVar(self, "File not chosen") self.filename = "" self.var = IntVar() self.var.set(1) self.clades = IntVar() self.clades.set(0) # self.columnconfigure(2, weight=1) # self.rowconfigure(2, weight=1) cbSSU = Checkbutton(self, text="SSU", variable=self.SSU, state=DISABLED, onvalue=1, offvalue=0) cbSSU.select() cbSSU.grid(sticky=W, padx=5, pady=5) cbCOX1 = Checkbutton(self, text="COX1", variable=self.COX1, onvalue=1, offvalue=0) cbCOX1.select() cbCOX1.grid(sticky=W, row=1, padx=5, pady=5) cbEF1A = Checkbutton(self, text="EF1A", variable=self.EF1A, onvalue=1, offvalue=0) cbEF1A.select() cbEF1A.grid(sticky=W, row=2, padx=5, pady=5) cbEcomb = Checkbutton(self, text="EF1A combinations", variable=self.EF1A_variants, onvalue=1, offvalue=0) cbEcomb.select() cbEcomb.grid(sticky=W, row=3, padx=5, pady=5) openButton = Button(self, text="Choose file", command=self.onOpen) openButton.grid(sticky=W, row=0, column=1, padx=5, pady=5) labFile = Label(self, textvariable=self.filelabel) labFile.grid(sticky=W, row=0, column=2, columnspan=2, padx=5, pady=5) closeButton = Button(self, text="Exit", command=self.quit) closeButton.grid(sticky=E, row=4, column=3, padx=5, pady=5) okButton = Button(self, text="OK", command=self.onOK) okButton.grid(sticky=W, row=4, column=0, padx=5, pady=5) def onOpen(self): ftypes = [('Excel files', '*.xls, *.xlsx'), ('All files', '*')] dlg = filedialog.Open(self, filetypes=ftypes) file = dlg.show() if file != '': self.filelabel.set("Current file: " + file) self.filename = file self.readExcel(self.filename) self.columns = BooleanVar() self.columns.set(1) if self.filelabel.get() != "File not chosen": rboneColumn = Radiobutton(self, text="Arrange in 1 column", variable=self.columns, value=1, command=self.onClick) rboneColumn.grid(sticky=W, row=2, column=1, padx=5, pady=5) rb2Columns = Radiobutton(self, text="Arrange in 2 columns", variable=self.columns, value=0, command=self.onClick) rb2Columns.grid(sticky=W, row=3, column=1, padx=5, pady=5) def readExcel(self, filename): self.dataframe = read_excel(filename, index_col="Specimen") if self.clades.get() != 0: self.labClades.grid_remove() self.clades.set(len(set(self.dataframe.loc[:, "Clade"]))) self.labClades = Label(self, text="Number of clades: " + str(self.clades.get())) self.labClades.grid(sticky=W, row=1, column=1, padx=5, pady=5) def onClick(self): if self.columns.get() == 0: self.scale = Scale(self, from_=1, to=self.clades.get() - 1, command=self.onScale, orient=HORIZONTAL) self.scale.grid(sticky=W, row=3, column=2) self.labScale = Label( self, text="Number of clades in the first column: ") self.labScale.grid(sticky=W, row=2, column=2) self.ScaleVal = Label(self, textvariable=self.var) self.ScaleVal.grid(sticky=E, row=2, column=2) else: self.scale.grid_remove() self.labScale.grid_remove() self.ScaleVal.grid_remove() def onScale(self, val): v = int(float(val)) self.var.set(v) # print(self.var.get()) def onOK(self): dataframe = self.dataframe SSU = self.SSU.get() COX1 = self.COX1.get() EF1A = self.EF1A.get() EF1A_combinations = self.EF1A_variants.get() change = self.var.get() onecolumn = self.columns.get() # graphical parameters: distance between columns and lines of variants, total height etc. top = 200 # uppermost position xS = 1 # X position of SSU column on the graph xE = 2 # X position of EF1A column on the graph xC = 0 # X position of COX1 column on the graph cladeX = 3.3 # X position of clade names on the graph distance = 5 # distance between lines shift = 5 # distance between two columns vardict = {} ssu_set = set() ef1a_set = set() cox1_set = set() # Count the number of specimens for each clade that have a valid SSU and at least one other valid gene variant countdict = {} for specimen in dataframe.index.values: valid = 0 if findall("[A-Za-z]", str(dataframe.loc[specimen, "SSU"])) == []: if EF1A and COX1: if findall("[A-Za-z]", str( dataframe.loc[specimen, "EF1A"])) == [] or findall( "[A-Za-z]", str(dataframe.loc[specimen, "COX1"])) == []: valid = 1 elif EF1A: if findall("[A-Za-z]", str(dataframe.loc[specimen, "EF1A"])) == []: valid = 1 elif COX1: if findall("[A-Za-z]", str(dataframe.loc[specimen, "COX1"])) == []: valid = 1 if dataframe.loc[specimen, "Clade"] not in countdict: countdict[dataframe.loc[specimen, "Clade"]] = valid else: countdict[dataframe.loc[specimen, "Clade"]] += valid # build a dict of connections for every SSU variant, regardless of clades for i in dataframe.index.values: if findall("[A-Za-z]", str(dataframe.loc[ i, "SSU"])) == []: # choosing ony valid SSU variants if dataframe.loc[i, "SSU"] not in vardict: vardict[dataframe.loc[i, "SSU"]] = { "SSU_count": 1, "EF1A": {}, "COX1": {} } # adding new SSU variant into dictionary ssu_set.add(dataframe.loc[i, "SSU"]) else: vardict[dataframe.loc[i, "SSU"]][ "SSU_count"] += 1 # increasing SSU variant count if COX1: if findall("[A-Za-z]", str(dataframe.loc[i, "COX1"]) ) == []: # choosing ony valid COX1 variants if dataframe.loc[i, "COX1"] not in vardict[ dataframe.loc[i, "SSU"]]["COX1"]: vardict[dataframe.loc[i, "SSU"]]["COX1"][ dataframe.loc[ i, "COX1"]] = 1 # adding new COX1 variant cox1_set.add(dataframe.loc[i, "COX1"]) else: vardict[dataframe.loc[i, "SSU"]]["COX1"][ dataframe.loc[ i, "COX1"]] += 1 # increasing COX1 variant count if EF1A and EF1A_combinations: if "homozygous" in str(dataframe.loc[i, "EF1A_combinations"]) \ or "both" in str(dataframe.loc[i, "EF1A_combinations"]) \ and findall("[A-Za-z]", str(dataframe.loc[ i, "EF1A"])) == []: # choosing ony homozygous EF1A variants or unique unknown heterozygous if dataframe.loc[i, "EF1A"] not in vardict[ dataframe.loc[i, "SSU"]]["EF1A"]: vardict[dataframe.loc[i, "SSU"]]["EF1A"][ dataframe.loc[ i, "EF1A"]] = 1 # adding new EF1A variant ef1a_set.add(dataframe.loc[i, "EF1A"]) else: vardict[dataframe.loc[i, "SSU"]]["EF1A"][ dataframe.loc[ i, "EF1A"]] += 1 # increasing EF1A variant count elif "+" in str(dataframe.loc[i, "EF1A_combinations"] ): # choosing known heterozygous variants for var in findall( "[0-9]+", str(dataframe.loc[i, "EF1A_combinations"])): if var not in vardict[dataframe.loc[ i, "SSU"]]["EF1A"]: vardict[dataframe.loc[i, "SSU"]]["EF1A"][ var] = 1 # adding new EF1A variant ef1a_set.add(int(var)) else: vardict[dataframe.loc[i, "SSU"]]["EF1A"][ var] += 1 # increasing EF1A variant count elif EF1A and findall("[A-Za-z]", str( dataframe.loc[i, "EF1A"])) == []: if dataframe.loc[i, "EF1A"] not in vardict[dataframe.loc[ i, "SSU"]]["EF1A"]: vardict[dataframe.loc[i, "SSU"]]["EF1A"][dataframe.loc[ i, "EF1A"]] = 1 # adding new EF1A variant ef1a_set.add(dataframe.loc[i, "EF1A"]) else: vardict[dataframe.loc[i, "SSU"]]["EF1A"][dataframe.loc[ i, "EF1A"]] += 1 # increasing EF1A variant count # print(vardict) # # modify dataframe by adding known heterozygous variants into EF1A column. new_dataframe = dataframe if EF1A_combinations: for i in range(len(new_dataframe["EF1A_combinations"])): if "+" in str(new_dataframe["EF1A_combinations"][i]): if len( findall("[0-9]+", str(new_dataframe["EF1A_combinations"] [i]))) == 1: new_dataframe.loc[ new_dataframe.index.values[i], "EF1A"] = int( findall( "[0-9]+", str(new_dataframe["EF1A_combinations"][i])) [0]) elif len( findall("[0-9]+", str(new_dataframe["EF1A_combinations"] [i]))) == 2: new_dataframe.loc[ new_dataframe.index.values[i], "EF1A"] = int( findall( "[0-9]+", str(new_dataframe["EF1A_combinations"][i])) [0]) new_dataframe = new_dataframe.append( new_dataframe.iloc[i], ignore_index=True) new_dataframe.loc[ new_dataframe.index.values[-1], "EF1A"] = int( findall( "[0-9]+", str(new_dataframe["EF1A_combinations"][i])) [1]) new_dataframe.loc[new_dataframe.index.values[-1], "COX1"] = "" grouping_columns = ["Clade", "SSU"] if COX1: grouping_columns.append("COX1") if EF1A: grouping_columns.append("EF1A") grouped = new_dataframe.groupby(grouping_columns).aggregate( {"SSU": "count"}) # print(grouped) # starting Y coordinates yS = top yE = top yC = top # dictionaries with pairs of coordinates for every variant of every gene ssu_coo = {} cox1_coo = {} ef1a_coo = {} clade_coo = {} # sets of clades and variants that were catalogued already to avoid duplicates clade_done = set() ssu_done = set() cox1_done = set() ef1a_done = set() # Gives XY coordinates to every genetic variant iterating through clades. # Variants are sorted acending; clades are sorted alphabetically counter = 0 # adjusting distance between columns by adding the size of the longest clade name length shift_adj = 0.1 * max( [len(i) for i in grouped.index.get_level_values("Clade")]) + 0.3 shift += shift_adj for clade in grouped.index.get_level_values("Clade"): if clade not in clade_done: if not onecolumn and counter == change: # if a specified change value is reached, starts the second column with a specified shift xS += shift yS = top if COX1: xC += shift yC = top if EF1A: xE += shift yE = top cladeX += shift counter += 1 yS -= distance if COX1: yC -= distance if EF1A: yE -= distance # add coordinates of the clade name and vertical line at the side ssuvalid = set([ i for i in grouped.loc[(clade)].index.get_level_values("SSU") if findall("[A-Za-z]", str(i)) == [] and str(i) != "" ]) if COX1: cox1valid = set([ i for i in grouped.loc[( clade)].index.get_level_values("COX1") if findall("[A-Za-z]", str(i)) == [] and str(i) != "" ]) if EF1A: ef1avalid = set([ i for i in grouped.loc[( clade)].index.get_level_values("EF1A") if findall("[A-Za-z]", str(i)) == [] and str(i) != "" ]) genelenlist = [len(ssuvalid)] if COX1: genelenlist.append(len(cox1valid)) if EF1A: genelenlist.append(len(ef1avalid)) cladeY = yS - (max(genelenlist) - 1) * distance * 0.5 linestart = yS + 0.5 * distance lineend = yS - (max(genelenlist) - 1) * distance - 0.5 * distance clade_coo[clade] = [ cladeX, cladeY, cladeX - 0.2, linestart, lineend, countdict[clade] ] # within-clade vertical position adjustments if COX1 and not EF1A: if len(ssuvalid) - len(cox1valid) >= 2: yC -= distance * (len(ssuvalid) - len(cox1valid)) // 2 elif len(cox1valid) - len(ssuvalid) >= 2: yS -= distance * (len(cox1valid) - len(ssuvalid)) // 2 elif EF1A and COX1: if len(ssuvalid) - len(cox1valid) >= 2: yC -= distance * (len(ssuvalid) - len(cox1valid)) // 2 if len(ssuvalid) - len(ef1avalid) >= 2: yE -= distance * (len(ssuvalid) - len(ef1avalid)) // 2 elif len(ef1avalid) - len(ssuvalid) >= 2: yS -= distance * (len(ef1avalid) - len(ssuvalid)) // 2 yC -= distance * (len(ef1avalid) - len(ssuvalid)) // 2 elif len(cox1valid) - len(ssuvalid) >= 2: yS -= distance * (len(cox1valid) - len(ssuvalid)) // 2 if len(cox1valid) - len(ef1avalid) >= 2: yE -= distance * (len(cox1valid) - len(ef1avalid)) // 2 elif len(ef1avalid) - len(cox1valid) >= 2: yC -= distance * (len(ef1avalid) - len(cox1valid)) // 2 yS -= distance * (len(ef1avalid) - len(cox1valid)) // 2 elif len(ef1avalid) - len(ssuvalid) >= 2: yS -= distance * (len(ef1avalid) - len(ssuvalid)) // 2 yC -= distance * (len(ef1avalid) - len(cox1valid)) // 2 elif len(ssuvalid) - len(ef1avalid) >= 2: yE -= distance * (len(ssuvalid) - len(ef1avalid)) // 2 elif EF1A: if len(ssuvalid) - len(ef1avalid) >= 2: yE -= distance * (len(ssuvalid) - len(ef1avalid)) // 2 elif len(ef1avalid) - len(ssuvalid) >= 2: yS -= distance * (len(ef1avalid) - len(ssuvalid)) // 2 # finally, assign coordinates for ssu in grouped.loc[(clade)].index.get_level_values("SSU"): if findall("[A-Za-z]", str(ssu)) == [] and str( ssu ) != "": # choose only valid genetic variants (no text, only numbers) if ssu not in ssu_done: ssu_coo[ssu] = [xS, yS] yS -= distance ssu_done.add(ssu) if COX1: for cox1 in grouped.loc[( clade)].index.get_level_values("COX1"): if findall("[A-Za-z]", str(cox1)) == [] and str( cox1 ) != "": # choose only valid genetic variants (no text, only numbers) if cox1 not in cox1_done: cox1_coo[cox1] = [xC, yC] yC -= distance cox1_done.add(cox1) if EF1A: for ef1a in grouped.loc[( clade)].index.get_level_values("EF1A"): if findall("[A-Za-z]", str(ef1a)) == [] and str( ef1a ) != "": # choose only valid genetic variants (no text, only numbers) if ef1a not in ef1a_done: ef1a_coo[ef1a] = [xE, yE] yE -= distance ef1a_done.add(ef1a) clade_done.add(clade) geneXlist = [xS] geneYlist = [yS] if COX1: geneXlist.append(xC) geneYlist.append(yC) if EF1A: geneXlist.append(xE) geneYlist.append(yE) lowest = min(geneYlist) yS = lowest yC = lowest yE = lowest # print(grouped) # Building a plot def choose_line(size): # a rule for choosing line width for the plot size = int(size) if size in (1, 2): width = 1 elif size == 3: width = 1.5 elif size < 6: width = 2 elif size < 11: width = 2.5 else: width = 3 return width # remove axes ax1 = axes(frameon=False) ax1.set_frame_on(False) ax1.get_xaxis().set_visible(False) ax1.get_yaxis().set_visible(False) # build the lines between genetic variants for ssu in vardict: if EF1A: for ef1a in vardict[ssu]["EF1A"]: if findall("[A-Za-z]", str(ef1a)) == []: size = vardict[ssu]["EF1A"][ef1a] plot([ ef1a_coo[int(ef1a)][0] + 0.4, ssu_coo[ssu][0] + 0.5 ], [ef1a_coo[int(ef1a)][1], ssu_coo[ssu][1]], linestyle="dashed" if size == 1 else "solid", linewidth=choose_line(size), color="black") text(ef1a_coo[int(ef1a)][0] + 0.7, ef1a_coo[int(ef1a)][1], ef1a, ha="center", va="center") if COX1: for cox1 in vardict[ssu]["COX1"]: if findall("[A-Za-z]", str(cox1)) == []: size = vardict[ssu]["COX1"][cox1] plot([cox1_coo[cox1][0], ssu_coo[ssu][0]], [cox1_coo[cox1][1], ssu_coo[ssu][1]], linestyle="dashed" if size == 1 else "solid", linewidth=choose_line(vardict[ssu]["COX1"][cox1]), color="black") text(cox1_coo[cox1][0] - 0.3, cox1_coo[cox1][1], cox1, ha="center", va="center") text(ssu_coo[ssu][0] + 0.25, ssu_coo[ssu][1], ssu, ha="center", va="center") # add gene names above the variants for the second column if not onecolumn: text(xS - shift + 0.25, top + distance + 0.2, "SSU", ha="center") text(xS + 0.25, top + distance + 0.2, "SSU", ha="center") if EF1A: text(xE - shift + 0.7, top + distance + 0.2, "EF1A", ha="center") text(xE + 0.7, top + distance + 0.2, "EF1A", ha="center") if COX1: text(xC - shift - 0.3, top + distance + 0.2, "COI", ha="center") text(xC - 0.3, top + distance + 0.2, "COI", ha="center") else: text(xS + 0.25, top + distance + 0.2, "SSU", ha="center") if EF1A: text(xE + 0.7, top + distance + 0.2, "EF1A", ha="center") if COX1: text(xC - 0.3, top + distance + 0.2, "COI", ha="center") # add clade names and vertical lines to the right of the column for clade in clade_coo: if EF1A: text(clade_coo[clade][0], clade_coo[clade][1], "%s (%d)" % (clade, clade_coo[clade][5]), ha="left", va="center") plot([clade_coo[clade][2], clade_coo[clade][2]], [clade_coo[clade][3], clade_coo[clade][4]], linewidth=2, color="black") else: text(clade_coo[clade][0] - shift * 0.5 + shift_adj + 0.65, clade_coo[clade][1], "%s (%d)" % (clade, clade_coo[clade][5]), ha="left", va="center") plot([ clade_coo[clade][2] - shift * 0.5 + shift_adj + 0.7, clade_coo[clade][2] - shift * 0.5 + shift_adj + 0.7 ], [clade_coo[clade][3], clade_coo[clade][4]], linewidth=2, color="black") # set limits for X axis to avoid overlapping with legend if not onecolumn and EF1A: xlim(0, 14) elif not onecolumn: xlim(0, 12) elif onecolumn and EF1A: xlim(0, 7) elif onecolumn: xlim(0, 5) # produce lines for a legend leg_lines = [ Line2D([0], [0], color="black", linestyle="dashed", linewidth=1), Line2D([0], [0], color="black", linewidth=1), Line2D([0], [0], color="black", linewidth=1.5), Line2D([0], [0], color="black", linewidth=2), Line2D([0], [0], color="black", linewidth=2.5), Line2D([0], [0], color="black", linewidth=3) ] # plot legend legend(leg_lines, ["1", "2", "3", "4-5", "6-10", "11-20"], loc="upper right") # show the plot show()
def initUI(self): self.style = Style() self.style.theme_use("default") self.master.title("LineChart") self.pack(fill=BOTH, expand=True) self.SSU = BooleanVar() self.SSU.set(1) self.COX1 = BooleanVar() self.COX1.set(1) self.EF1A = BooleanVar() self.EF1A.set(1) self.EF1A_variants = BooleanVar() self.EF1A_variants.set(1) self.filelabel = StringVar(self, "File not chosen") self.filename = "" self.var = IntVar() self.var.set(1) self.clades = IntVar() self.clades.set(0) # self.columnconfigure(2, weight=1) # self.rowconfigure(2, weight=1) cbSSU = Checkbutton(self, text="SSU", variable=self.SSU, state=DISABLED, onvalue=1, offvalue=0) cbSSU.select() cbSSU.grid(sticky=W, padx=5, pady=5) cbCOX1 = Checkbutton(self, text="COX1", variable=self.COX1, onvalue=1, offvalue=0) cbCOX1.select() cbCOX1.grid(sticky=W, row=1, padx=5, pady=5) cbEF1A = Checkbutton(self, text="EF1A", variable=self.EF1A, onvalue=1, offvalue=0) cbEF1A.select() cbEF1A.grid(sticky=W, row=2, padx=5, pady=5) cbEcomb = Checkbutton(self, text="EF1A combinations", variable=self.EF1A_variants, onvalue=1, offvalue=0) cbEcomb.select() cbEcomb.grid(sticky=W, row=3, padx=5, pady=5) openButton = Button(self, text="Choose file", command=self.onOpen) openButton.grid(sticky=W, row=0, column=1, padx=5, pady=5) labFile = Label(self, textvariable=self.filelabel) labFile.grid(sticky=W, row=0, column=2, columnspan=2, padx=5, pady=5) closeButton = Button(self, text="Exit", command=self.quit) closeButton.grid(sticky=E, row=4, column=3, padx=5, pady=5) okButton = Button(self, text="OK", command=self.onOK) okButton.grid(sticky=W, row=4, column=0, padx=5, pady=5)
class FrameSearch(EasyTkObject): def __init__(self,root_controller,root,widget): super(FrameSearch,self).__init__() self.easy.add_complete_widget(root) self.easy.add_complete_widget(widget) self.controller = root_controller self.init_variables_and_methods() self.import_variables( {"sort_by_var":self.sort_by_var,"sort_by_range":self.sort_by_range, "or_vertical":self.or_vertical,"or_horizontal":self.or_horizontal, "or_square":self.or_square,"img_res":self.img_res,"search_btn":self.search_btn}) self.import_modules([Checkbutton,]) def init_variables_and_methods(self): self.sort_by_var = StringVar() self.sort_by_var.set(None) self.sort_by_range = StringVar() self.sort_by_range.set(None) self.or_vertical = BooleanVar() self.or_horizontal = BooleanVar() self.or_square = BooleanVar() self.orPanoramicHorizontal = BooleanVar() self.img_res = StringVar() self.img_res.set(None) def create_widgets(self): self.open_file("view/json/FrameSearch.json") self.reading_from_json() def tkraise(self): """ print(self.get("FrameSearch")) """ self.controller.geometry = "1280x250" self.get("FrameSearch").tkraise() def set_models(self,models): self.search_details = models["SearchDetails"] self.current_page = models["CurrentPage"] self.getty_pictures = models["GettyPictures"] self.selected_pictures = models["SelectedPictures"] def search_btn(self): self.search_details.entry = self.get("EntrySearch").get() self.search_details.sort = self.sort_by_var.get() self.search_details.datum_range = self.sort_by_range.get() self.search_details.is_vertical = self.or_vertical.get() self.search_details.is_horizontal = self.or_horizontal.get() self.search_details.is_square = self.or_square.get() self.search_details.resolution = self.img_res.get() self.search_details.search() self.controller.switch_window("FramePictures") def reset_search(self): self.getty_pictures.reset_all() self.current_page.original_page_url = "" self.current_page.reset_page_number()
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, name="frame") self.parent = parent self.initUI() def initUI(self): gui_style = Style() gui_style.configure('My.TRadioButton', foreground='#334353') gui_style.configure('My.TFrame', columnspan=4) self.parent.title("Commands") self.pack(fill=BOTH, expand=True) self.btn = tk.Button(self, text="Button", command=self.onButton1Click) self.btn.grid(row=0, column=0, padx=15) ##self.btn.config(foreground = 'green') self.btn['fg'] = 'dark green' ##cb = Checkbutton(self , text="Checkbutton", command=self.onButton2Click) ##cb.pack(side=LEFT) self.parent.bind("<Escape>", self.quitApp) self.var = BooleanVar() cb = Checkbutton(self, text="Bind event", variable=self.var, command=lambda: self.onBind(self.btn)) cb.grid(row=0, column=1) self.rbvar = IntVar() self.rbvar.set(1) self._1 = 5 self._2 = 10 self._3 = 15 btnFrame = tk.Frame(self) self.rb0 = tk.Radiobutton(btnFrame, text="On", variable=self.rbvar, value=self._1, foreground='red', background='light gray', command=self.rbSelected) self.rb1 = tk.Radiobutton(btnFrame, text="Off", variable=self.rbvar, value=self._2, background='light gray', command=self.rbSelected) self.rb2 = tk.Radiobutton(btnFrame, text="Limbo", variable=self.rbvar, value=self._3, background='light gray', command=self.rbSelected) self.rb0.grid(row=0, column=0) self.rb1.grid(row=0, column=1) self.rb2.grid(row=0, column=2) btnFrame.grid(row=1, column=0, sticky='news', padx=6, pady=12) def rbSelected(self): self.btn['fg'] = self.rb0['fg'] = self.rb1['fg'] = self.rb2[ 'fg'] = 'black' if self.rbvar.get() == self._1: print('Radio button 1') self.btn['fg'] = self.rb0['fg'] = 'green' elif self.rbvar.get() == self._2: print('Radio button 2') self.btn['fg'] = self.rb1['fg'] = 'red' elif self.rbvar.get() == self._3: print('Radio button 3') self.btn['fg'] = self.rb2['fg'] = 'cyan' else: MB.showinfo(title='Tilt!!', message='Something went wrong. rbvar is: ' + str(self.rbvar)) def onBind(self, w): if (self.var.get() == True): w.bind("<Button-1>", self.onButton1Click) print('the BIND') else: print('the unbind') w.unbind("<Button-1>") def quitApp(self, e): ret = MB.askquestion("Question", "Are you sure you wish to quit?", default=MB.NO) if (ret == "yes"): self.quit() else: return def onButton1Click(self): print("Push Button clicked") def onButton2Click(self): print("Checkbutton clicked")
class ViewRenderedGrid(ViewWinGrid.ViewGrid): def __init__(self, modelXbrl, tabWin, lang): super(ViewRenderedGrid, self).__init__(modelXbrl, tabWin, "Rendering", True, lang) self.newFactItemOptions = ModelInstanceObject.NewFactItemOptions( xbrlInstance=modelXbrl) self.factPrototypes = [] self.zOrdinateChoices = None # context menu Boolean vars self.options = self.modelXbrl.modelManager.cntlr.config.setdefault( "viewRenderedGridOptions", {}) self.ignoreDimValidity = BooleanVar( value=self.options.setdefault("ignoreDimValidity", True)) self.xAxisChildrenFirst = BooleanVar( value=self.options.setdefault("xAxisChildrenFirst", True)) self.yAxisChildrenFirst = BooleanVar( value=self.options.setdefault("yAxisChildrenFirst", False)) def close(self): super(ViewRenderedGrid, self).close() if self.modelXbrl: for fp in self.factPrototypes: fp.clear() self.factPrototypes = None def loadTablesMenu(self): tblMenuEntries = {} tblRelSet = self.modelXbrl.relationshipSet("Table-rendering") for tblLinkroleUri in tblRelSet.linkRoleUris: for tableAxisArcrole in (XbrlConst.euTableAxis, XbrlConst.tableBreakdown, XbrlConst.tableBreakdown201301, XbrlConst.tableAxis2011): tblAxisRelSet = self.modelXbrl.relationshipSet( tableAxisArcrole, tblLinkroleUri) if tblAxisRelSet and len(tblAxisRelSet.modelRelationships) > 0: # table name modelRoleTypes = self.modelXbrl.roleTypes.get( tblLinkroleUri) if modelRoleTypes is not None and len(modelRoleTypes) > 0: roledefinition = modelRoleTypes[0].definition if roledefinition is None or roledefinition == "": roledefinition = os.path.basename(tblLinkroleUri) for table in tblAxisRelSet.rootConcepts: # add table to menu if there's any entry tblMenuEntries[roledefinition] = tblLinkroleUri break self.tablesMenu.delete(0, self.tablesMenuLength) self.tablesMenuLength = 0 self.tblELR = None for tblMenuEntry in sorted(tblMenuEntries.items()): tbl, elr = tblMenuEntry self.tablesMenu.add_command( label=tbl, command=lambda e=elr: self.view(viewTblELR=e)) self.tablesMenuLength += 1 if self.tblELR is None: self.tblELR = elr # start viewing first ELR def viewReloadDueToMenuAction(self, *args): if not self.blockMenuEvents: # update config (config saved when exiting) self.options["ignoreDimValidity"] = self.ignoreDimValidity.get() self.options["xAxisChildrenFirst"] = self.xAxisChildrenFirst.get() self.options["yAxisChildrenFirst"] = self.yAxisChildrenFirst.get() self.view() def view(self, viewTblELR=None, newInstance=None): startedAt = time.time() self.blockMenuEvents += 1 if newInstance is not None: self.modelXbrl = newInstance # a save operation has created a new instance to use subsequently clearZchoices = False if viewTblELR: # specific table selection self.tblELR = viewTblELR clearZchoices = True else: # first or subsequenct reloading (language, dimensions, other change) clearZchoices = self.zOrdinateChoices is None if clearZchoices: # also need first time initialization self.loadTablesMenu( ) # load menus (and initialize if first time viewTblELR = self.tblELR if not self.tblELR: return # no table to display if clearZchoices: self.zOrdinateChoices = {} # remove old widgets self.viewFrame.clearGrid() tblAxisRelSet, xTopStructuralNode, yTopStructuralNode, zTopStructuralNode = resolveAxesStructure( self, viewTblELR) if tblAxisRelSet: #print("tbl hdr width rowHdrCols {0}".format(self.rowHdrColWidth)) self.gridTblHdr.tblHdrWraplength = 200 # to adjust dynamically during configure callbacks self.gridTblHdr.tblHdrLabel = \ gridHdr(self.gridTblHdr, 0, 0, (self.modelTable.genLabel(lang=self.lang, strip=True) or # use table label, if any self.roledefinition), anchor="nw", #columnspan=(self.dataFirstCol - 1), #rowspan=(self.dataFirstRow), wraplength=200) # in screen units #wraplength=sum(self.rowHdrColWidth)) # in screen units zAspects = defaultdict(set) self.zAxis(1, zTopStructuralNode, zAspects, clearZchoices) xStructuralNodes = [] self.xAxis(self.dataFirstCol, self.colHdrTopRow, self.colHdrTopRow + self.colHdrRows - 1, xTopStructuralNode, xStructuralNodes, self.xAxisChildrenFirst.get(), True, True) self.yAxis(1, self.dataFirstRow, yTopStructuralNode, self.yAxisChildrenFirst.get(), True, True) for fp in self.factPrototypes: # dereference prior facts if fp is not None: fp.clear() self.factPrototypes = [] self.bodyCells(self.dataFirstRow, yTopStructuralNode, xStructuralNodes, zAspects, self.yAxisChildrenFirst.get()) # data cells #print("body cells done") self.modelXbrl.profileStat("viewTable_" + os.path.basename(viewTblELR), time.time() - startedAt) #self.gridView.config(scrollregion=self.gridView.bbox(constants.ALL)) self.blockMenuEvents -= 1 def zAxis(self, row, zStructuralNode, zAspects, clearZchoices): if zStructuralNode is not None: gridBorder(self.gridColHdr, self.dataFirstCol, row, TOPBORDER, columnspan=2) gridBorder(self.gridColHdr, self.dataFirstCol, row, LEFTBORDER) gridBorder(self.gridColHdr, self.dataFirstCol, row, RIGHTBORDER, columnspan=2) label = zStructuralNode.header(lang=self.lang) hdr = gridHdr( self.gridColHdr, self.dataFirstCol, row, label, anchor="w", columnspan=2, wraplength=200, # in screen units objectId=zStructuralNode.objectId(), onClick=self.onClick) if zStructuralNode.choiceStructuralNodes: # combo box valueHeaders = [ ''.ljust(zChoiceStructuralNode.indent * 4) + # indent if nested choices (zChoiceStructuralNode.header(lang=self.lang) or '') for zChoiceStructuralNode in zStructuralNode.choiceStructuralNodes ] combobox = gridCombobox( self.gridColHdr, self.dataFirstCol + 2, row, values=valueHeaders, selectindex=zStructuralNode.choiceNodeIndex, columnspan=2, comboboxselected=self.onComboBoxSelected) combobox.zStructuralNode = zStructuralNode combobox.zChoiceOrdIndex = row - 1 combobox.objectId = hdr.objectId = zStructuralNode.objectId() gridBorder(self.gridColHdr, self.dataFirstCol + 3, row, RIGHTBORDER) if zStructuralNode.childStructuralNodes: for zStructuralNode in zStructuralNode.childStructuralNodes: self.zAxis(row + 1, zStructuralNode, zAspects, clearZchoices) else: # nested-nost element, aspects process inheritance for aspect in aspectModels[self.aspectModel]: for ruleAspect in aspectRuleAspects.get( aspect, (aspect, )): if zStructuralNode.hasAspect( ruleAspect ): #implies inheriting from other z axes if ruleAspect == Aspect.DIMENSIONS: for dim in (zStructuralNode.aspectValue( Aspect.DIMENSIONS) or emptyList): zAspects[dim].add(zStructuralNode) else: zAspects[ruleAspect].add(zStructuralNode) def onComboBoxSelected(self, *args): combobox = args[0].widget self.zOrdinateChoices[combobox.zStructuralNode._definitionNode] = \ combobox.zStructuralNode.choiceNodeIndex = combobox.valueIndex self.view() # redraw grid def xAxis(self, leftCol, topRow, rowBelow, xParentStructuralNode, xStructuralNodes, childrenFirst, renderNow, atTop): if xParentStructuralNode is not None: parentRow = rowBelow noDescendants = True rightCol = leftCol widthToSpanParent = 0 sideBorder = not xStructuralNodes if atTop and sideBorder and childrenFirst: gridBorder(self.gridColHdr, self.dataFirstCol, 1, LEFTBORDER, rowspan=self.dataFirstRow) for xStructuralNode in xParentStructuralNode.childStructuralNodes: if not xStructuralNode.isRollUp: noDescendants = False rightCol, row, width, leafNode = self.xAxis( leftCol, topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, # nested items before totals childrenFirst, childrenFirst, False) if row - 1 < parentRow: parentRow = row - 1 #if not leafNode: # rightCol -= 1 nonAbstract = not xStructuralNode.isAbstract if nonAbstract: width += 100 # width for this label, in screen units widthToSpanParent += width label = xStructuralNode.header( lang=self.lang, returnGenLabel=isinstance( xStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))) if childrenFirst: thisCol = rightCol sideBorder = RIGHTBORDER else: thisCol = leftCol sideBorder = LEFTBORDER if renderNow: columnspan = (rightCol - leftCol + (1 if nonAbstract else 0)) gridBorder(self.gridColHdr, leftCol, topRow, TOPBORDER, columnspan=columnspan) gridBorder(self.gridColHdr, leftCol, topRow, sideBorder, columnspan=columnspan, rowspan=(rowBelow - topRow + 1)) gridHdr( self.gridColHdr, leftCol, topRow, label if label else " ", anchor="center", columnspan=(rightCol - leftCol + (1 if nonAbstract else 0)), rowspan=(row - topRow + 1) if leafNode else 1, wraplength=width, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) if nonAbstract: for i, role in enumerate(self.colHdrNonStdRoles): gridBorder( self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, TOPBORDER) gridBorder( self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, sideBorder) gridHdr( self.gridColHdr, thisCol, self.dataFirstRow - len(self.colHdrNonStdRoles) + i, xStructuralNode.header(role=role, lang=self.lang), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) ''' was if self.colHdrDocRow: gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - 1 - self.rowHdrCodeCol, xStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) if self.colHdrCodeRow: gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, TOPBORDER) gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, sideBorder) gridHdr(self.gridColHdr, thisCol, self.dataFirstRow - 1, xStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code"), anchor="center", wraplength=100, # screen units objectId=xStructuralNode.objectId(), onClick=self.onClick) ''' gridBorder(self.gridColHdr, thisCol, self.dataFirstRow - 1, BOTTOMBORDER) xStructuralNodes.append(xStructuralNode) if nonAbstract: rightCol += 1 if renderNow and not childrenFirst: self.xAxis(leftCol + (1 if nonAbstract else 0), topRow + 1, rowBelow, xStructuralNode, xStructuralNodes, childrenFirst, True, False) # render on this pass leftCol = rightCol if atTop and sideBorder and not childrenFirst: gridBorder(self.gridColHdr, rightCol - 1, 1, RIGHTBORDER, rowspan=self.dataFirstRow) return (rightCol, parentRow, widthToSpanParent, noDescendants) def yAxis(self, leftCol, row, yParentStructuralNode, childrenFirst, renderNow, atLeft): if yParentStructuralNode is not None: nestedBottomRow = row if atLeft: gridBorder( self.gridRowHdr, self.rowHdrCols + len(self.rowHdrNonStdRoles ), # was: self.rowHdrDocCol + self.rowHdrCodeCol, self.dataFirstRow, RIGHTBORDER, rowspan=self.dataRows) gridBorder(self.gridRowHdr, 1, self.dataFirstRow + self.dataRows - 1, BOTTOMBORDER, columnspan=( self.rowHdrCols + len(self.rowHdrNonStdRoles) )) # was: self.rowHdrDocCol + self.rowHdrCodeCol)) for yStructuralNode in yParentStructuralNode.childStructuralNodes: if not yStructuralNode.isRollUp: nestRow, nextRow = self.yAxis( leftCol + 1, row, yStructuralNode, # nested items before totals childrenFirst, childrenFirst, False) isAbstract = ( yStructuralNode.isAbstract or (yStructuralNode.childStructuralNodes and not isinstance( yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord)))) isNonAbstract = not isAbstract label = yStructuralNode.header( lang=self.lang, returnGenLabel=isinstance( yStructuralNode.definitionNode, (ModelClosedDefinitionNode, ModelEuAxisCoord))) topRow = row if childrenFirst and isNonAbstract: row = nextRow if renderNow: columnspan = self.rowHdrCols - leftCol + 1 if isNonAbstract or nextRow == row else None gridBorder(self.gridRowHdr, leftCol, topRow, LEFTBORDER, rowspan=(nestRow - topRow + 1)) gridBorder( self.gridRowHdr, leftCol, topRow, TOPBORDER, columnspan=(1 if childrenFirst and nextRow > row else columnspan)) if childrenFirst and row > topRow: gridBorder(self.gridRowHdr, leftCol + 1, row, TOPBORDER, columnspan=(self.rowHdrCols - leftCol)) depth = yStructuralNode.depth gridHdr( self.gridRowHdr, leftCol, row, label if label is not None else " ", anchor=("w" if isNonAbstract or nestRow == row else "center"), columnspan=columnspan, rowspan=(nestRow - row if isAbstract else None), # wraplength is in screen units wraplength=(self.rowHdrColWidth[depth] if isAbstract else self.rowHdrWrapLength - sum(self.rowHdrColWidth[0:depth])), #minwidth=self.rowHdrColWidth[leftCol], minwidth=(16 if isNonAbstract and nextRow > topRow else None), objectId=yStructuralNode.objectId(), onClick=self.onClick) if isNonAbstract: for i, role in enumerate(self.rowHdrNonStdRoles): isCode = "code" in role docCol = self.dataFirstCol - len( self.rowHdrNonStdRoles) + i gridBorder(self.gridRowHdr, docCol, row, TOPBORDER) gridBorder(self.gridRowHdr, docCol, row, LEFTBORDER) gridHdr( self.gridRowHdr, docCol, row, yStructuralNode.header(role=role, lang=self.lang), anchor="c" if isCode else "w", wraplength=40 if isCode else 100, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) ''' was: if self.rowHdrDocCol: docCol = self.dataFirstCol - 1 - self.rowHdrCodeCol gridBorder(self.gridRowHdr, docCol, row, TOPBORDER) gridBorder(self.gridRowHdr, docCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, docCol, row, yStructuralNode.header(role="http://www.xbrl.org/2008/role/documentation", lang=self.lang), anchor="w", wraplength=100, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) if self.rowHdrCodeCol: codeCol = self.dataFirstCol - 1 gridBorder(self.gridRowHdr, codeCol, row, TOPBORDER) gridBorder(self.gridRowHdr, codeCol, row, LEFTBORDER) gridHdr(self.gridRowHdr, codeCol, row, yStructuralNode.header(role="http://www.eurofiling.info/role/2010/coordinate-code"), anchor="center", wraplength=40, # screen units objectId=yStructuralNode.objectId(), onClick=self.onClick) # gridBorder(self.gridRowHdr, leftCol, self.dataFirstRow - 1, BOTTOMBORDER) ''' if isNonAbstract: row += 1 elif childrenFirst: row = nextRow if nestRow > nestedBottomRow: nestedBottomRow = nestRow + (isNonAbstract and not childrenFirst) if row > nestedBottomRow: nestedBottomRow = row #if renderNow and not childrenFirst: # dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, True, False) # render on this pass if not childrenFirst: dummy, row = self.yAxis(leftCol + 1, row, yStructuralNode, childrenFirst, renderNow, False) # render on this pass return (nestedBottomRow, row) def bodyCells(self, row, yParentStructuralNode, xStructuralNodes, zAspects, yChildrenFirst): if yParentStructuralNode is not None: rendrCntx = getattr(self.modelXbrl, "rendrCntx", None) # none for EU 2010 tables dimDefaults = self.modelXbrl.qnameDimensionDefaults for yStructuralNode in yParentStructuralNode.childStructuralNodes: if yChildrenFirst: row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspects, yChildrenFirst) if not yStructuralNode.isAbstract: yAspects = defaultdict(set) for aspect in aspectModels[self.aspectModel]: for ruleAspect in aspectRuleAspects.get( aspect, (aspect, )): if yStructuralNode.hasAspect(ruleAspect): if ruleAspect == Aspect.DIMENSIONS: for dim in (yStructuralNode.aspectValue( Aspect.DIMENSIONS) or emptyList): yAspects[dim].add(yStructuralNode) else: yAspects[ruleAspect].add(yStructuralNode) gridSpacer(self.gridBody, self.dataFirstCol, row, LEFTBORDER) # data for columns of row ignoreDimValidity = self.ignoreDimValidity.get() for i, xStructuralNode in enumerate(xStructuralNodes): xAspects = defaultdict(set) for aspect in aspectModels[self.aspectModel]: for ruleAspect in aspectRuleAspects.get( aspect, (aspect, )): if xStructuralNode.hasAspect(ruleAspect): if ruleAspect == Aspect.DIMENSIONS: for dim in ( xStructuralNode.aspectValue( Aspect.DIMENSIONS) or emptyList): xAspects[dim].add(xStructuralNode) else: xAspects[ruleAspect].add( xStructuralNode) cellAspectValues = {} matchableAspects = set() for aspect in _DICT_SET(xAspects.keys()) | _DICT_SET( yAspects.keys()) | _DICT_SET(zAspects.keys()): aspectValue = inheritedAspectValue( self, aspect, xAspects, yAspects, zAspects, xStructuralNode, yStructuralNode) if dimDefaults.get( aspect ) != aspectValue: # don't include defaulted dimensions cellAspectValues[aspect] = aspectValue matchableAspects.add( aspectModelAspect.get(aspect, aspect) ) #filterable aspect from rule aspect cellDefaultedDims = _DICT_SET(dimDefaults) - _DICT_SET( cellAspectValues.keys()) priItemQname = cellAspectValues.get(Aspect.CONCEPT) concept = self.modelXbrl.qnameConcepts.get( priItemQname) conceptNotAbstract = concept is None or not concept.isAbstract from arelle.ValidateXbrlDimensions import isFactDimensionallyValid value = None objectId = None justify = None fp = FactPrototype(self, cellAspectValues) if conceptNotAbstract: # reduce set of matchable facts to those with pri item qname and have dimension aspects facts = self.modelXbrl.factsByQname[ priItemQname] if priItemQname else self.modelXbrl.factsInInstance for aspect in matchableAspects: # trim down facts with explicit dimensions match or just present if isinstance(aspect, QName): aspectValue = cellAspectValues.get( aspect, None) if isinstance(aspectValue, ModelDimensionValue): if aspectValue.isExplicit: dimMemQname = aspectValue.memberQname # match facts with this explicit value else: dimMemQname = None # match facts that report this dimension elif isinstance(aspectValue, QName): dimMemQname = aspectValue # match facts that have this explicit value else: dimMemQname = None # match facts that report this dimension facts = facts & self.modelXbrl.factsByDimMemQname( aspect, dimMemQname) for fact in facts: if (all( aspectMatches(rendrCntx, fact, fp, aspect) for aspect in matchableAspects) and all( fact.context.dimMemberQname( dim, includeDefaults=True) in ( dimDefaults[dim], None) for dim in cellDefaultedDims)): if yStructuralNode.hasValueExpression( xStructuralNode): value = yStructuralNode.evalValueExpression( fact, xStructuralNode) else: value = fact.effectiveValue objectId = fact.objectId() justify = "right" if fact.isNumeric else "left" break if (conceptNotAbstract and (value is not None or ignoreDimValidity or isFactDimensionallyValid(self, fp))): if objectId is None: objectId = "f{0}".format( len(self.factPrototypes)) self.factPrototypes.append( fp) # for property views gridCell( self.gridBody, self.dataFirstCol + i, row, value, justify=justify, width= 12, # width is in characters, not screen units objectId=objectId, onClick=self.onClick) else: fp.clear() # dereference gridSpacer(self.gridBody, self.dataFirstCol + i, row, CENTERCELL) gridSpacer(self.gridBody, self.dataFirstCol + i, row, RIGHTBORDER) gridSpacer(self.gridBody, self.dataFirstCol + i, row, BOTTOMBORDER) row += 1 if not yChildrenFirst: row = self.bodyCells(row, yStructuralNode, xStructuralNodes, zAspects, yChildrenFirst) return row def onClick(self, event): objId = event.widget.objectId if objId and objId[0] == "f": viewableObject = self.factPrototypes[int(objId[1:])] else: viewableObject = objId self.modelXbrl.viewModelObject(viewableObject) def cellEnter(self, *args): self.blockSelectEvent = 0 def cellLeave(self, *args): self.blockSelectEvent = 1 def cellSelect(self, *args): if self.blockSelectEvent == 0 and self.blockViewModelObject == 0: self.blockViewModelObject += 1 #self.modelXbrl.viewModelObject(self.nodeToObjectId[self.treeView.selection()[0]]) #self.modelXbrl.viewModelObject(self.treeView.selection()[0]) self.blockViewModelObject -= 1 def viewModelObject(self, modelObject): if self.blockViewModelObject == 0: self.blockViewModelObject += 1 ''' try: if isinstance(modelObject, ModelObject.ModelRelationship): conceptId = modelObject.toModelObject.objectId() elif isinstance(modelObject, ModelObject.ModelFact): conceptId = self.modelXbrl.qnameConcepts[modelObject.qname].objectId() else: conceptId = modelObject.objectId() #node = self.objectIdToNode[conceptId] node = conceptId if self.treeView.exists(node): self.treeView.see(node) self.treeView.selection_set(node) except KeyError: self.treeView.selection_set(()) ''' self.blockViewModelObject -= 1 def saveInstance(self): if (not self.newFactItemOptions.entityIdentScheme or # not initialized yet not self.newFactItemOptions.entityIdentValue or not self.newFactItemOptions.startDateDate or not self.newFactItemOptions.endDateDate): if not getNewFactItemOptions(self.modelXbrl.modelManager.cntlr, self.newFactItemOptions): return # new instance not set newFilename = None # only used when a new instance must be created if self.modelXbrl.modelDocument.type != ModelDocument.Type.INSTANCE: newFilename = self.modelXbrl.modelManager.cntlr.fileSave( view=self, fileType="xbrl") if not newFilename: return # saving cancelled # continue saving in background thread = threading.Thread( target=lambda: self.backgroundSaveInstance(newFilename)) thread.daemon = True thread.start() def backgroundSaveInstance(self, newFilename=None): cntlr = self.modelXbrl.modelManager.cntlr if newFilename: self.modelXbrl.modelManager.showStatus( _("creating new instance {0}").format( os.path.basename(newFilename))) self.modelXbrl.modelManager.cntlr.waitForUiThreadQueue( ) # force status update self.modelXbrl.createInstance( newFilename ) # creates an instance as this modelXbrl's entrypoing instance = self.modelXbrl cntlr.showStatus( _("Saving {0}").format(instance.modelDocument.basename)) cntlr.waitForUiThreadQueue() # force status update newCntx = ModelXbrl.AUTO_LOCATE_ELEMENT newUnit = ModelXbrl.AUTO_LOCATE_ELEMENT # check user keyed changes for bodyCell in self.gridBody.winfo_children(): if isinstance(bodyCell, gridCell) and bodyCell.isChanged: value = bodyCell.value objId = bodyCell.objectId if objId: if objId[0] == "f": factPrototypeIndex = int(objId[1:]) factPrototype = self.factPrototypes[factPrototypeIndex] concept = factPrototype.concept entityIdentScheme = self.newFactItemOptions.entityIdentScheme entityIdentValue = self.newFactItemOptions.entityIdentValue periodType = factPrototype.concept.periodType periodStart = self.newFactItemOptions.startDateDate if periodType == "duration" else None periodEndInstant = self.newFactItemOptions.endDateDate qnameDims = factPrototype.context.qnameDims prevCntx = instance.matchContext( entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, qnameDims, [], []) if prevCntx is not None: cntxId = prevCntx.id else: # need new context newCntx = instance.createContext( entityIdentScheme, entityIdentValue, periodType, periodStart, periodEndInstant, concept.qname, qnameDims, [], [], afterSibling=newCntx) cntxId = newCntx.id # new context if concept.isNumeric: if concept.isMonetary: unitMeasure = qname( XbrlConst.iso4217, self.newFactItemOptions.monetaryUnit) unitMeasure.prefix = "iso4217" # want to save with a recommended prefix decimals = self.newFactItemOptions.monetaryDecimals elif concept.isShares: unitMeasure = XbrlConst.qnXbrliShares decimals = self.newFactItemOptions.nonMonetaryDecimals else: unitMeasure = XbrlConst.qnXbrliPure decimals = self.newFactItemOptions.nonMonetaryDecimals prevUnit = instance.matchUnit([unitMeasure], []) if prevUnit is not None: unitId = prevUnit.id else: newUnit = instance.createUnit( [unitMeasure], [], afterSibling=newUnit) unitId = newUnit.id attrs = [("contextRef", cntxId)] if concept.isNumeric: attrs.append(("unitRef", unitId)) attrs.append(("decimals", decimals)) value = Locale.atof(self.modelXbrl.locale, value, str.strip) newFact = instance.createFact(concept.qname, attributes=attrs, text=value) bodyCell.objectId = newFact.objectId( ) # switch cell to now use fact ID if self.factPrototypes[factPrototypeIndex] is not None: self.factPrototypes[factPrototypeIndex].clear() self.factPrototypes[ factPrototypeIndex] = None #dereference fact prototype else: # instance fact, not prototype fact = self.modelXbrl.modelObject(objId) if fact.concept.isNumeric: value = Locale.atof(self.modelXbrl.locale, value, str.strip) if fact.value != value: fact.text = value XmlValidate.validate(instance, fact) bodyCell.isChanged = False # clear change flag instance.saveInstance() cntlr.showStatus(_("Saved {0}").format( instance.modelDocument.basename), clearAfter=3000)
class GrepDialog(SearchDialogBase): "Dialog for searching multiple files." title = "Find in Files Dialog" icon = "Grep" needwrapbutton = 0 def __init__(self, root, engine, flist): """Create search dialog for searching for a phrase in the file system. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: globvar: Value of Text Entry widget for path to search. recvar: Boolean value of Checkbutton widget for traversing through subdirectories. """ SearchDialogBase.__init__(self, root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root) def open(self, text, searchphrase, io=None): "Make dialog visible on top of others and ready to use." SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail)) def create_entries(self): "Create base entry widgets and add widget for search path." SearchDialogBase.create_entries(self) self.globent = self.make_entry("In files:", self.globvar)[0] def create_other_buttons(self): "Add check button to recurse down subdirectories." btn = Checkbutton( self.make_frame()[0], variable=self.recvar, text="Recurse down subdirectories") btn.pack(side="top", fill="both") def create_command_buttons(self): "Create base command buttons and add button for search." SearchDialogBase.create_command_buttons(self) self.make_button("Search Files", self.default_command, 1) def default_command(self, event=None): """Grep for search pattern in file path. The default command is bound to <Return>. If entry values are populated, set OutputWindow as stdout and perform search. The search dialog is closed automatically when the search begins. """ prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.outwin import OutputWindow # leave here! save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save def grep_it(self, prog, path): """Search for prog within the lines of the files in path. For the each file in the path directory, open the file and search each line for the matching pattern. If the pattern is found, write the file and line information to stdout (which is an OutputWindow). """ dir, base = os.path.split(path) list = self.findfiles(dir, base, self.recvar.get()) list.sort() self.close() pat = self.engine.getpat() print(f"Searching {pat!r} in {path} ...") hits = 0 try: for fn in list: try: with open(fn, errors='replace') as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write(f"{fn}: {lineno}: {line}\n") hits += 1 except OSError as msg: print(msg) print(f"Hits found: {hits}\n(Hint: right-click to open locations.)" if hits else "No hits.") except AttributeError: # Tk window has been closed, OutputWindow.text = None, # so in OW.write, OW.text.insert fails. pass def findfiles(self, dir, base, rec): """Return list of files in the dir that match the base pattern. If rec is True, recursively iterate through subdirectories. """ try: names = os.listdir(dir or os.curdir) except OSError as msg: print(msg) return [] list = [] subdirs = [] for name in names: fn = os.path.join(dir, name) if os.path.isdir(fn): subdirs.append(fn) else: if fnmatch.fnmatch(name, base): list.append(fn) if rec: for subdir in subdirs: list.extend(self.findfiles(subdir, base, rec)) return list
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) super().__init__() self.parent = parent self.pack(fill=BOTH, expand=1) self.centerWindow() self.initUI() def centerWindow(self): w = 300 h = 380 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y)) def initUI(self): # self.master.title('Выберите параметры для анализа') self.pack(fill=BOTH, expand=True) #self.var = BooleanVar() self.parent.title('Выберите параметры для анализа') #self.style = Style() #self.style.theme_use("default") #names = ['Выравнивание абзаца', 'Отступ перед абзацем(см)', 'Отступ после абзаца(см)', 'Отступ слева(см)', # 'Отступ справа(см)', 'Отступ первой строки абзаца(см)', 'Не отрывать от следующего абзаца', # 'Не разрывать абзац', 'Абзац с новой страницы', 'Запрет висячих строк', 'Курсивный текст', # 'Полужирный текст', 'Подчёркнутый текст', 'Название шрифта', 'Размер шрифта(кегль)', # 'Цвет текста, RGB', 'Цвет заливки текста', 'Начать анализ'] self.var1 = BooleanVar() cb1 = Checkbutton(self, text='Выравнивание абзаца', variable=self.var1) cb1.place(x=20, y=20) self.var2 = BooleanVar() cb1 = Checkbutton(self, text='Отступ перед абзацем(см)', variable=self.var2) cb1.place(x=20, y=40) self.var3 = BooleanVar() cb1 = Checkbutton(self, text='Отступ после абзаца(см)', variable=self.var3) cb1.place(x=20, y=60) self.var4 = BooleanVar() cb1 = Checkbutton(self, text='Отступ слева(см)', variable=self.var4) cb1.place(x=20, y=80) self.var5 = BooleanVar() cb1 = Checkbutton(self, text='Отступ справа(см)', variable=self.var5) cb1.place(x=20, y=100) self.var6 = BooleanVar() cb1 = Checkbutton(self, text='Отступ первой строки абзаца(см)', variable=self.var6) cb1.place(x=20, y=120) self.var7 = BooleanVar() cb1 = Checkbutton(self, text='Не отрывать от следующего абзаца', variable=self.var7) cb1.place(x=20, y=140) self.var8 = BooleanVar() cb1 = Checkbutton(self, text='Не разрывать абзац', variable=self.var8) cb1.place(x=20, y=160) self.var9 = BooleanVar() cb1 = Checkbutton(self, text='Абзац с новой страницы', variable=self.var9) cb1.place(x=20, y=180) self.var10 = BooleanVar() cb1 = Checkbutton(self, text='Запрет висячих строк', variable=self.var10) cb1.place(x=20, y=200) self.var11 = BooleanVar() cb1 = Checkbutton(self, text='Курсивный текст', variable=self.var11) cb1.place(x=20, y=220) self.var12 = BooleanVar() cb1 = Checkbutton(self, text='Полужирный текст', variable=self.var12) cb1.place(x=20, y=240) self.var13 = BooleanVar() cb1 = Checkbutton(self, text='Подчёркнутый текст', variable=self.var13) cb1.place(x=20, y=260) self.var14 = BooleanVar() cb1 = Checkbutton(self, text='Название шрифта', variable=self.var14) cb1.place(x=20, y=280) self.var15 = BooleanVar() cb1 = Checkbutton(self, text='Размер шрифта(кегль)', variable=self.var15) cb1.place(x=20, y=300) self.var16 = BooleanVar() cb1 = Checkbutton(self, text='Цвет текста, RGB', variable=self.var16) cb1.place(x=20, y=320) self.var17 = BooleanVar() cb1 = Checkbutton(self, text='Цвет заливки текста', variable=self.var17) cb1.place(x=20, y=340) self.var18 = BooleanVar() #cb[i] = Checkbutton(self, text=names[i], variable=self.var, command=self.onClick) #cb1.place(x=50, y=50) self.pack(fill=BOTH, expand=1) quitButton = Button(self, text='Начать анализ', command=self.quit) quitButton.place(x=200, y=200) print(self.var1.get()) print(self.var2.get()) print(self.var3.get()) print(self.var4.get()) print(self.var5.get()) print(self.var6.get()) print(self.var7.get()) print(self.var8.get()) print(self.var9.get()) print(self.var10.get()) print(self.var11.get()) print(self.var12.get()) print(self.var13.get()) print(self.var14.get()) print(self.var15.get()) print(self.var16.get()) print(self.var17.get())
def run(self): root = Tk() icon_path = path.join(path.dirname(path.abspath(__file__)), "./logo.png") root.iconphoto(True, PhotoImage(file=icon_path)) root.title("VirxEC/VirxERLU") root.geometry("255x250") title = ttk.Label(root, text=f"{self.agent.name} hosted by VirxERLU") title.pack() author = ttk.Label(root, text=f"Bot by BotMaker (BotMaker/githubRepo)") author.pack() # Disable driving drive_bool = BooleanVar() drive_bool.set(self.agent.disable_driving) def set_drive(): self.agent.disable_driving = drive_bool.get() drive_btn = ttk.Checkbutton(root, text='Disable driving', variable=drive_bool, command=set_drive) drive_btn.pack() # Debugging debug_bool = BooleanVar() debug_bool.set(self.agent.debugging) def set_debug(): self.agent.debugging = debug_bool.get() debug_btn = ttk.Checkbutton(root, text='Debugging', variable=debug_bool, command=set_debug) debug_btn.pack() # Debug 2D debug_2d_bool = BooleanVar() debug_2d_bool.set(self.agent.debug_2d_bool) def set_debug_2d(): self.agent.debug_2d_bool = debug_2d_bool.get() debug_2d = ttk.Checkbutton(root, text='Debug 2D', variable=debug_2d_bool, command=set_debug_2d) debug_2d.pack() # Location show_coords_bool = BooleanVar() show_coords_bool.set(self.agent.show_coords) def set_show_coords(): self.agent.show_coords = show_coords_bool.get() show_coords_btn = ttk.Checkbutton(root, text='Show Car Info (2D/Lines)', variable=show_coords_bool, command=set_show_coords) show_coords_btn.pack() # Debug 3D debug_3d_bool = BooleanVar() debug_3d_bool.set(self.agent.debug_3d_bool) def set_debug_3d(): self.agent.debug_3d = debug_3d_bool.get() debug_3d = ttk.Checkbutton(root, text='Debug 3D', variable=debug_3d_bool, command=set_debug_3d) debug_3d.pack() # Debug Stack debug_stack_bool = BooleanVar() debug_stack_bool.set(self.agent.debug_stack_bool) def set_debug_stack(): self.agent.debug_stack_bool = debug_stack_bool.get() debug_stack = ttk.Checkbutton(root, text='Debug Stack (3D)', variable=debug_stack_bool, command=set_debug_stack) debug_stack.pack() # Debug Lines debug_lines_bool = BooleanVar() debug_lines_bool.set(self.agent.debug_lines) def set_debug_lines(): self.agent.debug_lines = debug_lines_bool.get() debug_lines = ttk.Checkbutton(root, text='Debug Lines', variable=debug_lines_bool, command=set_debug_lines) debug_lines.pack() # Debug ball prediction debug_ball_path_bool = BooleanVar() debug_ball_path_bool.set(self.agent.debug_ball_path) def set_debug_ball_path(): self.agent.debug_ball_path = debug_ball_path_bool.get() debug_ball_path = ttk.Checkbutton(root, text='Debug Ball Path (Lines)', variable=debug_ball_path_bool, command=set_debug_ball_path) debug_ball_path.pack() # Debug ball prediction precision debug_ball_path_precision_str = StringVar() debug_ball_path_precision_str.set( "Precision: " + str(self.agent.debug_ball_path_precision)) debug_ball_path_precision_label = ttk.Label( root, textvariable=debug_ball_path_precision_str) debug_ball_path_precision_label.pack() def set_debug_ball_path_precision(value): value = round(float(value)) self.agent.debug_ball_path_precision = value debug_ball_path_precision_str.set("Precision: " + str(value)) debug_ball_path_precision = ttk.Scale( root, orient=HORIZONTAL, from_=2, to=20, command=set_debug_ball_path_precision) debug_ball_path_precision.set(self.agent.debug_ball_path_precision) debug_ball_path_precision.pack() self.stop = root.destroy try: root.mainloop() except Exception: print_exc()