def add_customer(self, event=None): # validate and show errors if self.fname.get() == '': showerror("Error!", "First name field blank!") elif self.lname.get() == '': showerror("Error!", "Last name field blank!") elif self.mname.get() == '': showerror("Error!", "Middle initial field blank!") elif self.payment.get() not in ("Drop In", "Punch Card", "Monthly", "Inactive"): showerror("Error!", "Incorect Customer type!") elif not re.compile(r'[01]?\d/[0123]?\d/[12]\d{1,3}').search(self.date.get()): showerror("Error!", "Bad entry for date, use format mm/dd/yyyy") else: # do work name = ' '.join([self.fname.get(),self.mname.get(),self.lname.get()]) old, row = self.customers.find(str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip()) new = [str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip(), str(self.payment.get()).strip(), datetime.strptime(self.date.get(), "%m/%d/%Y")] if not old: #add customer self.customers.add(new) self.output_text("+ - New Customer: " + name + " (" + self.payment.get() + ")\n") self.refresh() else: var = IntVar() diag = AlreadyExistsDialog(self.root, new, old, var) diag.show() if var.get() == 0: # edit pass if var.get() == 1: # replace customer self.customers.replace(row, new) self.output_text("+ - Modified: " + name + " (" + self.payment.get() + ")\n") self.refresh()
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, width=5, font=("Helvetica", 20, "bold italic"), textvariable=self.counter) self.label.pack(side="left") self.up = Button(root, text="up", background="RED", command=self.increment) self.up.pack(side="left") self.down = Button(root, text="down", background="GREEN", command=self.decrement) self.down.pack(side="left") def increment(self): self.counter.set(self.counter.get() + 1) def decrement(self): self.counter.set(max(0, self.counter.get() - 1))
def test_invalid_value(self): v = IntVar(self.root, name="name") self.root.globalsetvar("name", "value") with self.assertRaises(ValueError): v.get() self.root.globalsetvar("name", "345.0") with self.assertRaises(ValueError): v.get()
def test_invalid_value(self): v = IntVar(self.root, name='name') self.root.globalsetvar('name', 'value') with self.assertRaises(ValueError): v.get() self.root.globalsetvar('name', '345.0') with self.assertRaises(ValueError): v.get()
class MainApplication(tk.Frame): throttle = 0 steering = 0 mode = 0 myRobot = BROBOT() def draw(self): print "DRAW" def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent # GUI INIT: 2 sliders and 1 button self.t = tk.Scale(troughcolor="light yellow", from_=100, to=-100, width=40, length=200) self.t.pack(side=tk.LEFT, fill=tk.BOTH, expand=1) self.s = tk.Scale(troughcolor="light cyan", from_=-100, to=100, width=40, length=250, orient=tk.HORIZONTAL) self.s.pack(side=tk.LEFT, fill=tk.X) self.after(50, self.timer) self.b = tk.Button(bg="light green", repeatdelay=1, repeatinterval=50, width=10, height=2, text="SERVO", command=self.buttonCallback) self.b.pack(side=tk.LEFT) self.mode_control = IntVar() self.m = tk.Checkbutton(text="PRO MODE", variable=self.mode_control) self.m.pack() def buttonCallback(self): self.myRobot.servo(1) time.sleep(0.2) self.myRobot.servo(0) def timer(self): # Timer at 50ms interval to read slider values if (self.t.get() != self.throttle): self.throttle = self.t.get() self.myRobot.throttle(self.throttle / 100.0) #print "THROTTLE:",self.throttle if (self.s.get() != self.steering): self.steering = self.s.get() self.myRobot.steering(self.steering / 100.0) #print "STEERING:",self.steering if (self.mode_control.get() != self.mode): self.mode = self.mode_control.get() self.myRobot.mode(self.mode) #print "MODE:",self.mode self.after(50, self.timer)
def ask_multiple_choice_question(prompt, options): root = Tk() if prompt: Label(root, text=prompt).pack() v = IntVar() for i, option in enumerate(options): Radiobutton(root, text=option, variable=v, value=i).pack(anchor="w") Button(text="Submit", command=root.destroy).pack() root.mainloop() if v.get() == 0: return None return options[v.get()]
class SetDefaultPropertiesDlg(SKModal): title = _("Set Default Properties") def __init__(self, master, category): self.category = category SKModal.__init__(self, master, name='setdefaults') def build_dlg(self): root = self.top top = TFrame(root, style='FlatFrame', borderwidth=13) top.pack(side=TOP) label = TLabel(top, text=_("Please select the object categories whose\n default properties you want to change")) label.pack(side=TOP, anchor=W) frame = TFrame(top, style='FlatFrame', borderwidth=10) frame.pack(side=TOP) self.var_graphics_style = IntVar(top) self.var_graphics_style.set(0) if self.category != 'font': self.var_graphics_style.set(1) button = TCheckbutton(frame, text=_("Graphics Objects"), state=(self.category == 'font' and DISABLED or NORMAL), variable=self.var_graphics_style) button.pack(side=TOP, anchor=W) self.var_text_style = IntVar(top) self.var_text_style.set(0) if self.category == 'font': self.var_text_style.set(1) button = TCheckbutton(frame, text=_("Text Objects"), state=(self.category == 'line' and DISABLED or NORMAL), variable=self.var_text_style) button.pack(side=TOP, anchor=W) label = TLabel(top, style="HLine") label.pack(side=TOP, fill=BOTH) but_frame = TFrame(top, style='FlatFrame') but_frame.pack(side=TOP, fill=BOTH, expand=1) button = TButton(but_frame, text=_("Cancel"), command=self.cancel) button.pack(side=RIGHT, expand=1) button = TButton(but_frame, text=_("OK"), command=self.ok) button.pack(side=RIGHT, expand=1) root.resizable (width=0, height=0) def ok(self, *args): graph = self.var_graphics_style.get() text = self.var_text_style.get() self.close_dlg((graph, text))
class getDist(): def __init__(self, master): self.master = master self.startwindow() #self.b=0 # no need for this, directly store in the global variable def startwindow(self): self.var1 = IntVar() self.textvar = StringVar() self.Label1 = Label(self.master, text="Search distance (meters)") self.Label1.grid(row=0, column=0) self.Label2 = Label(self.master, textvariable=self.textvar) self.Label2.grid(row=2, column=0) self.rb1 = Radiobutton(self.master, text="5000", variable=self.var1, value=5000, command=self.cb1select) self.rb1.grid(row=1, column=0, sticky=W) self.rb2 = Radiobutton(self.master, text="625", variable=self.var1, value=625, command=self.cb1select) self.rb2.grid(row=1, column=1, sticky=W) self.rb3 = Radiobutton(self.master, text="160", variable=self.var1, value=160, command=self.cb1select) self.rb3.grid(row=1, column=2, sticky=W) self.Button1 = Button(self.master, text="ok", command=self.ButtonClick) self.Button1.grid(row=2, column=2) def ButtonClick(self): global dist dist = self.var1.get() self.master.quit() def cb1select(self): return self.var1.get()
class Interface(Frame): """界面操作""" def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.create_widgets() def create_widgets(self): """构建界面""" self.radio_value = IntVar() Label(self, text="网络安全").grid(row=0, column=2, pady=10) # 生成label Label(self, text="用户名").grid(row=3, column=1, pady=10) Label(self, text="密码").grid(row=4, column=1) # 生成用户名和密码输入框 self.name_input = Entry(self) self.name_input.grid(row=3, column=2) self.password = Entry(self) self.password['show'] = '*' self.password.grid(row=4, column=2) self.radio = Radiobutton(self, text="rsa", variable=self.radio_value, padx=20, value=1) self.radio.grid(row=5, column=1) self.radio1 = Radiobutton(self, text="des", variable=self.radio_value, padx=20, value=2) self.radio1.grid(row=6, column=1) self.alert_button = Button(self, text='提交', command=self.submit) self.alert_button.grid(row=7, column=1) def submit(self): """提交处理""" name = self.name_input.get() or 'username' password = self.password.get() or "password" cryption = self.radio_value.get() or "1" # 构造传输的数据 data = name + ',' + password cryption = Crypt() my_socket = Mysocket() # 判断使用des还是rsa if cryption == 2: data = "des" + data need = 8 - (len(data) % 8) while need > 0: data += " " need -= 1 result = cryption.des_encrypt(data) result = "des" + result else: result = cryption.rsa_encrypt(data) result = "rsa" + result result = my_socket.make_connect(result) if result >= 0: tkMessageBox.showinfo('Message', '%s' % '合法用户') else: tkMessageBox.showinfo('Message', '%s' % '非法用户')
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=1) self.var = IntVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=50) def onClick(self): if self.var.get() == 1: self.master.title("Checkbutton") else: self.master.title("")
class Transmitter(object): def __init__(self, sstv, root, progress): def encode_line_hooked(line): progress.update_image(line) return self.original_encode_line(line) self.progress = progress self.sstv = sstv self.original_encode_line = sstv.encode_line sstv.encode_line = encode_line_hooked self.root = root self.tx_enabled = IntVar() self.audio_thread = None self.stopping = False def start_stop_tx(self): if self.tx_enabled.get(): self.stopping = False self.audio_thread = AudioThread(self.sstv, self) self.audio_thread.start() else: self.stop() if self.progress is not None: self.progress.update_image() def stop(self): if self.audio_thread is not None: self.stopping = True self.audio_thread.stop() def audio_thread_ended(self): if not self.stopping: self.tx_enabled.set(0) def close(self): self.root.destroy()
class HiddenNeuronNumber(Frame): def __init__(self, parent, layer_id): Frame.__init__(self, parent) self.parent = parent # Layer id is a number in range(MAX_NUMBER_OF_HIDDEN_LAYERS) self.layer_id = layer_id label_text = 'Neurons for layer {0}: '.format(layer_id + 1) self.label = Label(self, text = label_text) self.label.grid(row=0, column=0) number_options = range(1, MAX_NEURON_NUMBER_PER_HIDDEN_LAYER + 1) self.selected_number = \ IntVar(self, value = DEFAULT_NEURON_NUMBER_PER_HIDDEN_LAYER) self.option_menu = OptionMenu(self, self.selected_number, \ *number_options) self.option_menu.grid(row=0, column=1) self.disable() def get(self): return self.selected_number.get() def enable(self): self.label.config(state = 'normal') self.option_menu.config(state = 'normal') def disable(self): self.label.config(state = 'disabled') self.option_menu.config(state = 'disabled')
class HiddenNeuronNumber(Frame): def __init__(self, parent, layer_id): Frame.__init__(self, parent) self.parent = parent # Layer id is a number in range(MAX_NUMBER_OF_HIDDEN_LAYERS) self.layer_id = layer_id label_text = 'Neurons for layer {0}: '.format(layer_id + 1) self.label = Label(self, text=label_text) self.label.grid(row=0, column=0) number_options = range(1, MAX_NEURON_NUMBER_PER_HIDDEN_LAYER + 1) self.selected_number = \ IntVar(self, value = DEFAULT_NEURON_NUMBER_PER_HIDDEN_LAYER) self.option_menu = OptionMenu(self, self.selected_number, \ *number_options) self.option_menu.grid(row=0, column=1) self.disable() def get(self): return self.selected_number.get() def enable(self): self.label.config(state='normal') self.option_menu.config(state='normal') def disable(self): self.label.config(state='disabled') self.option_menu.config(state='disabled')
class NumberOfClasses(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent number_of_classes_label = Label(self, text = 'Number of classes: ') number_of_classes_label.grid(row = 0, column = 0) number_options = range(DEFAULT_NUMBER_OF_CLASS, MAX_NUMBER_OF_CLASSES+1) self.selected_number = IntVar(self, value = DEFAULT_NUMBER_OF_CLASS) option_menu = OptionMenu(self, self.selected_number, *number_options, command = self._on_number_selection) option_menu.grid(row = 0, column = 1) self.observers = [] def register_observer(self, observer): self.observers.append(observer) def notify_observers(self, class_number): for observer in self.observers: observer.set_class_number(class_number) def _on_number_selection(self, selected_number): self.notify_observers(selected_number) def get(self): return self.selected_number.get() def reset(self): self.selected_number.set(DEFAULT_NUMBER_OF_CLASS)
class PasswordDialog(Dialog): def __init__(self, title, prompt, parent): self.prompt = prompt Dialog.__init__(self, parent, title) def body(self, master): from Tkinter import Label from Tkinter import Entry from Tkinter import Checkbutton from Tkinter import IntVar from Tkinter import W self.checkVar = IntVar() Label(master, text=self.prompt).grid(row=0, sticky=W) self.e1 = Entry(master) self.e1.grid(row=0, column=1) self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar) self.cb.pack() self.cb.grid(row=1, columnspan=2, sticky=W) self.configure(show='*') def apply(self): self.result = (self.e1.get(), self.checkVar.get() == 1)
class StarterWindow(Tk): def __init__(self): Tk.__init__(self) self.wm_title("FRCA QBase Reader - Start Menu") self.exambtn = Button(self, text="start an exam", command=self.startExam) self.exambtn.pack() self.maxquestvar = IntVar() self.maxquest = Spinbox(self, from_=1, to=1667, width=4, textvariable=self.maxquestvar) self.maxquest.pack() self.questbtn = Button(self, text="start single questions", command=self.startQuestions) self.questbtn.pack() self.um = """User manual:\n Start either an exam or single questions\n Go to next question either with mouse or the <right arrow>\n Toggle checkboxes either with mouse or <keyboard buttons 1-5>\n In single question mode, show answer either with mouse or <return>\n In exam mode, results will display after the set question number\n Text can be made bigger/smaller with <Up> or <Down> keyboard arrows""" self.usermanual = Label(self, text=self.um, justify=LEFT) self.usermanual.pack() def startExam(self): call(["python", "exam.py", str(self.maxquestvar.get())]) def startQuestions(self): call(["python", "quest_by_quest.py"])
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=1) self.var = IntVar() #We create an IntVar object. #It is a value holder for integer values for widgets in Tkinter. cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) #An instance of the Checkbutton is created. #The value holder is connected to the widget via the variable parameter. #When we click on the check button, the onClick() method is called. #This is done with the command parameter. cb.select() #Initially, the title is shown in the titlebar. #So at the start, we make it checked with the select() method. cb.place(x=50, y=50) def onClick(self): #Inside the onClick() method, we display or hide the title based on the value from the self.var variable. if self.var.get() == 1: self.master.title("Checkbutton") else: self.master.title("")
def input_input_checkbox(self, e): var = IntVar(master=self.frame) self.master.serialized[e.name] = lambda: var.get() and True or False if e.default is not None: var.set(e.default) w = Checkbutton(self.frame, text=self.compile_text(e.label), variable=var) self.pack_element(w)
class PasswordDialog(Dialog): def __init__(self, title, prompt, parent): self.prompt = prompt Dialog.__init__(self, parent, title) def body(self, master): from Tkinter import Label from Tkinter import Entry from Tkinter import Checkbutton from Tkinter import IntVar from Tkinter import W self.checkVar = IntVar() Label(master, text=self.prompt).grid(row=0, sticky=W) self.e1 = Entry(master) self.e1.grid(row=0, column=1) self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar) self.cb.pack() self.cb.grid(row=1, columnspan=2, sticky=W) self.e1.configure(show='*') def apply(self): self.result = (self.e1.get(), self.checkVar.get() == 1)
class waitWidget(Frame): # pylint: disable=R0924,R0904 """ A wait widget that shows something is happening. """ def __init__(self, queue, master): self.queue = queue Frame.__init__(self, master) self.pack(fill="both") self.focus_set() # get the focus self.grab_set() # make this window modal master.resizable(False, False) # not resizable master.title("") # no title # don't let user close window using X - instead call timer master.protocol("WM_DELETE_WINDOW", self.timer) self.wait = IntVar(master, 0, "wait") Label(master, bitmap="hourglass").pack(fill="both") Label(master, text="Please wait ...").pack(fill="both") Label(master, textvariable=self.wait).pack(fill="both") self.timer() def timer(self): """ A callback that counts milliseconds until SELF.QUEUE has somthing in it """ wait = self.wait.get() + 1 if not self.queue.empty(): # when queue is filled, quit loop and print elapsed time logging.debug('elapsed time = %2.1f [s]', wait * 0.10) self.quit() self.wait.set(wait) # loop over this callback every 100[ms] until queue is filled self.after(100, self.timer)
class NumberOfClasses(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent number_of_classes_label = Label(self, text='Number of classes: ') number_of_classes_label.grid(row=0, column=0) number_options = range(DEFAULT_NUMBER_OF_CLASS, MAX_NUMBER_OF_CLASSES + 1) self.selected_number = IntVar(self, value=DEFAULT_NUMBER_OF_CLASS) option_menu = OptionMenu(self, self.selected_number, *number_options, command=self._on_number_selection) option_menu.grid(row=0, column=1) self.observers = [] def register_observer(self, observer): self.observers.append(observer) def notify_observers(self, class_number): for observer in self.observers: observer.set_class_number(class_number) def _on_number_selection(self, selected_number): self.notify_observers(selected_number) def get(self): return self.selected_number.get() def reset(self): self.selected_number.set(DEFAULT_NUMBER_OF_CLASS)
def __init__(self, parent): self.parent = parent top = self.top = Toplevel(parent.root) Label(top, text="Secret Key(base32):").grid(columnspan=3) base32_key = Entry(top) base32_key.grid(row=1, column=0, columnspan=3) challenge_response_slot = IntVar() challenge_response_slot_widgets = ( Radiobutton( top, text='slot 1', variable=challenge_response_slot, value=1, ).grid(row=3, column=0), Radiobutton( top, text='slot 2', variable=challenge_response_slot, value=2, ).grid(row=3, column=1), ) require_button = IntVar() require_button_widget = Checkbutton(top, text='Button press required', variable=require_button, ).grid(row=2, columnspan=3) require_button.set(1) submit = Button(top, text="Program", command=lambda: self._program_confirm( challenge_response_slot.get(), base32_key.get(), require_button.get() ) ).grid(row=4, column=1) cancel = Button( top, text="Cancel", command=self._program_cancel ).grid(row=4, column=0)
class SetDefaultPropertiesDlg(SKModal): title = _("Set Default Properties") def __init__(self, master, category): self.category = category SKModal.__init__(self, master, name = 'setdefaults') def build_dlg(self): top = self.top label = Label(top, name = 'label', text = _("Please select the object categories whose " "default properties you want to change")) label.pack(side = TOP, anchor = W) frame = Frame(top) frame.pack(side = TOP) self.var_graphics = IntVar(top) if self.category != 'font': self.var_graphics.set(1) button = Checkbutton(frame, text = _("Graphics Objects"), state = (self.category == 'font' and DISABLED or NORMAL), variable = self.var_graphics) button.pack(side = TOP, anchor = W) self.var_text = IntVar(top) if self.category == 'font': self.var_text.set(1) button = Checkbutton(frame, text = _("Text Objects"), state = (self.category == 'line' and DISABLED or NORMAL), variable = self.var_text) button.pack(side = TOP, anchor = W) but_frame = Frame(top) but_frame.pack(side = TOP, fill = BOTH, expand = 1) button = Button(but_frame, text = _("OK"), command = self.ok) button.pack(side = LEFT, expand = 1) button = Button(but_frame, text = _("Cancel"), command = self.cancel) button.pack(side = RIGHT, expand = 1) def ok(self, *args): which_properties = (self.var_graphics.get(), self.var_text.get()) self.close_dlg(which_properties)
class Checked(object): def __init__(self, parent_frame, check_text, set_checked=False, on_check_callback=None, on_uncheck_callback=None): self._checked_value = IntVar(value=1 if set_checked else 0) self._check = Checkbutton(parent_frame, text=check_text, variable=self._checked_value, command=self._on_check, anchor=W, justify=LEFT, width=15) self._check.pack(side=TOP) self._on_check_callback = on_check_callback self._on_uncheck_callback = on_uncheck_callback self._check_text = check_text def _on_check(self): if self._checked_value.get() == 1: #print '%s Checked' % self._check_text if self._on_check_callback: self._on_check_callback() else: #print '%s Un-hecked' % self._check_text if self._on_uncheck_callback: self._on_uncheck_callback() def display(self, show=True): if show: self._check.pack(side=TOP) else: self._check.pack_forget() def get_checked(self): return True if self._checked_value.get() == 1 else False def set_checked(self, is_checked): if is_checked: self._checked_value.set(1) else: self._checked_value.set(0) checked = property(fget=get_checked, fset=set_checked)
class Checkbox(Checkbutton): def __init__(self, master, text, default=None, **args): self.var = IntVar() Checkbutton.__init__(self, master, text=text, variable=self.var, **args) if default is not None: self.var.set(default) def get(self): return self.var.get()
class FrequencyBandSettings (): ''' Used to pass common settings ''' def __init__(self): self.channel = {} self.channel[ChannelTypes.LEFT] = IntVar() self.channel[ChannelTypes.MID] = IntVar() self.channel[ChannelTypes.RIGHT] = IntVar() self.channel[ChannelTypes.BACK] = IntVar() self.showLabels = IntVar() self.frequencyBand = StringVar() self.channel[ChannelTypes.LEFT].set(1) self.channel[ChannelTypes.MID].set(1) self.channel[ChannelTypes.RIGHT].set(1) self.channel[ChannelTypes.BACK].set(1) self.showLabels.set(1) self.frequencyBand.set(FrequencyBands.ALPHA) def getCopy(self): copy = FrequencyBandSettings(); copy.channel[ChannelTypes.LEFT].set(self.channel[ChannelTypes.LEFT].get()) copy.channel[ChannelTypes.MID].set(self.channel[ChannelTypes.MID].get()) copy.channel[ChannelTypes.RIGHT].set(self.channel[ChannelTypes.RIGHT].get()) copy.channel[ChannelTypes.BACK].set(self.channel[ChannelTypes.BACK].get()) copy.showLabels.set(self.showLabels.get()) copy.frequencyBand = self.frequencyBand return copy def update(self, other): self.channel[ChannelTypes.LEFT].set(other.channel[ChannelTypes.LEFT].get()) self.channel[ChannelTypes.MID].set(other.channel[ChannelTypes.MID].get()) self.channel[ChannelTypes.RIGHT].set(other.channel[ChannelTypes.RIGHT].get()) self.channel[ChannelTypes.BACK].set(other.channel[ChannelTypes.BACK].get()) self.showLabels.set(other.showLabels.get()) self.frequencyBand = other.frequencyBand def get_showLabels(self): if self.showLabels.get()==1: return True else: return False
def update_syntax(self, key=None): if not key is None: self.text_changed() for name in self.tag_names(): self.tag_delete(name) self.create_syntas_tags() #directives self.highlight_pattern("(#"+"|#".join(directives)+")", "directive") self.highlight_pattern("#[ ]*[define|include|ifndef|endif|pragma][ ]*.*", "directive") #decimal self.highlight_pattern("\y[\d]+\y", "number") #floats self.highlight_pattern("\y[\d]+\.[\d]+\y", "number") #bin self.highlight_pattern("\y0[Bb][01]+\y", "number") #hexa self.highlight_pattern("\y0[Xx][A-Fa-f\d]+\y", "number") #reserved self.highlight_pattern("("+"|".join(const)+")", "reserved") ##operators #self.highlight_pattern("[()\[\]{}<>=\-\+\*\\%#!~&^,]", "operators") #library.function self.highlight_pattern("[^0-9][a-zA-Z0-9_]*\.[^0-9][a-zA-Z0-9_][^\\(]*", "reserved") #double quotation self.highlight_pattern(r'"[^"\\]*(\\.[^"\\]*)*"', "dquot") #single quotation self.highlight_pattern(r"'[^'\\]*(\\.[^'\\]*)*'", "squot") #single line comment self.highlight_pattern(r'//[^\n]*', "scomment") #multi line comment start = self.index("1.0") end = self.index("end") self.mark_set("matchStart", start) self.mark_set("matchEnd", start) self.mark_set("searchLimit", end) count = IntVar() self.mark_set("searchLimit", "end") while True: index = self.search("/*", "matchEnd", "searchLimit", count=count, regexp=False) if index == "": break self.mark_set("matchStart", index) index = self.search("*/", "matchEnd", "searchLimit", count=count, regexp=False) self.mark_set("matchEnd", "%s+%sc" % (index, count.get())) self.tag_add("dcomment", "matchStart", "matchEnd")
def add_customer(self, event=None): # validate and show errors if self.fname.get() == '': showerror("Error!", "First name field blank!") elif self.lname.get() == '': showerror("Error!", "Last name field blank!") elif self.mname.get() == '': showerror("Error!", "Middle initial field blank!") elif self.payment.get() not in ("Drop In", "Punch Card", "Monthly", "Inactive"): showerror("Error!", "Incorect Customer type!") elif not re.compile(r'[01]?\d/[0123]?\d/[12]\d{1,3}').search(self.date.get()): showerror("Error!", "Bad entry for date, use format mm/dd/yyyy") else: self.close = True # do work old, row = self.customers.find(str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip()) new = [str(self.lname.get()).strip(), str(self.fname.get()).strip(), str(self.mname.get()).strip(), str(self.payment.get()).strip(), datetime.strptime(self.date.get(), "%m/%d/%Y")] if not old and self.close: self.new_customer_name = ' '.join([new[1],new[2],new[0]]) self.customers.add(new) elif self.close and not self.edit: var = IntVar() diag = AlreadyExistsDialog(self.root, new, old, var) diag.show() if var.get() == 0: # edit self.close = False if var.get() == 1: # replace self.customers.replace(row, new) self.new_customer_name = ' '.join([new[1],new[2],new[0]]) elif var.get() == 2: # add duplicate self.customers.add(new) self.new_customer_name = ' '.join([new[1],new[2],new[0]]) else: self.customers.replace(row, new) if self.close: self.refresh() self.root.quit()
class Controller(Observer): def __init__(self, parent, subject): print("Controller : __init__") self.subject = subject self.amp = IntVar() self.scale_amp = Scale(parent, variable=self.amp, label="Amplitude", orient="horizontal", length=250, from_=0, to=5, relief="sunken", sliderlength=20, tickinterval=1, command=self.update_amplitude) self.freq = IntVar() self.scale_freq = Scale(parent, variable=self.freq, label="Frequence", orient="horizontal", length=250, from_=0, to=5, relief="sunken", sliderlength=20, tickinterval=1, command=self.update_frequence) def update(self, subject): pass def update_amplitude(self, event): print("Controller : update_amplitude", self.amp.get()) self.subject.set_magnitude(self.amp.get()) def update_frequence(self, event): print("Controller : update_frequence", self.freq.get()) self.subject.set_frequency(self.freq.get()) def packing(self): self.scale_amp.pack(expand=1, fill="x", padx=6) self.scale_freq.pack(expand=1, fill="x", padx=6)
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, textvariable=self.counter) self.label.pack(side="left") self.up = Button(root, text="up", command=self.increment) self.up.pack(side="left") self.down = Button(root, text="down", command=self.decrement) self.down.pack(side="left") def increment(self): self.counter.set(self.counter.get() + 1) def decrement(self): self.counter.set(max(0, self.counter.get() - 1))
class PropertyPanel(SketchPanel): receivers = SketchPanel.receivers[:] def __init__(self, master, main_window, doc, *args, **kw): self.var_auto_update = IntVar(master) self.var_auto_update.set(1) apply(SketchPanel.__init__, (self, master, main_window, doc) + args, kw) receivers.append((SELECTION, 'selection_changed')) receivers.append((EDITED, 'selection_changed')) def selection_changed(self, *args): if self.var_auto_update.get(): self.Update() def create_std_buttons(self, master, update_from=1): button_frame = Frame(master) button = Checkbutton(button_frame, text=_("Auto Update"), variable=self.var_auto_update) button.pack(side=TOP, expand=1, fill=X) if update_from: button = UpdatedButton(button_frame, text=_("Update From..."), command=self.update_from_object) button.pack(side=TOP, expand=1, fill=X) button = UpdatedButton(button_frame, text=_("Apply"), command=self.do_apply, sensitivecb=self.can_apply) button.pack(side=LEFT, expand=1, fill=X) self.Subscribe(SELECTION, button.Update) button = UpdatedButton(button_frame, text=_("Close"), command=self.close_dlg) button.pack(side=RIGHT, expand=1, fill=X) return button_frame def update_from_object(self): self.main_window.canvas.PickObject(self.update_from_object_cb) def update_from_object_cb(self, obj): pass can_apply = SketchPanel.doc_has_selection def SetDocument(self, doc): SketchPanel.SetDocument(self, doc) self.selection_changed()
def gui(): master = Tk() rawfile = askopenfilename(title="Select raw file or first tiff in series", filetypes=[("Raw files", "*.raw"), ("Tiff files", "*.tif")]) if len(rawfile) == 0: quit(0) rawtrunk, rawext = os.path.splitext(rawfile) if rawext == ".raw": Label(master, text="Raw conversion").grid(row=0, sticky=W) var = IntVar() Checkbutton(master, text="LMZA lossless compression", variable=var).grid(row=1, sticky=W) Button(master, text='Cancel', command=quit).grid(row=2, sticky=W, pady=4) Button(master, text='Convert', command=master.quit).grid(row=3, sticky=W, pady=4) mainloop() compress = var.get() != 0 mp = False elif rawext == ".tif": Label(master, text="Multipage TIFF").grid(row=0, sticky=W) var = IntVar() Checkbutton(master, text="Generate multipage TIFF", variable=var).grid(row=1, sticky=W) Button(master, text='Cancel', command=quit).grid(row=2, sticky=W, pady=4) Button(master, text='Convert', command=master.quit).grid(row=3, sticky=W, pady=4) mainloop() compress = False mp = var.get() != 0 return rawfile, mp, compress
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Listbox + Scale + ChkBtn") self.pack(fill=BOTH, expand=1) acts = ['Scarlett Johansson', 'Rachel Weiss', 'Natalie Portman', 'Jessica Alba'] lb = Listbox(self) for i in acts: lb.insert(END, i) lb.bind("<<ListboxSelect>>", self.onSelect) lb.place(x=20, y=20) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=20, y=190) scale = Scale(self, from_=0, to=100, command=self.onScale) scale.place(x=20, y=220) self.var_scale = IntVar() self.label_scale = Label(self, text=0, textvariable=self.var_scale) self.label_scale.place(x=180, y=220) self.var_chk = IntVar() cb = Checkbutton(self, text="Test", variable=self.var_chk, command=self.onClick) cb.select() cb.place(x=220, y=60) def onSelect(self, val): sender = val.widget idx = sender.curselection() value = sender.get(idx) self.var.set(value) def onScale(self, val): v = int(float(val)) self.var_scale.set(v) def onClick(self): if self.var_chk.get() == 1: self.var.set("checked") else: self.var.set("unchecked")
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, textvariable=self.counter) self.label.pack() self.up = Button(root, text="up", command=self.increment) self.up.pack() self.down = Button(root, text="down", command=self.decrement) self.down.pack() def increment(self): self.counter.set(self.counter.get() + 1) def decrement(self): self.counter.set(max(0, self.counter.get() - 1))
class RadioButtonlist(ttk.Frame): def __init__(self,master=None,buttonnamelist=[],**kw): ttk.Frame.__init__(self, master=None, **kw) self.__buttonlist=[] self.__vat= IntVar() self.__vat.set(0) for i in range(len(buttonnamelist)): self.__buttonlist.append(ttk.Radiobutton(self,text=buttonnamelist[i],variable=self.__vat,value=i)) self.__buttonlist[i].pack(anchor = 'nw',side = 'left',padx=5,pady=5) def getvalue(self): return self.__vat.get()
class Candidate(object): def __init__(self, id, name="", points=0): self.name = StringVar() self.points = IntVar() self.id = id if points != 0: self.points.set(points) if name == "": self.name.set("Player " + str(self.id + 1)) else: self.name.set(name) def addPoints(self, points): oldPoints = self.points.get() oldPoints += points self.points.set(oldPoints) def subPoints(self, points): oldPoints = self.points.get() oldPoints -= points self.points.set(oldPoints)
class SpectrumSettings: ''' Used to pass common settings ''' def __init__(self): self.channel = {} self.channel[ChannelTypes.LEFT] = IntVar() self.channel[ChannelTypes.MID] = IntVar() self.channel[ChannelTypes.RIGHT] = IntVar() self.channel[ChannelTypes.BACK] = IntVar() self.showLabels = IntVar() self.channel[ChannelTypes.LEFT].set(1) self.channel[ChannelTypes.MID].set(1) self.channel[ChannelTypes.RIGHT].set(1) self.channel[ChannelTypes.BACK].set(1) self.showLabels.set(1) def getCopy(self): copy = SpectrumSettings(); copy.channel[ChannelTypes.LEFT].set(self.channel[ChannelTypes.LEFT].get()) copy.channel[ChannelTypes.MID].set(self.channel[ChannelTypes.MID].get()) copy.channel[ChannelTypes.RIGHT].set(self.channel[ChannelTypes.RIGHT].get()) copy.channel[ChannelTypes.BACK].set(self.channel[ChannelTypes.BACK].get()) copy.showLabels.set(self.showLabels.get()) return copy def update(self, other): self.channel[ChannelTypes.LEFT].set(other.channel[ChannelTypes.LEFT].get()) self.channel[ChannelTypes.MID].set(other.channel[ChannelTypes.MID].get()) self.channel[ChannelTypes.RIGHT].set(other.channel[ChannelTypes.RIGHT].get()) self.channel[ChannelTypes.BACK].set(other.channel[ChannelTypes.BACK].get()) self.showLabels.set(other.showLabels.get()) def get_showLabels(self): if self.showLabels.get()==1: return True else: return False
class MethodCheckButton(Frame): def __init__(self, master): Frame.__init__(self, master, width = 15) self.initComplete = False self.getVar = IntVar() self.postVar = IntVar() self.getCheckButton = Checkbutton(self, \ text = "GET", width = 6, variable = self.getVar, \ command = self.__singleSelectCommandGet, onvalue = 1, offvalue = 0) self.postCheckButton = Checkbutton(self, \ text = "POST", width = 6, variable = self.postVar, \ command = self.__singleSelectCommandPost, onvalue = 1, offvalue = 0) self.label = Label(self, text = "Use Method:", padx = 3) self.__boxComponents() self.initComplete = True def __boxComponents(self): self.label.grid(row = 0, column = 0) self.getCheckButton.grid(row = 0, column = 1) self.postCheckButton.grid(row = 0, column = 2) def __singleSelectCommandGet(self): if self.initComplete == False: return self.postCheckButton.deselect() def __singleSelectCommandPost(self): if self.initComplete == False: return self.getCheckButton.deselect() def getCurrentMethod(self): if self.getVar.get() == 1: return "get" if self.postVar.get() == 1: return "post" return None
class Input_selection(): """Class for creating GUI for input selection by user. Parameters: - identifiers: list of types of elements in the circuit - values: list of element values in the circuit - number_of_options: number of voltage sources in circuit. """ def __init__(self, identifiers, values, number_of_options): """ Initialize Instance of class Input_selection. A GUI with title Select your input for transfer function is created. """ self.root = Tk() self.passive_element_list = identifiers self.element_values = values self.num_volt_sources = number_of_options self.root.title("Select your input for transfer function") self.options_input() self.root.mainloop() def options_input(self): """ Input is selected by the user from options provided via radiobuttons. If there are *n* voltage sources in the circuit, *n* radiobuttons are given as optons to the user. The user can select any one and then clicks on Confirm selection of input. """ self.v = IntVar() Label(self.root, text="Options for input").grid(row=0, column=0, sticky='news') for ind in range(self.num_volt_sources): Radiobutton(self.root, text="V"+str(ind+1), variable=self.v, value=ind+1).grid(row=ind+1, column=0, sticky=tk.W, pady=4) Button(self.root, text="Confirm selection of input", command=self.compute_val).grid(row=ind+4, column=0, sticky=tk.W, pady=4) def compute_val(self): """Value of the voltage source selected by user is stored in inpval.""" ind = self.passive_element_list.index("V"+str(self.v.get())) self.inpval = self.element_values[ind] self.root.destroy()
class getDist(): def __init__(self, master): self.master=master self.startwindow() #self.b=0 # no need for this, directly store in the global variable def startwindow(self): self.var1 = IntVar() self.textvar = StringVar() self.Label1=Label(self.master, text="Search distance (meters)") self.Label1.grid(row=0, column=0) self.Label2=Label(self.master, textvariable=self.textvar) self.Label2.grid(row=2, column=0) self.rb1 = Radiobutton(self.master, text="5000", variable=self.var1, value=5000, command=self.cb1select) self.rb1.grid(row=1, column=0, sticky=W) self.rb2 = Radiobutton(self.master, text="625", variable=self.var1, value=625, command=self.cb1select) self.rb2.grid(row=1, column=1, sticky=W) self.rb3 = Radiobutton(self.master, text="160", variable=self.var1, value=160, command=self.cb1select) self.rb3.grid(row=1, column=2, sticky=W) self.Button1=Button(self.master, text="ok", command=self.ButtonClick) self.Button1.grid(row=2, column=2) def ButtonClick(self): global dist dist = self.var1.get() self.master.quit() def cb1select(self): return self.var1.get()
def search_pattern(self, pattern, tag, start="1.0", end="end", regexp=False): start = self.index(start) end = self.index(end) self.mark_set("matchStart", start) self.mark_set("matchEnd", start) self.mark_set("searchLimit", end) count = IntVar() while True: index = self.search(pattern, "matchEnd", "searchLimit", count=count, regexp=regexp) if index == "": break self.mark_set("matchStart", index) self.mark_set("matchEnd", "%s+%sc" % (index, count.get())) self.tag_add(tag, "matchStart", "matchEnd")
class CheckBox(Checkbutton): """Adds some methods to Checkbutton """ def __init__(self, parent, **kw): self._var = IntVar() kw['variable'] = self._var Checkbutton.__init__(self, parent, **kw) @property def variable(self): return self._var def is_selected(self): return bool(self._var.get())
class Transmitter(object): def __init__(self, sstv, root, progress, set_ptt_pin, ptt_state): def encode_line_hooked(line): progress.update_image(line) return self.original_encode_line(line) self.progress = progress self.sstv = sstv self.original_encode_line = sstv.encode_line sstv.encode_line = encode_line_hooked self.root = root self.tx_enabled = IntVar() self.audio_thread = None self.stopping = False self.set_ptt_pin = set_ptt_pin self.ptt_state = ptt_state def set_ptt(self, state): if self.set_ptt_pin is None: return if not state: sleep(0.2) self.set_ptt_pin(state != self.ptt_state) if state: sleep(0.2) def start_stop_tx(self): if self.tx_enabled.get(): self.stopping = False self.audio_thread = AudioThread(self.sstv, self) self.set_ptt(True) self.audio_thread.start() else: self.stop() if self.progress is not None: self.progress.update_image() def stop(self): if self.audio_thread is not None: self.stopping = True self.audio_thread.stop() self.set_ptt(False) def audio_thread_ended(self): if not self.stopping: self.set_ptt(False) self.tx_enabled.set(0) def close(self): self.root.destroy()
class Application(object): def __init__(self, root): self.counter = IntVar() self.counter.set(0) self.label = Label(root, textvariable=self.counter) self.label.pack() self.button = Button(root, text="add one", command=self.increment) self.button.pack() def increment(self): self.counter.set(self.counter.get() + 1)
class PopUp(Toplevel): def __init__(self): Toplevel.__init__(self) self.geometry("200x100+2+2") self.initPopup() def initPopup(self): self.var1 = IntVar() cb = Checkbutton(self, text=str("Osteolysis"), variable=self.var1) cb.grid(row=0, column=0, padx=15, pady=20, sticky=E) self.var2 = IntVar() cb = Checkbutton(self, text=str("Synovitis"), variable=self.var2) cb.grid(row=0, column=1, pady=20, sticky=W) printButton = Button(self, text="Submit", command=self.setVars) printButton.grid(row=1, column=0, padx=15, sticky=E) printButton = Button(self, text="Close", command=self.destroy) printButton.grid(row=1, column=1, sticky=W) def setVars(self): global outputs global roiCounter global localRow global localCol global rowVal global colVal roiCounter += 1 colVal.append(localCol) rowVal.append(localRow) self.variables = [] self.variables.append(self.var1.get()) self.variables.append(self.var2.get()) self.destroy() outputs.append(self.variables)
class MethodCheckButton(Frame): def __init__(self, master): Frame.__init__(self, master, width=15) self.initComplete = False self.getVar = IntVar() self.postVar = IntVar() self.getCheckButton = Checkbutton(self, \ text = "GET", width = 6, variable = self.getVar, \ command = self.__singleSelectCommandGet, onvalue = 1, offvalue = 0) self.postCheckButton = Checkbutton(self, \ text = "POST", width = 6, variable = self.postVar, \ command = self.__singleSelectCommandPost, onvalue = 1, offvalue = 0) self.label = Label(self, text="Use Method:", padx=3) self.__boxComponents() self.initComplete = True def __boxComponents(self): self.label.grid(row=0, column=0) self.getCheckButton.grid(row=0, column=1) self.postCheckButton.grid(row=0, column=2) def __singleSelectCommandGet(self): if self.initComplete == False: return self.postCheckButton.deselect() def __singleSelectCommandPost(self): if self.initComplete == False: return self.getCheckButton.deselect() def getCurrentMethod(self): if self.getVar.get() == 1: return "get" if self.postVar.get() == 1: return "post" return None
class PropertyPanel(SketchPanel): receivers = SketchPanel.receivers[:] def __init__(self, master, main_window, doc, *args, **kw): self.var_auto_update = IntVar(master) self.var_auto_update.set(1) apply(SketchPanel.__init__, (self, master, main_window, doc) +args, kw) receivers.append((SELECTION, 'selection_changed')) receivers.append((EDITED, 'selection_changed')) def selection_changed(self, *args): if self.var_auto_update.get(): self.Update() def create_std_buttons(self, master, update_from = 1): button_frame = Frame(master) button = Checkbutton(button_frame, text = _("Auto Update"), variable = self.var_auto_update) button.pack(side = TOP, expand = 1, fill = X) if update_from: button = UpdatedButton(button_frame, text = _("Update From..."), command = self.update_from_object) button.pack(side = TOP, expand = 1, fill = X) button = UpdatedButton(button_frame, text = _("Apply"), command = self.do_apply, sensitivecb = self.can_apply) button.pack(side = LEFT, expand = 1, fill = X) self.Subscribe(SELECTION, button.Update) button = UpdatedButton(button_frame, text = _("Close"), command = self.close_dlg) button.pack(side = RIGHT, expand = 1, fill = X) return button_frame def update_from_object(self): self.main_window.canvas.PickObject(self.update_from_object_cb) def update_from_object_cb(self, obj): pass can_apply = SketchPanel.doc_has_selection def SetDocument(self, doc): SketchPanel.SetDocument(self, doc) self.selection_changed()
class CheckbuttonEntry(BaseWiget): def __init__(self, parent, **kw): BaseWiget.__init__(self,parent, **kw) self.old_value = "" self.var = IntVar() self.cbtn = Checkbutton(self, text=self.caption, variable=self.var) self.cbtn.grid(row=1, column=0) self.var.trace("w", self._onChangeVariable) self.old_value = self.getValue() self.onEndSetupContent() #------------- интерфейс -------------# def setValue(self, value): print "setValue", value if self.old_value == value: return self.old_value = value self.var.set(value) def getValue(self): return self.var.get() def getDictValue(self): raise NotImplementedError def forceSave(self): """принудительное сохранение""" self._onEndInput() #------------- внутренние методы -------------# def _onEndInput(self): value = self.getValue() if self.old_value != value: self.onValueChangeEndByUser(self.old_value, value) self.old_value = value def _onChangeVariable(self, *event): value = self.getValue() if self.old_value == value: return self._onEndInput()
class IssueDialog(tkSimpleDialog.Dialog): def body(self, top): self.title("Issue Number") Label(top, text="Enter issue number: ").grid(row=0, sticky=W) Label(top, text="Chapter number to start with: ").grid(row=1, sticky=W) Label(top, text="Enter password for " + user + ": ").grid(row=2, sticky=W) self.e1 = Entry(top) self.e1.insert(0, "000") self.e1.grid(row=0, column=1) self.e3 = Entry(top) self.e3.insert(0, "2") self.e3.grid(row=1, column=1) self.e2 = Entry(top, show="*") self.e2.grid(row=2, column=1) self.var = IntVar() self.b = Checkbutton(top, text="Debug?", variable= self.var, onvalue = 1, offvalue = 0) self.b.grid(row=3, columnspan=2, sticky=W) #def callConvert(): #essa_clipboardDateConvert.convert() #self.convertButton = Button(top, text="Convert clipboard date", command=callConvert) #self.convertButton.grid(row=4, columnspan=2, sticky=W) def apply(self): global issue issue = self.e1.get() global chapNum chapNum = int(self.e3.get()) global password password = self.e2.get() global debug debug = self.var.get()
def highlight_pattern(self, pattern, tag, start="1.0", end="end", regexp=True): start = self.index(start) end = self.index(end) self.mark_set("matchStart", start) self.mark_set("matchEnd", start) self.mark_set("searchLimit", end) count = IntVar() while True: index = self.search(pattern, "matchEnd", "searchLimit", count=count, regexp=regexp) if index == "": break self.mark_set("matchStart", index) self.mark_set("matchEnd", "%s+%sc" % (index, count.get())) self.tag_add(tag, "matchStart", "matchEnd")
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") self.parent = parent self.initUI() def initUI(self): self.parent.title("simple") Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') self.columnconfigure(0, pad=3) self.columnconfigure(3, pad=3) self.rowconfigure(0, pad=3) self.rowconfigure(4, pad=3) entry = Entry(self) entry.grid(row=0, columnspan=4, sticky=W + E) cls = Button(self, text="Cls") cls.grid(row=1, column=0) quitbutton = Button(self, text="quit", command=self.parent.destroy) quitbutton.grid(row=4, column=0) self.var = IntVar() cb = Checkbutton(self, text="show title", variable=self.var, command=self.onClick) cb.select() cb.grid(row=2, column=2) self.pack() def onClick(self): if self.var.get() == 1: self.parent.title("checkbutton") else: self.parent.title("")