def check_tkvar(val: tk.Variable, allow_blank: bool = False): """Returns True if calling ``val.get()`` doesn't raise `TclError`.""" try: val.get() return True except tk.TclError: # noinspection PyProtectedMember if allow_blank and not val._tk.globalgetvar(val._name).strip(): return True else: return False
class Prop: def __init__(self, initialValue=None, callback=None): self._var = Variable(value=initialValue) if callback is not None: self._var.trace(mode='w', callback=callback) def get(self): return self._var.get() def set(self, value): self._var.set(value) def on_change(self, listener): def update(*dummy): listener(self._var.get()) self._var.trace('w', update)
def wrap_cls(_unit: Variable, amount: Variable) -> str: unit = _unit.get() if unit in size_units: return size_units[unit].__name__ + f'({amount.get()})' elif unit in time_units: return time_units[unit].__name__ + f'({amount.get()})' else: raise NotImplementedError
def test_variable(self): self.assertRaises(RuntimeError, Variable) root = tkinter.Tk() v = Variable() v.set("value") self.assertEqual(v.get(), "value") root.destroy() tkinter.NoDefaultRoot() self.assertRaises(RuntimeError, Variable)
def _update_fromvar(self, key: str, var: tk.Variable, *unused): # OptionMenu gives us the changes as positional argument, # but Checkbutton doesn't # This function streamline the process of getting the value, # and thus *args is here to catch some additional unused parameters conf = {} conf[key] = var.get() self._update_config(**conf)
def __init__(self, master: tk_gui.VariableListFrame, values: Union[data.ValueRange, Tuple], variable: tk.Variable, text: str, width=650, execute: Optional[callable] = None): super().__init__(master) # basic behaviour and layout self.transient(master) self.protocol('WM_DELETE_WINDOW', self._on_close) self.grab_set() self.config(background='white') # Label and Title self.title = 'Set Value' ttk.Label(self, text=text).pack() # Variable change widget if isinstance(values, data.ValueRange): tk.Scale(master=self, from_=values.min, to=values.max, resolution=values.step or (values.max - values.min) / 100, orient=tk.HORIZONTAL, variable=variable, length=width, background='white').pack() else: ttk.Combobox(master=self, textvariable=variable, values=values, background='white').pack() self.variable = variable self.original_value = variable.get() # Button(s) button_frame = ttk.Frame(self) button_frame.pack() if execute: @tk_gui.message_box_on_error def command_ok(): self.destroy() self.grab_release() execute(variable.get()) else: command_ok = self.destroy ttk.Button(button_frame, text='Done', command=command_ok) \ .grid(row=0, column=1, padx=30, pady=10) ttk.Button(button_frame, text='Cancel', command=self._on_close) \ .grid(row=0, column=0)
class OptionMenuComponent(MediatorComponent): """WidgetMediator component that contains an OptionMenu """ # Private Attributes: # - _var: the external mutatable variable for the menu widget # - _om: the OptionMenu shown to the user that displays the selection # - _mediator: the mediator to notify a selection has been made to update other colleages _var: Variable _om: OptionMenu _mediator: MenuMediator def __init__(self, parent: Widget, mediator: MenuMediator) -> None: self._var = Variable() self._mediator = mediator self._om = OptionMenu(parent, self._var, "") def reset_selection(self) -> None: """Sets the option menu variable to an empty string""" self._var.set("") def set_selection(self, data: list) -> None: """Sets the OptionMenu options to data""" menu = self._om["menu"] _delete_menu_options(menu) def click_command(variable: Variable, opt: Any) -> Callable: """Return the command to be called when clicking an option item""" def wrapper() -> None: """Function called when clicking an option item""" variable.set(opt) self._mediator.update_selection(()) return wrapper data = sorted(set(data)) menu.add_command(label="", command=click_command(self._var, "")) for option in data: menu.add_command(label=option, command=click_command(self._var, option)) def get_widget(self) -> Widget: """Return a list containing this OptionMenu""" return self._om def configure_menu(self, config: str, value: str) -> None: """Configures the setting of the composed dOptionMenu""" self._om[config] = value def get_selected(self) -> Any: """Return the current variable's value""" return self._var.get()
def tkVariable(var: Variable, key: str, default=None): """ 将tkinter的var绑定到缓存 :param var: :param key: :param default: :return: """ _cache = cache.get(key, default=None) if _cache is None: if default is not None: var.set(default) else: var.set(_cache) var.trace('w', lambda a, b, c: cache.set(key, var.get()))
def test_trace_old(self): # Old interface v = Variable(self.root) vname = str(v) trace = [] def read_tracer(*args): trace.append(('read', ) + args) def write_tracer(*args): trace.append(('write', ) + args) cb1 = v.trace_variable('r', read_tracer) cb2 = v.trace_variable('wu', write_tracer) self.assertEqual(sorted(v.trace_vinfo()), [('r', cb1), ('wu', cb2)]) self.assertEqual(trace, []) v.set('spam') self.assertEqual(trace, [('write', vname, '', 'w')]) trace = [] v.get() self.assertEqual(trace, [('read', vname, '', 'r')]) trace = [] info = sorted(v.trace_vinfo()) v.trace_vdelete('w', cb1) # Wrong mode self.assertEqual(sorted(v.trace_vinfo()), info) with self.assertRaises(TclError): v.trace_vdelete('r', 'spam') # Wrong command name self.assertEqual(sorted(v.trace_vinfo()), info) v.trace_vdelete('r', (cb1, 43)) # Wrong arguments self.assertEqual(sorted(v.trace_vinfo()), info) v.get() self.assertEqual(trace, [('read', vname, '', 'r')]) trace = [] v.trace_vdelete('r', cb1) self.assertEqual(v.trace_vinfo(), [('wu', cb2)]) v.get() self.assertEqual(trace, []) trace = [] del write_tracer gc.collect() v.set('eggs') self.assertEqual(trace, [('write', vname, '', 'w')]) trace = [] del v gc.collect() self.assertEqual(trace, [('write', vname, '', 'u')])
def test_trace(self): v = Variable(self.root) vname = str(v) trace = [] def read_tracer(*args): trace.append(('read', ) + args) def write_tracer(*args): trace.append(('write', ) + args) tr1 = v.trace_add('read', read_tracer) tr2 = v.trace_add(['write', 'unset'], write_tracer) self.assertEqual(sorted(v.trace_info()), [(('read', ), tr1), (('write', 'unset'), tr2)]) self.assertEqual(trace, []) v.set('spam') self.assertEqual(trace, [('write', vname, '', 'write')]) trace = [] v.get() self.assertEqual(trace, [('read', vname, '', 'read')]) trace = [] info = sorted(v.trace_info()) v.trace_remove('write', tr1) # Wrong mode self.assertEqual(sorted(v.trace_info()), info) with self.assertRaises(TclError): v.trace_remove('read', 'spam') # Wrong command name self.assertEqual(sorted(v.trace_info()), info) v.get() self.assertEqual(trace, [('read', vname, '', 'read')]) trace = [] v.trace_remove('read', tr1) self.assertEqual(v.trace_info(), [(('write', 'unset'), tr2)]) v.get() self.assertEqual(trace, []) trace = [] del write_tracer gc.collect() v.set('eggs') self.assertEqual(trace, [('write', vname, '', 'write')]) trace = [] del v gc.collect() self.assertEqual(trace, [('write', vname, '', 'unset')])
def test_trace_old(self): # Old interface v = Variable(self.root) vname = str(v) trace = [] def read_tracer(*args): trace.append(('read',) + args) def write_tracer(*args): trace.append(('write',) + args) cb1 = v.trace_variable('r', read_tracer) cb2 = v.trace_variable('wu', write_tracer) self.assertEqual(sorted(v.trace_vinfo()), [('r', cb1), ('wu', cb2)]) self.assertEqual(trace, []) v.set('spam') self.assertEqual(trace, [('write', vname, '', 'w')]) trace = [] v.get() self.assertEqual(trace, [('read', vname, '', 'r')]) trace = [] info = sorted(v.trace_vinfo()) v.trace_vdelete('w', cb1) # Wrong mode self.assertEqual(sorted(v.trace_vinfo()), info) with self.assertRaises(TclError): v.trace_vdelete('r', 'spam') # Wrong command name self.assertEqual(sorted(v.trace_vinfo()), info) v.trace_vdelete('r', (cb1, 43)) # Wrong arguments self.assertEqual(sorted(v.trace_vinfo()), info) v.get() self.assertEqual(trace, [('read', vname, '', 'r')]) trace = [] v.trace_vdelete('r', cb1) self.assertEqual(v.trace_vinfo(), [('wu', cb2)]) v.get() self.assertEqual(trace, []) trace = [] del write_tracer gc.collect() v.set('eggs') self.assertEqual(trace, [('write', vname, '', 'w')]) trace = [] del v gc.collect() self.assertEqual(trace, [('write', vname, '', 'u')])
def test_trace(self): v = Variable(self.root) vname = str(v) trace = [] def read_tracer(*args): trace.append(('read',) + args) def write_tracer(*args): trace.append(('write',) + args) tr1 = v.trace_add('read', read_tracer) tr2 = v.trace_add(['write', 'unset'], write_tracer) self.assertEqual(sorted(v.trace_info()), [ (('read',), tr1), (('write', 'unset'), tr2)]) self.assertEqual(trace, []) v.set('spam') self.assertEqual(trace, [('write', vname, '', 'write')]) trace = [] v.get() self.assertEqual(trace, [('read', vname, '', 'read')]) trace = [] info = sorted(v.trace_info()) v.trace_remove('write', tr1) # Wrong mode self.assertEqual(sorted(v.trace_info()), info) with self.assertRaises(TclError): v.trace_remove('read', 'spam') # Wrong command name self.assertEqual(sorted(v.trace_info()), info) v.get() self.assertEqual(trace, [('read', vname, '', 'read')]) trace = [] v.trace_remove('read', tr1) self.assertEqual(v.trace_info(), [(('write', 'unset'), tr2)]) v.get() self.assertEqual(trace, []) trace = [] del write_tracer gc.collect() v.set('eggs') self.assertEqual(trace, [('write', vname, '', 'write')]) trace = [] del v gc.collect() self.assertEqual(trace, [('write', vname, '', 'unset')])
def test_name_and_value(self): v = Variable(self.root, "sample string", "varname") self.assertEqual("sample string", v.get()) self.assertEqual("varname", str(v))
def test_default(self): v = Variable(self.root) self.assertEqual("", v.get()) self.assertRegex(str(v), r"^PY_VAR(\d+)$")
def SaveVar(var: _TK.Variable, master=None, value=None, name=None, filename='data.pkl') \ -> (_TK.Variable): """Save tkinter variable data in a pickle file and load the same value when the program is executed next time. #### If the content of the file changes, it might not load correct values \ to the assigned variables. To avoid this issue use `name` to \ refer to the exact assigned values later. ### Args: - `var`: Give the `tkinter.Variable` class like (`tk.StringVar`, `tk.IntVar`). - `master`: Parent widget. - `value`: Set value. - `name`: Set a name to group variables or to refer to assigned value when loaded. - `filename`: Set the name of the save file. (To make the file invisible in the \ directory start the name of the file with "." like ".cache-savevar") ### Return: - returns the tk.Variable instance passed to `var` argument. ### Example: root = tk.Tk() var1 = SaveVar(tk.StringVar,'Enter Username','Var1','.cache-savevar') var2 = SaveVar(tk.StringVar,'Enter Password','Var2','.cache-savevar') tk.Entry(root,textvariable=var1).pack() tk.Entry(root,textvariable=var2).pack() root.mainloop()""" def update_val(*args): """Internal function for updating the value for variable""" try: # try/except , if the file doesn't exists. open1 = open(filename, 'rb') tmpdict = pkl.load(open1) # load saved dictionary data. # Block of code to check for the right value. if tmpdict.get(str(var)): old, default = tmpdict.get(str(var)) new = var.get() if new != default: var.set(new) elif new == default and not startup[0]: var.set(default) else: var.set(old) tmpdict.update({str(var): (var.get(), defaultval)}) open1.close() except Exception as e: tmpdict = {} tmpdict[str(var)] = (var.get(), defaultval) open2 = open(filename, 'wb') pkl.dump(tmpdict, open2) startup[0] = False open2.close() startup = [True] if not(filename.endswith('.pickle') or filename.endswith('.pkl')) \ and not filename.startswith('.'): filename = filename + '.pkl' var = var(master=master, value=value, name=name) defaultval = var.get() # get a default value of the variable update_val() for mode, cbname in (var.trace_info()): if mode[0] == 'write' and update_val.__name__ in cbname: try: var.trace_remove('write', cbname) except: pass res = var.trace_add('write', update_val) return var
def _forward_options(self, key: str, var: tk.Variable, *unused): option = {} option[key] = var.get() self.set_options(**option)
def test_name_and_value(self): v = Variable(self.root, 'sample string', 'varname') self.assertEqual('sample string', v.get()) self.assertEqual('varname', str(v))
def test_default(self): v = Variable(self.root) self.assertEqual('', v.get()) self.assertRegex(str(v), '^PY_VAR(\\d+)$')