示例#1
0
 def test_get(self):
     v = IntVar(self.root, 123, "name")
     self.assertEqual(123, v.get())
     self.root.globalsetvar("name", "345")
     self.assertEqual(345, v.get())
     self.root.globalsetvar("name", "876.5")
     self.assertEqual(876, v.get())
示例#2
0
class DlgLogin(Dialog):
    def body(self, master, cfg={}):
        "place user dialog widgets"
        self.config = cfg
        self.config["OK button"] = False
        self.site = StringVar()
        self.site.set(cfg.get("site", ""))
        self.login = StringVar()
        self.login.set(cfg.get("user", ""))
        self.password = StringVar()
        self.password.set(str(cfg.get("password", "")))
        site = Entry(master, width=15, textvariable=self.site)
        site.grid(column=1, row=0, sticky="e")
        Label(master, text=_("Site:")).grid(column=0, row=0, sticky="w")
        loge = Entry(master, width=15, textvariable=self.login)
        loge.grid(column=1, row=1, sticky="e")
        Label(master, text=_("Username:"******"w")
        pase = Entry(master, width=15, textvariable=self.password, show="*")
        pase.grid(column=1, row=2, sticky="e")
        Label(master, text=_("Password:"******"w")
        self.to_remember = IntVar()
        self.to_remember.set(cfg.get("remember_passwd", 1))
        chk1 = Checkbutton(master, text="Remember",
                           variable=self.to_remember)
        chk1.grid(column=0, row=3, sticky="w", columnspan=2)
        self.resizable(width=0, height=0)
        return loge

    def apply(self):
        "On ok button pressed"
        self.config["remember_passwd"] = self.to_remember.get()
        self.config["site"] = self.site.get()
        self.config["user"] = self.login.get()
        self.config["password"].set_password(self.password.get())
        self.config["OK button"] = True
示例#3
0
    def main(self):
        '''Function to run on game start'''
        self.mainMenu=Tk()
        self.mainMenu.geometry('200x300+200+200')
        self.mainMenu.title("Minesweeper")
        playButton=Button(self.mainMenu,text='Play',command=lambda:self.startPlay(None))

        self.height= IntVar()
        self.width= IntVar()
        self.minesAmount= IntVar()

        self.height.set(10)
        self.width.set(10)
        self.minesAmount.set(10)

        playButton.pack()
        
        xSlider=Scale(self.mainMenu,orient='horizontal',length=150,width=15,label='Height',sliderlength=20,from_=1,to=15,tickinterval=0,variable=self.height).pack()
        ySlider=Scale(self.mainMenu,orient='horizontal',length=150,width=15,label='Width',sliderlength=20,from_=1,to=15,tickinterval=0,variable=self.width).pack()      
        minesSlider=Scale(self.mainMenu,orient='horizontal',length=150,width=15,label='Mines',sliderlength=20,from_=0,to=15*15-1,tickinterval=0,variable=self.minesAmount).pack()
        
        aboutButton=Button(self.mainMenu,text='About',command=self.about)
        quitButton=Button(self.mainMenu,text='Quit',command=self.quitApp)

        
        
        aboutButton.pack()
        quitButton.pack()
示例#4
0
 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 NetworkPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        self.generalnavframe = ttk.Frame(self)
        self.generalnavframe.grid(row=0, column=0, sticky="nsew")

        self.generalpagebutt = tk.Button(self.generalnavframe, text="General", width=10, height=3, command=lambda: controller.show_frame(GeneralPage))
        self.generalpagebutt.grid(row=0, column=0)

        self.filesyspagebutt = tk.Button(self.generalnavframe, text="File System", width=10, height=3, command=lambda: controller.show_frame(FileSYSPage))
        self.filesyspagebutt.grid(row=0, column=1)

        self.serialpagebutt = tk.Button(self.generalnavframe, text="Serial", width=10, height=3, command=lambda: controller.show_frame(SerialPage))
        self.serialpagebutt.grid(row=0, column=2)

        self.networkpagebutt = tk.Button(self.generalnavframe, text="Network", width=10, height=3, bg='gray', command=lambda: controller.show_frame(NetworkPage))
        self.networkpagebutt.grid(row=0, column=3)

        self.generalcontrollsframe = ttk.Frame(self)  # secondary frame with page controlls
        self.generalcontrollsframe.grid(row=1, column=0, sticky="nsew")

        self.var = IntVar()
        self.var.set(2)

        self.dhcp = ttk.Radiobutton(self.generalcontrollsframe, text="Dhcp", variable=self.var, value=2)
        self.dhcp.grid(row=0, column=1)

        self.static = ttk.Radiobutton(self.generalcontrollsframe, text="Static", variable=self.var, value=1)
        self.static.grid(row=0, column=0)

        self.ipaddress = ttk.Label(self.generalcontrollsframe, text="Ip Address")
        self.ipaddress.grid(row=1, column=0)
        self.ipaddrv4 = ttk.Entry(self.generalcontrollsframe, width=16)
        self.ipaddrv4.grid(row=1, column=1)

        self.subnetlbl = ttk.Label(self.generalcontrollsframe, text="Subnet")
        self.subnetlbl.grid(row=2, column=0)
        self.subnet = ttk.Entry(self.generalcontrollsframe, width=16)
        self.subnet.grid(row=2, column=1)

        self.gatewaylbl = ttk.Label(self.generalcontrollsframe, text="Gateway")
        self.gatewaylbl.grid(row=3, column=0)
        self.gateway = ttk.Entry(self.generalcontrollsframe, width=16)
        self.gateway.grid(row=3, column=1)

        self.dns1lbl = ttk.Label(self.generalcontrollsframe, text="Dns1")
        self.dns1lbl.grid(row=4, column=0)
        self.dns1 = ttk.Entry(self.generalcontrollsframe, width=16)
        self.dns1.grid(row=4, column=1)

        self.dns2lbl = ttk.Label(self.generalcontrollsframe, text="Dns2")
        self.dns2lbl.grid(row=5, column=0)
        self.dns2 = ttk.Entry(self.generalcontrollsframe, width=16)
        self.dns2.grid(row=5, column=1)

        self.setnetwork = ttk.Button(self.generalcontrollsframe, text="Set", width=16)
        self.setnetwork.grid(row=7, column=0, columnspan=2)
示例#6
0
class FrameKSPObject(Frame):
    
    
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        frame = Frame(self)
        frame.pack()
        self.string_var0 = StringVar()
        self.string_var1 = StringVar()
        self.int_var = IntVar()
        self.entry0 = Entry(frame, textvariable=self.string_var0)
        self.entry0.pack(side='left')
        Entry(frame, textvariable=self.string_var1).pack(side='left')
        frame = Frame(self)
        frame.pack()
        Button(frame, width=8, text='Accept', command=self.accept).pack(side='left')
        Button(frame, width=8, text='Cancel', command=self.cancel).pack(side='left')
        Button(frame, width=8, text='Delete', command=self.delete).pack(side='left')
        
        
    def populate(self, kspobject):
        self._kspobject = kspobject
        self.string_var0.set(kspobject.name)
        self.string_var1.set(kspobject.value)
        self.int_var.set(kspobject.id_)
        
        
    def accept(self):
        name = self.string_var0.get()
        value = self.string_var1.get()
        id_ = self.int_var.get()
        self.master.master.update_kspobject(name, value, id_)
        self.master.destroy()
    
    
    def cancel(self):
        self.master.destroy()
    
    
    def delete(self):
        id_ = self.int_var.get()
        self.master.master.delete_kspobject(id_)
        self.master.destroy()
        
        
        
        
        
        
        
        
        
        
        
        
        
示例#7
0
class DiceTab(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        #Sides of Dice
        labelSides=Label(self,text="Sides")
        labelSides.grid(row=0,column=0)
        self.sides=StringVar()
        self.sides.set(20)
        spinboxSides=Spinbox(self,from_=1,to=20,increment=1,width=4)
        spinboxSides.config(textvariable=self.sides, font="sans 24", justify="center")
        spinboxSides.grid(row=0,column=1)
        #Number of Dices
        labelNumber=Label(self,text="Number")
        labelNumber.grid(row=1,column=0)
        self.number=StringVar()
        self.number.set(1)
        spinboxNumber=Spinbox(self,from_=1,to=30,increment=1,width=4)
        spinboxNumber.config(textvariable=self.number, font="sans 24", justify="center")
        spinboxNumber.grid(row=1,column=1)
        #Modifier
        labelModifier=Label(self,text="Modifier")
        labelModifier.grid(row=2,column=0)
        self.modifier=StringVar()
        self.modifier.set(0)
        spinboxModifier=Spinbox(self,from_=-5,to=5,increment=1,width=4)
        spinboxModifier.config(textvariable=self.modifier, font="sans 24", justify="center")
        spinboxModifier.grid(row=2,column=1)
        #Hide Checkbox
        labelHide=Label(self, text="Hide")
        labelHide.grid(row=2, column=2)
        self.hide=IntVar()
        self.hide.set(0)
        checkbuttonHide=Checkbutton(self,variable=self.hide)
        checkbuttonHide.grid(row=2,column=3)
        #Result display
        self.result=StringVar()
        self.result.set("")
        labelResult1=Label(self,text="Result")
        labelResult1.grid(row=1, column=4)
        labelResult2=Label(self,text=self.result.get(),relief=SUNKEN,width=4)
        labelResult2.grid(row=1,column=5)
        #Button to roll
        buttonRoll=Button(self,text="Roll!", command=self.roll)
        buttonRoll.grid(row=2,column=5)
        

    def roll(self):
        self.throws=[]
        numberOfDices=int(self.number.get())
        sidesOfDice=int(self.sides.get())
        modifierOfDice=int(self.modifier.get())
        
        for i in range(numberOfDices):
            self.throws.append(rd.randint(1,sidesOfDice))
        self.result.set(str(sum(self.throws)+modifierOfDice))
        labelResult2=Label(self,text=self.result.get(),relief=SUNKEN, width=4)
        labelResult2.grid(row=1,column=5)
示例#8
0
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()
示例#9
0
文件: calc.py 项目: anwittin/Python
class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, "%P"))

        self.add_button = Button(master, text="+", command=lambda: self.update("add"))
        self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
        self.multiply_button = Button(master, text="*", command=lambda: self.update("multiply"))
        # self.divide_button = Button(master, text="/", command=lambda: self.update("divide"))
        self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))

        # LAYOUT
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=5, sticky=W + E)
        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.multiply_button.grid(row=2, column=2)
        # self.divide_button.grid(row=2, column=3)
        self.reset_button.grid(row=2, column=4, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
        return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        elif method == "multiply":
            self.total *= self.entered_number
        elif method == "divide":
            self.total /= self.entered_number
        else:  # reset
            self.total = 0
        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
示例#10
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

        filemenu = Menu(menubar, tearoff=0, borderwidth=0)
        filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(
            label="20", variable=self._result_size, underline=0, value=20, command=self.set_result_size
        )
        rescntmenu.add_radiobutton(
            label="50", variable=self._result_size, underline=0, value=50, command=self.set_result_size
        )
        rescntmenu.add_radiobutton(
            label="100", variable=self._result_size, underline=0, value=100, command=self.set_result_size
        )
        rescntmenu.invoke(1)
        editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(
            label="60 characters", variable=self._cntx_bf_len, underline=0, value=60, command=self.set_cntx_bf_len
        )
        cntxbfmenu.add_radiobutton(
            label="80 characters", variable=self._cntx_bf_len, underline=0, value=80, command=self.set_cntx_bf_len
        )
        cntxbfmenu.add_radiobutton(
            label="100 characters", variable=self._cntx_bf_len, underline=0, value=100, command=self.set_cntx_bf_len
        )
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label="Before", underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(
            label="70 characters", variable=self._cntx_af_len, underline=0, value=70, command=self.set_cntx_af_len
        )
        cntxafmenu.add_radiobutton(
            label="90 characters", variable=self._cntx_af_len, underline=0, value=90, command=self.set_cntx_af_len
        )
        cntxafmenu.add_radiobutton(
            label="110 characters", variable=self._cntx_af_len, underline=0, value=110, command=self.set_cntx_af_len
        )
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label="After", underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label="Context", underline=0, menu=cntxmenu)

        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        self.top.config(menu=menubar)
示例#11
0
class ProgressCheckButton(Frame, Observable):
    def __init__(self, parent, model, index, status_model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self.model = model
        self.index = index
        self.status_model = status_model
        self.var = IntVar()
        self.var.set(model.get_checked())
        self.progress_var = IntVar()
        self.progress_status = ProgressStatus.undefined
        self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self.model.add_listener(self._model_changed)

    def _model_changed(self, new_status):
        model_state = self.model.get_checked()
        gui_state = self.var.get()
        if model_state is not gui_state:
            self.model.set_checked(gui_state)

    def refresh_check(self):
        if self.status_model.is_checked_force_reload():
            self.check_button.select()
        else:
            self.check_button.deselect()

    def is_checked(self):
        return self.var.get()

    def _progress_status_changed(self, new_status):
        self._refresh_progress()

    def _refresh_progress(self):
        status = self.status_model.get_status()
        if not status == self.progress_status:
            if status == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _check_changed(self):
        new_checked = self.var.get()
        if new_checked is not self.model.get_checked():
            self.model.set_checked(new_checked)
        if new_checked is not self.status_model.is_checked():
            self._notify(self.index, new_checked)
示例#12
0
文件: gui.py 项目: basilevs/varfill
    def __init__(self, control, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.config(padx=2)
        self.queue = Queue()
        self.control = control
        self.disabledWhileRunning = []

        self.formulae = list(map(lambda t: StringVar(self, t), ["x/22.5+4", "50-x*50/180"]))
        self.executionTime = DoubleVar(self, "360")
        self.programSpeed = IntVar(self, "292")
        self.maxTravel = IntVar(self, "-200000")
        self.loadSettings()

        self.createWidgets()
        self.thread = None
示例#13
0
class ProgressListBoxItem(Frame, Observable):
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

        # Create variables and initialise to zero
        self._checked_var = IntVar()
        self._progress_var = IntVar()
        self._checked_var.set(0)
        self._progress_var.set(0)
        self._current_gui_checked_state = CheckStatus.undefined
        self._current_gui_progress_state = ProgressStatus.undefined

        self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self._update()
        self._model.add_listener(self._model_changed)

    def _model_changed(self):
        self.update()

    def _update(self):
        # Update check status
        model_check_state = self._model.get_check_status()
        if model_check_state is not self._current_gui_checked_state:
            self._current_gui_checked_state = model_check_state
            # if self.status_model.is_checked_force_reload():
            if model_check_state:
                self.check_button.select()
            else:
                self.check_button.deselect()

        # Update progress status
        model_progress_state = self._model.get_progress_status
        if not model_progress_state == self._current_gui_progress_state:
            self._current_gui_progress_state = model_progress_state
            if model_progress_state == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _user_check_changed(self):
        new_checked = self._checked_var.get()
        if new_checked is not self._model.get_check_status():
            self._model.manual_set_checked(new_checked)
示例#14
0
  def initialize_ui(self):
    default_padding = {'padx': 10, 'pady' : 10}

    customer_frame = Frame(self)
    self.customer_id_label = Label(customer_frame, text = "Customer id:", style="BW.TLabel")
    self.customer_id_label.pack(default_padding, side = LEFT)

    self.customer_id_value = Label(customer_frame,style="BW.TLabel")
    self.customer_id_value["textvariable"] = self.controller.customer_id
    self.customer_id_value.pack(default_padding, side = LEFT)

    customer_frame.pack(expand = True, fill = "x")

    self.take_picture_frame = Frame(self, border = 10)
    
    self.picture_mode = IntVar()
    Radiobutton(self.take_picture_frame, text = "Light", variable = self.picture_mode, value = 1).pack(side = LEFT)
    Radiobutton(self.take_picture_frame, text = "Dark", variable = self.picture_mode, value = 2).pack(side = LEFT)
    
    self.button_take_picture = Button(self.take_picture_frame, text = "Take picture", command = self.take_picture)
    self.button_take_picture.pack(expand = True, fill = "x", side = BOTTOM)

    self.take_picture_frame.pack(expand = True)
    
    self.button_update = Button(self, text = "Update", command = self.controller.run_update_script)
    self.button_update.pack(expand = True, fill = "x")
示例#15
0
文件: calc.py 项目: anwittin/Python
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, "%P"))

        self.add_button = Button(master, text="+", command=lambda: self.update("add"))
        self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
        self.multiply_button = Button(master, text="*", command=lambda: self.update("multiply"))
        # self.divide_button = Button(master, text="/", command=lambda: self.update("divide"))
        self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))

        # LAYOUT
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=5, sticky=W + E)
        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.multiply_button.grid(row=2, column=2)
        # self.divide_button.grid(row=2, column=3)
        self.reset_button.grid(row=2, column=4, sticky=W + E)
示例#16
0
 def __init__(self, master, ordinances=False, **kwargs):
     super(Options, self).__init__(master, **kwargs)
     self.ancestors = IntVar()
     self.ancestors.set(4)
     self.descendants = IntVar()
     self.spouses = IntVar()
     self.ordinances = IntVar()
     self.contributors = IntVar()
     self.start_indis = StartIndis(self)
     self.fid = StringVar()
     btn = Frame(self)
     entry_fid = EntryWithMenu(btn, textvariable=self.fid, width=16)
     entry_fid.bind('<Key>', self.enter)
     label_ancestors = Label(self, text=_('Number of generations to ascend'))
     entry_ancestors = EntryWithMenu(self, textvariable=self.ancestors, width=5)
     label_descendants = Label(self, text=_('Number of generations to descend'))
     entry_descendants = EntryWithMenu(self, textvariable=self.descendants, width=5)
     btn_add_indi = Button(btn, text=_('Add a FamilySearch ID'), command=self.add_indi)
     btn_spouses = Checkbutton(self, text='\t' + _('Add spouses and couples information'), variable=self.spouses)
     btn_ordinances = Checkbutton(self, text='\t' + _('Add Temple information'), variable=self.ordinances)
     btn_contributors = Checkbutton(self, text='\t' + _('Add list of contributors in notes'), variable=self.contributors)
     self.start_indis.grid(row=0, column=0, columnspan=3)
     entry_fid.grid(row=0, column=0, sticky='w')
     btn_add_indi.grid(row=0, column=1, sticky='w')
     btn.grid(row=1, column=0, columnspan=2, sticky='w')
     entry_ancestors.grid(row=2, column=0, sticky='w')
     label_ancestors.grid(row=2, column=1, sticky='w')
     entry_descendants.grid(row=3, column=0, sticky='w')
     label_descendants.grid(row=3, column=1, sticky='w')
     btn_spouses.grid(row=4, column=0, columnspan=2, sticky='w')
     if ordinances:
         btn_ordinances.grid(row=5, column=0, columnspan=3, sticky='w')
     btn_contributors.grid(row=6, column=0, columnspan=3, sticky='w')
     entry_ancestors.focus_set()
示例#17
0
 def highlight_pattern(self, pattern, tag, start="1.0", end="end", regexp=False):
     '''Apply the given tag to all text that matches the given pattern
     If 'regexp' is set to True, pattern will be treated as a regular expression
     '''
     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")
示例#18
0
    def __init__(self,parent,col,row,genre):

        """

        :param parent: fenetre root
        :param col: colonne pour placer le label
        :param row: ligne pour placer le label
        :param genre: type de label (int ou str)
        """
        self.val=StringVar()
        self.val.set("RED")
        if (genre=="integer"):
            self.val=IntVar()
            self.val.set(0)
        label=Label(parent,textvariable=self.val,bg="bisque")
        label.grid(column=col,row=row)
示例#19
0
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("-")
示例#20
0
文件: tree.py 项目: DrDub/nltk
    def __init__(self, *trees):
        from math import sqrt, ceil

        self._trees = trees

        self._top = Tk()
        self._top.title('NLTK')
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Control-q>', self.destroy)

        cf = self._cframe = CanvasFrame(self._top)
        self._top.bind('<Control-p>', self._cframe.print_to_file)

        # Size is variable.
        self._size = IntVar(self._top)
        self._size.set(12)
        bold = ('helvetica', -self._size.get(), 'bold')
        helv = ('helvetica', -self._size.get())

        # Lay the trees out in a square.
        self._width = int(ceil(sqrt(len(trees))))
        self._widgets = []
        for i in range(len(trees)):
            widget = TreeWidget(cf.canvas(), trees[i], node_font=bold,
                                leaf_color='#008040', node_color='#004080',
                                roof_color='#004040', roof_fill='white',
                                line_color='#004040', draggable=1,
                                leaf_font=helv)
            widget.bind_click_trees(widget.toggle_collapsed)
            self._widgets.append(widget)
            cf.add_widget(widget, 0, 0)

        self._layout()
        self._cframe.pack(expand=1, fill='both')
        self._init_menubar()
示例#21
0
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)
    def __init__(self):



        Frame.__init__(self)
        self.master.title("Cherry Pick Creator")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)
        self.radiovariable = IntVar()
        self.head = StringVar()
        self.head = ' '
        self.filenamestring = "before"


        self.button2 = Button(self, text="Load CSV", command=self.load_file, width=10)
        #self.radiobutton1 = Radiobutton(self, text="Replicates on Different Plates", variable=self.radiovariable, value=1, command=self.radio_sel)
        #self.radiobutton1.grid(row=1, column=0, sticky=W)
        #self.radiobutton2 = Radiobutton(self, text="Replicates on Same Plate", variable=self.radiovariable, value=2, command=self.radio_sel)
        #self.radiobutton2.grid(row=1, column=1, sticky=W)
        self.plate_reps_lbl = Label(self, text="Plate Copies")
        self.plate_reps_lbl.grid(row=0, column=0, sticky=W)
        self.plate_reps_lbl2 = Label(self, text="Replicates Per Plate")
        self.plate_reps_lbl2.grid(row=0, column=1, sticky=W)
        self.button2.grid(row=3, column=0, sticky=W)
        self.spinbox = Spinbox(self, from_=1, to=50, command=self.spin_com)
        self.spinbox.grid(row=2, column=0, sticky=W)
        self.spinbox2 = Spinbox(self, from_=1, to=50, command=self.spin_com)
        self.spinbox2.grid(row=2, column=1, sticky=W)
        self.filneame_lable = Label(self, text=self.head)
        self.filneame_lable.grid(row=3, column=1, sticky=W)
        self.gobutton = Button(self, text="Run", command=self.run_program, width=10)
        self.gobutton.grid(row=4, column=0, sticky=W)
        self.spin_com()
示例#23
0
    def highlight_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
            if count.get() == 0: break
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")
示例#24
0
文件: gui.py 项目: babab/DisPass
    def __init__(self, settings, filehandler):
        '''Initialize GUI object, create the widgets and start mainloop

        Try to import Tkinter and tkMessageBox. If that fails, show a help
        message with quick instructions on installing Tkinter.
        '''

        self.settings = settings
        self.labelspecs = {l[0]: l[1:] for l in filehandler.labelfile}

        Frame.__init__(self, Tk(className='dispass'))
        self.lengthVar = IntVar()
        self.lengthVar.set(self.settings.passphrase_length)
        self.sequenceVar = IntVar()
        self.sequenceVar.set(self.settings.sequence_number)
        self.master.title(versionStr)
        self.grid()
        self.createWidgets()
示例#25
0
    def __init__(self, *args, **kwargs):
        self._app = Scripting.root_node
        self.__gui_images = []
        self.__topwin = kwargs.pop('topwin')
        super().__init__(*args, **kwargs)
        
        imageMLbl = ImageTk.PhotoImage(
            file=Scripting.root_node.get_gui_image_path('Pattern_M_Label.png')
        )
        self.__gui_images.append(imageMLbl)        
        self.__M = LabeledEntry(self)
        self.__M.label.config(text='M', image=imageMLbl, compound='left')
        self.__M.entry_width = 6
        self.__M.entry_text = 10
        self.__M.entry.bind(
            '<Return>', 
            lambda dumb: self._on_solve_button_click())
        self.__M.checker_function = self._app.gui.value_checker.check_int
        self.__M.pack()
        
        self._app.gui.balloon.bind_widget(
            self.__M, 
            balloonmsg='The number of the array elements.')

        image_solve = ImageTk.PhotoImage(
            file=Scripting.root_node.get_gui_image_path('Pattern_Solve_Button.png'))
        self.__gui_images.append(image_solve)

        self.__btnSolve = Button(
            self, 
            text='Solve', 
            image=image_solve, 
            compound='left', 
            command=self._on_solve_button_click)
        self.__btnSolve.pack(side='top', fill='x')
        self._app.gui.balloon.bind_widget(
            self.__btnSolve, 
            balloonmsg='Launch the solver to synthesize the correlation matrix.')
        
        image_display = ImageTk.PhotoImage(
            file=Scripting.root_node.get_gui_image_path('Pattern_Display_Button.png'))
        self.__gui_images.append(image_display)
        self.__bDisplay = IntVar(0)
        chk_display = Checkbutton(
            self, 
            text="Display", 
            image=image_display, 
            compound='left', 
            variable=self.__bDisplay)
        chk_display.pack(side='top')
        self._app.gui.balloon.bind_widget(
            chk_display, 
            balloonmsg='Display solver output.')
        chk_display_width = chk_display.winfo_width()
        self.__btnSolve['width'] = chk_display_width
        
        self.name = 'Optimize'
示例#26
0
    def __init__(self, master):
        self.init_args()
        self.master = master
        master.title("Helper")

        self.label = Label(master, text="Parser Helper")
        self.label.pack()

        self.exception_value = IntVar()
        # Exception
        C1 = Checkbutton(master, text="Exception", variable=self.exception_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C1.pack()


        self.cause_value = IntVar()
        # Cause by
        C2 = Checkbutton(master, text="Cause by", variable=self.cause_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C2.pack()
        # Verbose
        self.verbose_value = IntVar()
        C3 = Checkbutton(master, text="Verbose", variable=self.verbose_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C3.pack()

        # Log to file
        self.log_value = IntVar()
        C4 = Checkbutton(master, text="Log to file", variable=self.log_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C4.pack()

        self.greet_button = Button(master, text="Select file", command=self.open_file)
        self.greet_button.pack()

        self.close_button = Button(master, text="Execute", command=self.execute)
        self.close_button.pack()

        self.close_button = Button(master, text="Quit", command=master.quit)
        self.close_button.pack()
    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)
示例#28
0
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

        # Create variables and initialise to zero
        self._checked_var = IntVar()
        self._progress_var = IntVar()
        self._checked_var.set(0)
        self._progress_var.set(0)
        self._current_gui_checked_state = CheckStatus.undefined
        self._current_gui_progress_state = ProgressStatus.undefined

        self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self._update()
        self._model.add_listener(self._model_changed)
示例#29
0
    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget("size"))

        self._boldfont = tkinter.font.Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = tkinter.font.Font(family="helvetica", size=self._size.get())
示例#30
0
    def __init__(self):
        """
            À completer !.
        """
        super().__init__()

        # Nom de la fenêtre.
        self.title("Ultimate Tic-Tac-Toe")

        # La partie de ultimate Tic-Tac-Toe
        self.partie = Partie()

        # Un ditionnaire contenant les 9 canvas des 9 plateaux du jeu
        self.canvas_uplateau = {}

        Button(self.canvas_uplateau, text ='Débuter la partie', command =self.demande_confirmation).\
            grid(row =0, column =4)

        self.var = IntVar()
        Checkbutton(self, text= 'VS ordinateur', variable=self.var, onvalue =1, offvalue =0).grid(row =0, column =2)


        # L'entrée du joueur1 est automatiquement demandé
        Label(self.canvas_uplateau, text ="Nom du Joueur 1:").\
            grid(row =0, column =0, sticky=E)
        self.joueur1 = Entry(self.canvas_uplateau, width =14)
        self.joueur1.grid(row =0, column =1, padx=5, pady=5, sticky=E+W)

#        Label (self.canvas_uplateau, text="Le tour: {}".format(self.partie.joueur_courant.nom)).grid(row=3, column=3)

        # L'entrée du joueur2 est selon la checkbox (peut etre l'ordinateur
        Label(self.canvas_uplateau, text ="Nom du Joueur 2:").\
            grid(row =1, column =0, sticky=E)
        self.joueur2 = Entry(self.canvas_uplateau, width =14)
        self.joueur2.grid(row =1, column =1, padx=5, pady=5, sticky=E+W)

        Button(self.canvas_uplateau, text = 'Quitter', command = self.quit).\
            grid (row = 5, column = 4, sticky = E)

        # Création des frames et des canvas du jeu
        for i in range(0, 3):
            for j in range(0, 3):
                cadre = Frame(self, borderwidth=5, relief=GROOVE, background = '#e1e1e1')
                cadre.grid(row=i+3, column=j, padx=5, pady=5)
                cadre.bind('<Enter>', self.entrer_frame)
                cadre.bind('<Leave>', self.sortir_frame)
                self.canvas_uplateau[i,j] = CanvasPlateau(cadre, self.partie.uplateau[i,j])
                self.canvas_uplateau[i,j].grid()
                # On lie un clic sur le Canvas à une méthode.
                self.canvas_uplateau[i,j].bind('<Button-1>', self.selectionner)

        # Ajout d'une étiquette d'information.
        self.messages = Label(self)
        self.messages.grid(columnspan=3)
示例#31
0
文件: MathTest.py 项目: PHSC138/D-Edu
class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.instruction = tk.Label(self,
                                    height=1,
                                    font=("Times New Roman", 45))
        self.instruction.grid(row=0, columnspan=7, sticky='N')

        self.problem = tk.Label(self, height=1, font=("Times New Roman", 45))
        self.problem.grid(row=1, columnspan=7, sticky='N')

        self.radio0 = tk.Radiobutton(self,
                                     font=("Times New Roman", 45),
                                     borderwidth="3")
        self.radio1 = tk.Radiobutton(self,
                                     font=("Times New Roman", 45),
                                     borderwidth="3")
        self.radio2 = tk.Radiobutton(self,
                                     font=("Times New Roman", 45),
                                     borderwidth="3")
        self.radio0.grid(row=2, column=0, columnspan=7, sticky='N')
        self.radio1.grid(row=3, column=0, columnspan=7, sticky='N')
        self.radio2.grid(row=4, column=0, columnspan=7, sticky='N')

        #assign function buttons
        self.submit = tk.Button(self,
                                text="Submit",
                                font=("Times New Roman", 30),
                                borderwidth="3",
                                command=self.post)
        self.submit.grid(row=7, column=0, columnspan=2, sticky='S')

        self.quit = tk.Button(self,
                              text="QUIT",
                              fg="red",
                              font=("Times New Roman", 30),
                              borderwidth="3",
                              command=self.end)
        self.quit.grid(row=7, column=5, columnspan=2, sticky='S')

        self.pack()
        self.create_widgets()

    def create_widgets(self):
        global instructions
        self.instruction["text"] = instructions[problemCounter]

        self.problem["text"] = problems[problemCounter]

        self.radioVar = IntVar(root)
        self.radioVar.set(0)
        self.radio0["text"] = options[problemCounter][0]
        self.radio1["text"] = options[problemCounter][1]
        self.radio2["text"] = options[problemCounter][2]
        self.radio0["value"] = 0
        self.radio1["value"] = 1
        self.radio2["value"] = 2
        self.radio0["variable"] = self.radioVar
        self.radio1["variable"] = self.radioVar
        self.radio2["variable"] = self.radioVar
        self.radio0["command"] = self.updateradioVar
        self.radio1["command"] = self.updateradioVar
        self.radio2["command"] = self.updateradioVar

        self.submit.bind('<Return>', self.post)
        self.quit.bind('<Return>', self.end)

    def updateradioVar(self):
        global radioVarValue
        print("updating: " + str((self.radioVar).get()))
        radioVarValue = (self.radioVar).get()

    def post(self, *args):
        global radioVarValue
        global noProblems
        global grade

        print("post")
        print(radioVarValue)
        global problemCounter
        #Check answers
        grade += checkAnswers()
        print("GRADE: " + str(grade))
        print("OUT OF: " + str(noProblems))

        problemCounter += 1
        if problemCounter == noProblems:
            self.end()
        else:
            self.radioVar.set(0)
            self.create_widgets()
            app.master.update()

    def end(self, *args):
        print("post to chain")
        writeBC('addMathScore', studentHash, grade, noProblems)
        print("quitting")
        root.destroy()
        exit(0)
示例#32
0
class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master,
                           validate="key",
                           validatecommand=(vcmd, '%P'))

        self.add_button = Button(master,
                                 text="+",
                                 command=lambda: self.update("add"))
        self.subtract_button = Button(master,
                                      text="-",
                                      command=lambda: self.update("subtract"))
        self.reset_button = Button(master,
                                   text="Reset",
                                   command=lambda: self.update("reset"))

        # LAYOUT

        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)

        self.entry.grid(row=1, column=0, columnspan=3, sticky=W + E)

        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.reset_button.grid(row=2, column=2, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
            return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        else:  # reset
            self.total = 0

        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
示例#33
0
class Spinbox(Frame):
    def __init__(self, master, **kwargs):
        Frame.__init__(self, master, **kwargs)

        self._last = 0
        self.entryVar = IntVar(self._last)
        self.entry = Entry(self, textvariable=self.entryVar, width=4)
        self.entry.grid(row=0, column=1)
        self.entry.bind("<FocusIn>", self._store)
        self.entry.bind("<FocusOut>", self._validateEntry)
        self.entry.bind("<KeyPress-Return>", self._validateEntry)

        self.leftImg = PhotoImage(
            file=os.path.join(RESOURCE_DIR, "arrow-left.gif"))
        self.rightImg = PhotoImage(
            file=os.path.join(RESOURCE_DIR, "arrow-right.gif"))

        self.left = Button(self, image=self.leftImg, command=self.decrement)
        self.left.grid(row=0, column=0, sticky=Tkc.NS)

        self.down = Button(self, image=self.rightImg, command=self.increment)
        self.down.grid(row=0, column=2, sticky=Tkc.NS)

        self.minimum = 0
        self.maximum = 10

        self.changedCallback = None

    def set(self, value):
        assert type(value) == int
        if self._valid(value):
            self.entryVar.set(value)
            if value != self._last:
                self._last = value
                self._issueChanged()

    def get(self):
        return self.entryVar.get()

    def min(self, value):
        assert type(value) == int
        i = int(value)
        if i < self.maximum:
            self.minimum = i
            if self.get() < self.minimum:
                self.set(self.minimum)
        else:
            self.minimum = self.maximum
            self.set(self.minimum)

    def max(self, value):
        assert type(value) == int
        i = int(value)
        if i > self.minimum:
            self.maximum = i
            if self.get() > self.maximum:
                self.set(self.maximum)
        else:
            self.maximum = self.minimum
            self.set(self.maximum)

    def increment(self):
        i = self.entryVar.get()
        if i < self.maximum:
            self.set(i + 1)

    def decrement(self):
        i = self.entryVar.get()
        if i > self.minimum:
            self.set(i - 1)

    def reset(self):
        self._last = 0
        self.entryVar.set(self._last)
        self.minimum = 0
        self.maximum = 10

    def _issueChanged(self):
        if self.changedCallback is not None:
            self.changedCallback()

    def _validateEntry(self, event):
        try:
            i = int(self.entryVar.get())
        except ValueError:
            i = self._current

        if not self._valid(i):
            i = min(self.maximum, max(self.minimum, i))

        self._current = i
        self.set(i)

    def _store(self, event):
        self._current = self.entryVar.get()

    def _valid(self, value):
        return (value >= self.minimum and value <= self.maximum)
示例#34
0
    def __init__(self, master, queue, scrape_url):
        self.queue = queue

        # ACTION:

        def form_setup():  # function to combin form setup
            form.iconbitmap('Wave_inputs/wave_ico.ico')  # Assign icon
            form.title("Betfair Wave")  # Assign window titly

        form_setup()  # run form setup

        # Define parent tab
        tab_parent = ttk.Notebook(form)

        # ------------------- Bet overview tab
        # init constants
        rw = 1

        # Define tabs existence
        global bet_overview
        bet_overview = ttk.Frame(tab_parent)

        def tab_overview_setup():
            tab_parent.add(bet_overview, text="Overview")

        tab_overview_setup()  # run tab setup

        # & Bet link text

        def bet_overview_static_text():
            Label(bet_overview,
                  text="Betfair Sportsbook URL: ").grid(row=1,
                                                        column=1,
                                                        columnspan=1)
            Label(bet_overview, text="Strategy: ").grid(row=2,
                                                        column=1,
                                                        columnspan=1)
            Label(bet_overview, text="TIme period (s): ").grid(row=3,
                                                               column=1,
                                                               columnspan=1)

        bet_overview_static_text()  # call static text

        # & Bet URL input
        global bet_url_entry
        bet_url_entry = tk.Entry(bet_overview, width=70)
        bet_url_entry.grid(row=rw, column=3, columnspan=7, sticky="W")
        bet_url_entry.insert(END,
                             "https://www.betfair.com/exchange/plus/football")

        # Strategy drop down menu
        OPTIONS = []
        import os
        for file in os.listdir():
            if file.startswith("strategy"):
                file = file.replace(".py", "")
                OPTIONS.append(file)

        global strategyoptions
        strategyoptions = StringVar(bet_overview)
        strategyoptions.set(OPTIONS[1])  # default value

        w = OptionMenu(bet_overview, strategyoptions, *OPTIONS)
        w.grid(row=2, column=3, columnspan=1)

        # Timer drop down menu
        timeoptions = [60, 600, 6000, 60000]

        global timeoption
        timeoption = StringVar(bet_overview)
        timeoption.set(timeoptions[3])  # default value

        w = OptionMenu(bet_overview, timeoption, *timeoptions)
        w.grid(row=3, column=3, columnspan=1)

        #w.pack()

        # & Start button

        start_btn_scrape = tk.Button(bet_overview,
                                     text="Start",
                                     command=scrape_url,
                                     width=15)
        start_btn_scrape.grid(row=rw, column=10, sticky="W")

        # ------------------- Settings
        # init constants
        srw = 1

        # -------- Define tabs existence
        settings = ttk.Frame(tab_parent)

        def tab_settings_setup():
            tab_parent.add(settings, text="Settings")

        tab_settings_setup()  # run tab setup

        # Lift tkinter to front
        var1 = IntVar()

        def on_top_func():
            if var1.get() == 1:
                form.lift()
                form.call('wm', 'attributes', '.', '-topmost', '1')
            else:
                form.call('wm', 'attributes', '.', '-topmost', '0')

        Checkbutton(settings,
                    text="Window always visible",
                    variable=var1,
                    command=on_top_func).grid(row=srw,
                                              sticky="W",
                                              columnspan=3)

        # Add text
        def settings_static_text():
            Label(settings, text="Back Bet Value:").grid(row=2,
                                                         column=1,
                                                         sticky="W")
            Label(settings, text="Lay Bet Value:").grid(row=3,
                                                        column=1,
                                                        sticky="W")

        settings_static_text()  # call static text

        # Lay bet entry
        lay_bet_value = tk.Entry(settings, width=20)
        lay_bet_value.grid(row=2, column=2, sticky="W")
        lay_bet_value.insert(END, "2")

        # Lay bet entry
        lay_bet_value = tk.Entry(settings, width=20)
        lay_bet_value.grid(row=3, column=2, sticky="W")
        lay_bet_value.insert(END, "2")

        # unpack tabs
        tab_parent.pack(expand=1, fill="both")
示例#35
0
    def __init__(self,
                 root: LabelFrame,
                 name: str,
                 change_setting_func: Callable,
                 config: RenderingConfig,
                 render_mode: str,
                 shader_settings: List[str] = None,
                 row: int = 0,
                 column: int = 0):
        self.name: str = name
        self.render_frame: LabelFrame = LabelFrame(root,
                                                   text=self.name,
                                                   width=60,
                                                   padx=1,
                                                   pady=1)
        self.render_mode: IntVar = IntVar(value=config[render_mode])
        self.render_radio_buttons: List[Radiobutton] = []
        self.shader_settings: Dict[str, SettingEntry] = dict()
        self.shader_setting_frame: LabelFrame = LabelFrame(
            self.render_frame, text="Shader Settings", padx=1, pady=1)

        def create_apply_func(function: Callable,
                              inner_func: Callable) -> Callable:
            def command():
                function(inner_func)

            return command

        self.apply_settings: Button = Button(self.shader_setting_frame,
                                             text="Apply",
                                             command=create_apply_func(
                                                 self.get_settings,
                                                 change_setting_func))

        def create_radio_func(setting_value: int) -> Callable:
            def command():
                change_setting_func(render_mode, setting_value)

            return command

        for i, option in enumerate(config.selection_labels[render_mode]):
            self.render_radio_buttons.append(
                Radiobutton(self.render_frame,
                            text=option,
                            variable=self.render_mode,
                            value=i,
                            command=create_radio_func(i)))
            self.render_radio_buttons[i].grid(row=i, column=0)

        change_setting_func(self.name, config[render_mode])

        if shader_settings is not None:
            for i, setting in enumerate(shader_settings):
                self.shader_settings[setting] = SettingEntry(
                    self.shader_setting_frame, config.shader_label[setting],
                    config[setting], "float", i, 0)

            self.apply_settings.grid(row=len(self.shader_settings),
                                     column=0,
                                     columnspan=2)
            self.shader_setting_frame.grid(row=0,
                                           column=1,
                                           rowspan=len(
                                               self.render_radio_buttons),
                                           padx=1,
                                           pady=1)
        self.render_frame.grid(row=row, column=column, padx=1, pady=1)

        self.get_settings(change_setting_func)
示例#36
0
    def __bottom_frame(self):
        """
        Create bottom frame content
        """
        self._cbx_max_power_value = IntVar(self._tk_obj)
        self._cbx_lowball_value = IntVar(self._tk_obj)

        frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff')
        frame.grid(column=0, row=2, padx=15, pady=15, sticky=W + E)
        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # headline
        txt_section = Label(frame, text="Receive RF Settings")
        txt_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E)
        txt_section.configure(font=self.__FONT_HEADLINE)

        # lowball
        lab_lowball = Label(frame, text='Lowball')
        lab_lowball.grid(column=0, row=1, padx=5, pady=5, sticky=E)
        lab_lowball.configure(font=self.__FONT_STYLE)

        # @ToDo: implementation lowball
        cbx_lowball = Checkbutton(frame, state='disabled')
        cbx_lowball.grid(column=1, row=1, padx=5, pady=5, sticky=W)
        cbx_lowball.configure(onvalue=1,
                              offvalue=0,
                              variable=self._cbx_lowball_value)

        # max power
        lab_max_power = Label(frame, text='max Power')
        lab_max_power.grid(column=2, row=1, padx=5, pady=5, sticky=E)
        lab_max_power.configure(font=self.__FONT_STYLE)

        # @ToDo: implementation of max power
        cbx_max_power = Checkbutton(frame, state='disabled')
        cbx_max_power.grid(column=3, row=1, padx=5, pady=5, sticky=W)
        cbx_max_power.configure(onvalue=1,
                                offvalue=0,
                                variable=self._cbx_max_power_value)

        # receive signal
        self._btn_receive = Button(frame,
                                   text='Start receive',
                                   command=self.__action_receive_signal)
        self._btn_receive.grid(column=4, row=1, padx=5, pady=5)
        self._btn_receive.configure(font=self.__FONT_STYLE)
        self._btn_receive.bind(
            "<Enter>", lambda event: event.widget.config(fg='indian red'))
        self._btn_receive.bind("<Leave>",
                               lambda event: event.widget.config(fg='black'))

        # copy to clipboard
        self._btn_copy = Button(frame,
                                text='Copy to clipboard',
                                command=self.__action_copy_to_clipboard)
        self._btn_copy.grid(column=5, row=1, padx=5, pady=5)
        self._btn_copy.configure(font=self.__FONT_STYLE)
        self._btn_copy.bind("<Enter>",
                            lambda event: event.widget.config(fg='indian red'))
        self._btn_copy.bind("<Leave>",
                            lambda event: event.widget.config(fg='black'))

        # status
        self._stx_receive_status = ScrolledText(frame)
        self._stx_receive_status.grid(columnspan=6,
                                      row=2,
                                      padx=5,
                                      pady=5,
                                      sticky=W + E)
        self._stx_receive_status.configure(height=12,
                                           font=self.__FONT_STYLE,
                                           borderwidth=1,
                                           relief=SOLID)
示例#37
0
    def __init__(self, master):
        super().__init__(master)
        self.name = None  # currently unused, but will be for saving and loading
        # dictionary of default colors for initialization and the reset button:
        self._default = {
            'r': [255, 255, 255, 220, 75, 3, 3, 30, 125, 220, 255],
            'g': [0, 150, 255, 255, 255, 255, 145, 3, 3, 3, 0],
            'b': [0, 0, 0, 3, 3, 240, 255, 255, 255, 255, 0]
        }
        self.n_updates = 0
        # self.backgroundcolor = self.rgb_tk((0, 0, 0))
        self._resetcolors = True  # this tells the color boxes to fill themselves with the defaults
        self._colordict = deepcopy(
            self._default
        )  # this is master list of colors that you use and edit. Starts as default

        # variables for the background color:
        self._bg_red = StringVar()
        self._bg_green = StringVar()
        self._bg_blue = StringVar()
        # putting them all into a single object:
        self._bg_vars = {
            'r': self._bg_red,
            'g': self._bg_green,
            'b': self._bg_blue
        }
        # this will be the swatch that shows you the color
        self._bg_color_example = None

        # label the background control area
        backgroundlabel = Label(self, text="Background:", font=self.h1)
        backgroundlabel.grid(row=2,
                             column=3,
                             columnspan=300,
                             pady=(10, 5),
                             sticky="nw")
        # setup the controls for the background color
        self.setup_background_color_area()

        # label the pattern color control area
        patternlabel = Label(self, text="Pattern:", font=self.h1)
        patternlabel.grid(row=6,
                          column=3,
                          columnspan=300,
                          pady=(10, 5),
                          sticky="nw")

        # initializing and setting the main parameters
        self._totalcolors = Parameter(
            self,
            label="Total Colors (fade smoothness)",
            from_=1,
            to=300,
            command=self.check_ratio_tot,
            row=9
        )  # this one sets the number of transitionary colors beginning to end of the selected colors
        self._totalcolors.set(100)
        self._colorstops = Parameter(
            self,
            label="Number of Stops",
            from_=2,
            to=11,
            command=self.update_colorstops,
            row=10
        )  # this one sets the number of colors you define specifically
        self._colorstops.set(11)

        settodefaultcolors = Button(
            self,
            text='Load Default Colors',
            command=self.reset_colors_to_default
        )  # resets colordict back to the default rainbow set
        settodefaultcolors.grid(row=18, column=3, columnspan=300)
        reversecolors = Button(
            self, text='Reverse Order', command=self.reverse_color_order
        )  # this button flips the order of the entire color dictionary
        reversecolors.grid(row=18, column=500, columnspan=300)

        # This comes from the Tab class, and it is a Separate frame that can
        # keep spacing independent from controls on the rest of the tab. this
        # is where the color boxes will go.
        self._spacedarea.grid(row=20, column=0, columnspan=800)

        self._colorshiftvar = IntVar()
        self._colorshift = Parameter(
            self,
            label="Shift Position",
            from_=-6,
            to=6,
            row=25,
            command=self.shift_color,
            bigincrement=1,
            variable=self._colorshiftvar
        )  # this control shifts the position of the colors in the dictionary
        self._previousshift = 0  # this is for determining the interval of shift (-1 or 1)

        self._hueshiftvar = IntVar(
        )  # using a variable with this one so that I can reset hue shift to zero on loading without triggering the callback.
        self._hueshift = Parameter(self,
                                   label="Shift Hue",
                                   from_=-127,
                                   to=127,
                                   row=27,
                                   command=self.shift_hue,
                                   bigincrement=2,
                                   resolution=2,
                                   variable=self._hueshiftvar)
        self._previoushue = 0

        # label the effects section of the tab
        effectslabel = Label(self, text="Effects:", font=self.h2)
        effectslabel.grid(row=28,
                          column=3,
                          columnspan=200,
                          pady=(10, 5),
                          padx=(10, 0))

        # creating the buttons for each color transformation
        shiftlightnessbutton = Button(
            self,
            text="Shift Lightness",
            command=lambda: ShiftLightnessDialog(self.shift_lightness))
        ramplightnessbutton = Button(
            self,
            text="Ramp Lightness",
            command=lambda: RampLightnessDialog(self.ramp_lightness))

        shiftlightnessbutton.grid(row=30,
                                  column=3,
                                  columnspan=200,
                                  pady=10,
                                  padx=(5, 0))
        ramplightnessbutton.grid(row=30, column=210, columnspan=200)
示例#38
0
class ApplicationUi(BaseUi):

    __FONT_HEADLINE = ('verdana', 13, 'bold')
    __FONT_STYLE = ('verdana', 11, 'normal')
    __MODULATION_OPTIONS = [
        'Please select', 'MOD_2FSK', 'MOD_GFSK', 'MOD_ASK_OOK', 'MOD_MSK'
    ]

    def __init__(self, window_title, window_resizable, bg_color, show_menu):
        """
        Overwrite base tkinter object

        :type window_title: str
        :param window_title: set window title
        :type window_resizable: bool
        :param window_resizable: set windows resizeable true or false
        :type bg_color: str
        :param bg_color: color code ('#ddd')
        :type show_menu: bool
        :param show_menu: set menu visible true or false
        """
        # initialize logging and set logging level
        self.__logger = logging.getLogger(__name__)
        logging.basicConfig(level=logging.INFO)

        # all needed variables
        self.__sample_list = []
        self.rf_object = RfCat()
        self._selected_modulation = None
        self._selected_channel = None
        self._selected_sync_mode = None
        self._ety_frequency = None
        self._ety_baud = None
        self._ety_deviation = None
        self._ety_channel_bandwidth = None
        self._ety_sync_word = None
        self._ety_channel_spacing = None
        self._cbx_manchester_value = None
        self._btn_save_settings = None
        self._ety_message_to_send = None
        self._sbx_repeats = None
        self._btn_send = None
        self._txt_send_status = None
        self._cbx_max_power_value = None
        self._cbx_lowball_value = None
        self._stx_receive_status = None
        self._btn_copy = None
        self._btn_receive = None

        BaseUi.__init__(self, window_title, window_resizable, bg_color,
                        show_menu)

    def __add_message_hex_to_list(self, value):
        """
        Split message HEX values into list
        """
        for element in value:
            self.__sample_list.append(element)

    def __set_btn_disabled(self):
        """
        Set all button state to disabled
        """
        self._btn_send.configure(state=DISABLED)
        self._btn_save_settings.configure(state=DISABLED)
        self._btn_receive.configure(state=DISABLED)
        self._btn_copy.configure(state=DISABLED)

    def __set_btn_normal(self):
        """
        Set all button state to normal
        """
        self._btn_send.configure(state=NORMAL)
        self._btn_save_settings.configure(state=NORMAL)
        self._btn_receive.configure(state=NORMAL)
        self._btn_copy.configure(state=NORMAL)

    def __action_clear_message(self):
        """
        Delete values from tkinter box
        """
        self._ety_message_to_send.delete(0, END)

    def __action_store_settings(self):
        """
        Store values from tkinter items on rfcat dongle
        """
        self.__set_btn_disabled()

        # frequency
        frequency = int(self._ety_frequency.get())
        self.__logger.info('Frequency:%i', frequency)
        if frequency in range(300000000, 928000000):
            self.rf_object.setFreq(frequency)

        # modulation
        modulation = str(self._selected_modulation.get())
        self.__logger.info('Modulation:%s', modulation)
        if modulation == 'MOD_2FSK':
            self.rf_object.setMdmModulation(MOD_2FSK)
        elif modulation == 'MOD_GFSK':
            self.rf_object.setMdmModulation(MOD_GFSK)
        elif modulation == 'MOD_ASK_OOK':
            self.rf_object.setMdmModulation(MOD_ASK_OOK)
        elif modulation == 'MOD_MSK':
            self.rf_object.setMdmModulation(MOD_MSK)
        else:
            self.rf_object.setMdmModulation(MOD_2FSK)

        # channel
        channel = int(self._selected_channel.get())
        self.__logger.info('Channel:%i', channel)
        if channel in range(0, 10):
            self.rf_object.setChannel(channel)

        # baud rate
        baud_rate = int(self._ety_baud.get())
        self.__logger.info('BaudRate:%i', baud_rate)
        if baud_rate in range(210, 250000):
            self.rf_object.setMdmDRate(baud_rate)

        # deviation
        deviation = int(self._ety_deviation.get())
        self.__logger.info('Deviation:%i', deviation)

        # channel bandwidth
        channel_bandwidth = int(self._ety_channel_bandwidth.get())
        self.__logger.info('ChannelBandwidth:%i', channel_bandwidth)

        # sync mode
        sync_mode = int(self._selected_sync_mode.get())
        self.__logger.info('SyncMode:%i', sync_mode)
        if sync_mode in range(0, 8):
            self.rf_object.setMdmSyncMode(sync_mode)

        # sync word
        sync_word = self._ety_sync_word.get()
        self.__logger.info('SyncWord:%s', sync_word)

        # channel spacing
        channel_spacing = int(self._ety_channel_spacing.get())
        self.__logger.info('ChannelSpacing:%i', channel_spacing)

        # manchester encoding
        manchester_encoding = int(self._cbx_manchester_value.get())
        self.__logger.info('ManchesterEncoding:%i', manchester_encoding)

        self.__set_btn_normal()

    def __action_send_signal(self):
        """
        Send rfcat dongle signal
        """
        self.__set_btn_disabled()
        self._txt_send_status.configure(state='normal')
        self._txt_send_status.delete('0.0', END)

        rf_message = str(self._ety_message_to_send.get()).strip()

        if not rf_message:
            self.__logger.info('No message found')
            self._txt_send_status.insert(END, 'No message to send?')
        else:
            self.__logger.info('Message:%s', rf_message)
            self._txt_send_status.insert(END, 'Message: ' + rf_message)

            # text to binary
            rf_bin_message = ' '.join(format(ord(x), 'b') for x in rf_message)
            self._txt_send_status.insert(END, "\nBinary: " + rf_bin_message)

            # text to hex
            rf_hex_message = rf_message.encode().hex()
            self._txt_send_status.insert(END, "\nHEX: " + rf_hex_message)

            # add hex to list and count bytes
            self.__add_message_hex_to_list(re.findall('..', rf_hex_message))
            byte_count = len(self.__sample_list)
            self._txt_send_status.insert(END, "\nBytes: " + str(byte_count))

            rf_repeats = int(self._sbx_repeats.get())
            self.__logger.info('Repeats:%i', rf_repeats)
            self._txt_send_status.insert(END, "\nRepeats: " + str(rf_repeats))

            rf_datetime = datetime.now()
            self.__logger.info('Date/Time:%s', rf_datetime)
            self._txt_send_status.insert(END, "\nDate: " + str(rf_datetime))

            # convert hex to bytes and start transmit
            send_message = bytes.fromhex(rf_hex_message)
            self.rf_object.RFxmit(data=send_message, repeat=int(rf_repeats))
            self.__logger.info('Transmit of message done (%i)',
                               int(rf_repeats))

            self.rf_object.setModeIDLE()
            self.__logger.info('set USB dongle into idle state')

            self._txt_send_status.insert(
                END, "\nResult: transmit done, USB dongle set to idle")

            self.__sample_list = []

        self._txt_send_status.configure(state='disabled')
        self.__set_btn_normal()

    def __action_receive_signal(self):
        """
        Store settings and start receive signal
        """
        self.__set_btn_disabled()
        self._stx_receive_status.delete(0.0, END)

        # @ToDo: store settings of lowball/max power

        # @ToDo: run signal receiving into ScrolledText incl press key to stop loop
        output = self.rf_object.discover()
        print(output)

        self.__set_btn_normal()

    def __action_copy_to_clipboard(self):
        """
        Copy content of received signal field to clipboard
        """
        self.__set_btn_disabled()

        field_value = self._stx_receive_status.get("1.0", 'end-1c')

        if not field_value:
            self.__logger.info('NoValueForClipboard')
        else:
            self._tk_obj.clipboard_clear()
            self._tk_obj.clipboard_append(field_value)

        self.__set_btn_normal()

    def build_frames(self):
        """
        Build all tkinter frames and start mainloop
        """
        self.__logger.info('BuildAllFrames')

        self.__top_frame()
        self.__middle_frame()
        self.__bottom_frame()

        self.run_app()

    def __top_frame(self):
        """
        Create top frame content
        """
        self._selected_modulation = StringVar(self._tk_obj)
        self._selected_channel = StringVar(self._tk_obj)
        self._selected_sync_mode = StringVar(self._tk_obj)
        self._cbx_manchester_value = IntVar(self._tk_obj)

        frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff')
        frame.grid(column=0, row=0, padx=15, pady=15, sticky=W + E)
        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # headline
        lab_section = Label(frame, text="Default RF Settings")
        lab_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E)
        lab_section.configure(font=self.__FONT_HEADLINE)

        # frequency
        lab_frequency = Label(frame, text='Frequency')
        lab_frequency.grid(column=0, row=1, padx=5, pady=5, sticky=E)
        lab_frequency.configure(font=self.__FONT_STYLE)

        self._ety_frequency = Entry(frame)
        self._ety_frequency.grid(column=1, row=1, padx=5, pady=5, sticky=W)
        self._ety_frequency.configure(font=self.__FONT_STYLE)
        value_frequency = self.rf_object.getFreq()
        self._ety_frequency.insert(0, int(value_frequency[0]))

        # modulation
        lab_modulation = Label(frame, text='Modulation')
        lab_modulation.grid(column=0, row=2, padx=5, pady=5, sticky=E)
        lab_modulation.configure(font=self.__FONT_STYLE)

        opm_modulation = OptionMenu(frame, self._selected_modulation,
                                    *self.__MODULATION_OPTIONS)
        opm_modulation.grid(column=1, row=2, padx=5, pady=5, sticky=W)
        opm_modulation.configure(font=self.__FONT_STYLE)
        value_modulation = self.rf_object.getMdmModulation()
        if value_modulation == 0:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[1])
        elif value_modulation == 16:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[2])
        elif value_modulation == 48:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[3])
        elif value_modulation == 112:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[4])
        else:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[0])

        # channel
        lab_channel = Label(frame, text='Channel')
        lab_channel.grid(column=0, row=3, padx=5, pady=5, sticky=E)
        lab_channel.configure(font=self.__FONT_STYLE)

        sbx_channel = Spinbox(frame, state='readonly')
        sbx_channel.grid(column=1, row=3, padx=5, pady=5, sticky=W)
        sbx_channel.configure(font=self.__FONT_STYLE)
        self._selected_channel.set(self.rf_object.getChannel())
        sbx_channel.configure(from_=0,
                              to=10,
                              increment=1,
                              textvariable=self._selected_channel)

        # baud rate
        lab_baud = Label(frame, text='Baud Rate')
        lab_baud.grid(column=2, row=1, padx=5, pady=5, sticky=E)
        lab_baud.configure(font=self.__FONT_STYLE)

        self._ety_baud = Entry(frame)
        self._ety_baud.grid(column=3, row=1, padx=5, pady=5, sticky=W)
        self._ety_baud.configure(font=self.__FONT_STYLE)
        self._ety_baud.insert(0, int(self.rf_object.getMdmDRate()))

        # deviation
        lab_deviation = Label(frame, text='Deviation')
        lab_deviation.grid(column=2, row=2, padx=5, pady=5, sticky=E)
        lab_deviation.configure(font=self.__FONT_STYLE)

        self._ety_deviation = Entry(frame)
        self._ety_deviation.grid(column=3, row=2, padx=5, pady=5, sticky=W)
        self._ety_deviation.configure(font=self.__FONT_STYLE)
        self._ety_deviation.insert(0, int(self.rf_object.getMdmDeviatn()))
        self._ety_deviation.configure(state='readonly')

        # channel bandwidth
        lab_channel_bandwidth = Label(frame, text='Channel BW')
        lab_channel_bandwidth.grid(column=2, row=3, padx=5, pady=5, sticky=E)
        lab_channel_bandwidth.configure(font=self.__FONT_STYLE)

        self._ety_channel_bandwidth = Entry(frame)
        self._ety_channel_bandwidth.grid(column=3,
                                         row=3,
                                         padx=5,
                                         pady=5,
                                         sticky=W)
        self._ety_channel_bandwidth.configure(font=self.__FONT_STYLE)
        self._ety_channel_bandwidth.insert(0,
                                           int(self.rf_object.getMdmChanBW()))
        self._ety_channel_bandwidth.configure(state='readonly')

        # sync mode
        lab_sync_mode = Label(frame, text='Sync Mode')
        lab_sync_mode.grid(column=4, row=1, padx=5, pady=5, sticky=E)
        lab_sync_mode.configure(font=self.__FONT_STYLE)

        sbx_sync_mode = Spinbox(frame, state='readonly')
        sbx_sync_mode.grid(column=5, row=1, padx=5, pady=5, sticky=W)
        sbx_sync_mode.configure(font=self.__FONT_STYLE)
        self._selected_sync_mode.set(self.rf_object.getMdmSyncMode())
        sbx_sync_mode.configure(from_=0,
                                to=7,
                                increment=1,
                                textvariable=self._selected_sync_mode)

        # sync word
        lab_sync_word = Label(frame, text='Sync Word')
        lab_sync_word.grid(column=4, row=2, padx=5, pady=5, sticky=E)
        lab_sync_word.configure(font=self.__FONT_STYLE)

        self._ety_sync_word = Entry(frame)
        self._ety_sync_word.grid(column=5, row=2, padx=5, pady=5, sticky=W)
        self._ety_sync_word.configure(font=self.__FONT_STYLE)
        self._ety_sync_word.insert(0, self.rf_object.getMdmSyncWord())
        self._ety_sync_word.configure(state='readonly')

        # channel spacing
        lab_channel_spacing = Label(frame, text='Channel Spacing')
        lab_channel_spacing.grid(column=4, row=3, padx=5, pady=5, sticky=E)
        lab_channel_spacing.configure(font=self.__FONT_STYLE)

        self._ety_channel_spacing = Entry(frame)
        self._ety_channel_spacing.grid(column=5,
                                       row=3,
                                       padx=5,
                                       pady=5,
                                       sticky=W)
        self._ety_channel_spacing.configure(font=self.__FONT_STYLE)
        value_channel_spacing = self.rf_object.getMdmChanSpc()
        self._ety_channel_spacing.insert(0, int(value_channel_spacing))
        self._ety_channel_spacing.configure(state='readonly')

        # enable manchester
        lab_manchester = Label(frame, text='Enable Manchester')
        lab_manchester.grid(column=0, row=4, padx=5, pady=5, sticky=E)
        lab_manchester.configure(font=self.__FONT_STYLE)

        cbx_manchester = Checkbutton(frame)
        cbx_manchester.grid(column=1, row=4, padx=5, pady=5, sticky=W)
        if self.rf_object.getEnableMdmManchester() == 1:
            self._cbx_manchester_value.set(1)
        else:
            self._cbx_manchester_value.set(0)
        cbx_manchester.configure(onvalue=1,
                                 offvalue=0,
                                 variable=self._cbx_manchester_value)

        # save settings
        self._btn_save_settings = Button(frame,
                                         text='Save all Settings',
                                         command=self.__action_store_settings)
        self._btn_save_settings.grid(column=5, row=4, padx=5, pady=5)
        self._btn_save_settings.configure(font=self.__FONT_STYLE)
        self._btn_save_settings.bind(
            "<Enter>", lambda event: event.widget.config(fg='indian red'))
        self._btn_save_settings.bind(
            "<Leave>", lambda event: event.widget.config(fg='black'))

    def __middle_frame(self):
        """
        Create middle frame content
        """
        frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff')
        frame.grid(column=0, row=1, padx=15, pady=15, sticky=W + E)
        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # headline
        lab_section = Label(frame, text="Transmit RF Settings")
        lab_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E)
        lab_section.configure(font=self.__FONT_HEADLINE)

        # message
        lab_message_to_send = Label(frame, text='Message')
        lab_message_to_send.grid(column=0, row=1, padx=5, pady=5, sticky=E)
        lab_message_to_send.configure(font=self.__FONT_STYLE)

        self._ety_message_to_send = Entry(frame, width=50)
        self._ety_message_to_send.grid(column=1,
                                       row=1,
                                       padx=5,
                                       pady=5,
                                       sticky=W)
        self._ety_message_to_send.configure(font=self.__FONT_STYLE)

        btn_clear = Button(frame,
                           text='Clear message',
                           command=self.__action_clear_message)
        btn_clear.grid(column=2, row=1, padx=5, pady=5)
        btn_clear.configure(font=self.__FONT_STYLE)

        # repeats
        lab_repeats = Label(frame, text='Repeats')
        lab_repeats.grid(column=3, row=1, padx=5, pady=5, sticky=E)
        lab_repeats.configure(font=self.__FONT_STYLE)

        self._sbx_repeats = Spinbox(frame, width=10)
        self._sbx_repeats.grid(column=4, row=1, padx=5, pady=5, sticky=W)
        self._sbx_repeats.configure(from_=0,
                                    to=50,
                                    increment=5,
                                    state='readonly')
        self._sbx_repeats.configure(font=self.__FONT_STYLE)

        # button send
        self._btn_send = Button(frame,
                                text='Start transmit',
                                command=self.__action_send_signal)
        self._btn_send.grid(column=5, row=1, padx=5, pady=5, sticky=E)
        self._btn_send.configure(font=self.__FONT_STYLE)
        self._btn_send.bind("<Enter>",
                            lambda event: event.widget.config(fg='indian red'))
        self._btn_send.bind("<Leave>",
                            lambda event: event.widget.config(fg='black'))

        self._txt_send_status = Text(frame, height=10)
        self._txt_send_status.grid(columnspan=6,
                                   row=2,
                                   padx=5,
                                   pady=5,
                                   sticky=W + E)
        self._txt_send_status.configure(state='disabled',
                                        borderwidth=1,
                                        relief=SOLID)

    def __bottom_frame(self):
        """
        Create bottom frame content
        """
        self._cbx_max_power_value = IntVar(self._tk_obj)
        self._cbx_lowball_value = IntVar(self._tk_obj)

        frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff')
        frame.grid(column=0, row=2, padx=15, pady=15, sticky=W + E)
        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # headline
        txt_section = Label(frame, text="Receive RF Settings")
        txt_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E)
        txt_section.configure(font=self.__FONT_HEADLINE)

        # lowball
        lab_lowball = Label(frame, text='Lowball')
        lab_lowball.grid(column=0, row=1, padx=5, pady=5, sticky=E)
        lab_lowball.configure(font=self.__FONT_STYLE)

        # @ToDo: implementation lowball
        cbx_lowball = Checkbutton(frame, state='disabled')
        cbx_lowball.grid(column=1, row=1, padx=5, pady=5, sticky=W)
        cbx_lowball.configure(onvalue=1,
                              offvalue=0,
                              variable=self._cbx_lowball_value)

        # max power
        lab_max_power = Label(frame, text='max Power')
        lab_max_power.grid(column=2, row=1, padx=5, pady=5, sticky=E)
        lab_max_power.configure(font=self.__FONT_STYLE)

        # @ToDo: implementation of max power
        cbx_max_power = Checkbutton(frame, state='disabled')
        cbx_max_power.grid(column=3, row=1, padx=5, pady=5, sticky=W)
        cbx_max_power.configure(onvalue=1,
                                offvalue=0,
                                variable=self._cbx_max_power_value)

        # receive signal
        self._btn_receive = Button(frame,
                                   text='Start receive',
                                   command=self.__action_receive_signal)
        self._btn_receive.grid(column=4, row=1, padx=5, pady=5)
        self._btn_receive.configure(font=self.__FONT_STYLE)
        self._btn_receive.bind(
            "<Enter>", lambda event: event.widget.config(fg='indian red'))
        self._btn_receive.bind("<Leave>",
                               lambda event: event.widget.config(fg='black'))

        # copy to clipboard
        self._btn_copy = Button(frame,
                                text='Copy to clipboard',
                                command=self.__action_copy_to_clipboard)
        self._btn_copy.grid(column=5, row=1, padx=5, pady=5)
        self._btn_copy.configure(font=self.__FONT_STYLE)
        self._btn_copy.bind("<Enter>",
                            lambda event: event.widget.config(fg='indian red'))
        self._btn_copy.bind("<Leave>",
                            lambda event: event.widget.config(fg='black'))

        # status
        self._stx_receive_status = ScrolledText(frame)
        self._stx_receive_status.grid(columnspan=6,
                                      row=2,
                                      padx=5,
                                      pady=5,
                                      sticky=W + E)
        self._stx_receive_status.configure(height=12,
                                           font=self.__FONT_STYLE,
                                           borderwidth=1,
                                           relief=SOLID)
示例#39
0
    def __top_frame(self):
        """
        Create top frame content
        """
        self._selected_modulation = StringVar(self._tk_obj)
        self._selected_channel = StringVar(self._tk_obj)
        self._selected_sync_mode = StringVar(self._tk_obj)
        self._cbx_manchester_value = IntVar(self._tk_obj)

        frame = Frame(self._tk_obj, borderwidth=1, relief=SUNKEN, bg='#fff')
        frame.grid(column=0, row=0, padx=15, pady=15, sticky=W + E)
        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)

        # headline
        lab_section = Label(frame, text="Default RF Settings")
        lab_section.grid(columnspan=6, row=0, padx=5, pady=5, sticky=W + E)
        lab_section.configure(font=self.__FONT_HEADLINE)

        # frequency
        lab_frequency = Label(frame, text='Frequency')
        lab_frequency.grid(column=0, row=1, padx=5, pady=5, sticky=E)
        lab_frequency.configure(font=self.__FONT_STYLE)

        self._ety_frequency = Entry(frame)
        self._ety_frequency.grid(column=1, row=1, padx=5, pady=5, sticky=W)
        self._ety_frequency.configure(font=self.__FONT_STYLE)
        value_frequency = self.rf_object.getFreq()
        self._ety_frequency.insert(0, int(value_frequency[0]))

        # modulation
        lab_modulation = Label(frame, text='Modulation')
        lab_modulation.grid(column=0, row=2, padx=5, pady=5, sticky=E)
        lab_modulation.configure(font=self.__FONT_STYLE)

        opm_modulation = OptionMenu(frame, self._selected_modulation,
                                    *self.__MODULATION_OPTIONS)
        opm_modulation.grid(column=1, row=2, padx=5, pady=5, sticky=W)
        opm_modulation.configure(font=self.__FONT_STYLE)
        value_modulation = self.rf_object.getMdmModulation()
        if value_modulation == 0:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[1])
        elif value_modulation == 16:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[2])
        elif value_modulation == 48:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[3])
        elif value_modulation == 112:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[4])
        else:
            self._selected_modulation.set(self.__MODULATION_OPTIONS[0])

        # channel
        lab_channel = Label(frame, text='Channel')
        lab_channel.grid(column=0, row=3, padx=5, pady=5, sticky=E)
        lab_channel.configure(font=self.__FONT_STYLE)

        sbx_channel = Spinbox(frame, state='readonly')
        sbx_channel.grid(column=1, row=3, padx=5, pady=5, sticky=W)
        sbx_channel.configure(font=self.__FONT_STYLE)
        self._selected_channel.set(self.rf_object.getChannel())
        sbx_channel.configure(from_=0,
                              to=10,
                              increment=1,
                              textvariable=self._selected_channel)

        # baud rate
        lab_baud = Label(frame, text='Baud Rate')
        lab_baud.grid(column=2, row=1, padx=5, pady=5, sticky=E)
        lab_baud.configure(font=self.__FONT_STYLE)

        self._ety_baud = Entry(frame)
        self._ety_baud.grid(column=3, row=1, padx=5, pady=5, sticky=W)
        self._ety_baud.configure(font=self.__FONT_STYLE)
        self._ety_baud.insert(0, int(self.rf_object.getMdmDRate()))

        # deviation
        lab_deviation = Label(frame, text='Deviation')
        lab_deviation.grid(column=2, row=2, padx=5, pady=5, sticky=E)
        lab_deviation.configure(font=self.__FONT_STYLE)

        self._ety_deviation = Entry(frame)
        self._ety_deviation.grid(column=3, row=2, padx=5, pady=5, sticky=W)
        self._ety_deviation.configure(font=self.__FONT_STYLE)
        self._ety_deviation.insert(0, int(self.rf_object.getMdmDeviatn()))
        self._ety_deviation.configure(state='readonly')

        # channel bandwidth
        lab_channel_bandwidth = Label(frame, text='Channel BW')
        lab_channel_bandwidth.grid(column=2, row=3, padx=5, pady=5, sticky=E)
        lab_channel_bandwidth.configure(font=self.__FONT_STYLE)

        self._ety_channel_bandwidth = Entry(frame)
        self._ety_channel_bandwidth.grid(column=3,
                                         row=3,
                                         padx=5,
                                         pady=5,
                                         sticky=W)
        self._ety_channel_bandwidth.configure(font=self.__FONT_STYLE)
        self._ety_channel_bandwidth.insert(0,
                                           int(self.rf_object.getMdmChanBW()))
        self._ety_channel_bandwidth.configure(state='readonly')

        # sync mode
        lab_sync_mode = Label(frame, text='Sync Mode')
        lab_sync_mode.grid(column=4, row=1, padx=5, pady=5, sticky=E)
        lab_sync_mode.configure(font=self.__FONT_STYLE)

        sbx_sync_mode = Spinbox(frame, state='readonly')
        sbx_sync_mode.grid(column=5, row=1, padx=5, pady=5, sticky=W)
        sbx_sync_mode.configure(font=self.__FONT_STYLE)
        self._selected_sync_mode.set(self.rf_object.getMdmSyncMode())
        sbx_sync_mode.configure(from_=0,
                                to=7,
                                increment=1,
                                textvariable=self._selected_sync_mode)

        # sync word
        lab_sync_word = Label(frame, text='Sync Word')
        lab_sync_word.grid(column=4, row=2, padx=5, pady=5, sticky=E)
        lab_sync_word.configure(font=self.__FONT_STYLE)

        self._ety_sync_word = Entry(frame)
        self._ety_sync_word.grid(column=5, row=2, padx=5, pady=5, sticky=W)
        self._ety_sync_word.configure(font=self.__FONT_STYLE)
        self._ety_sync_word.insert(0, self.rf_object.getMdmSyncWord())
        self._ety_sync_word.configure(state='readonly')

        # channel spacing
        lab_channel_spacing = Label(frame, text='Channel Spacing')
        lab_channel_spacing.grid(column=4, row=3, padx=5, pady=5, sticky=E)
        lab_channel_spacing.configure(font=self.__FONT_STYLE)

        self._ety_channel_spacing = Entry(frame)
        self._ety_channel_spacing.grid(column=5,
                                       row=3,
                                       padx=5,
                                       pady=5,
                                       sticky=W)
        self._ety_channel_spacing.configure(font=self.__FONT_STYLE)
        value_channel_spacing = self.rf_object.getMdmChanSpc()
        self._ety_channel_spacing.insert(0, int(value_channel_spacing))
        self._ety_channel_spacing.configure(state='readonly')

        # enable manchester
        lab_manchester = Label(frame, text='Enable Manchester')
        lab_manchester.grid(column=0, row=4, padx=5, pady=5, sticky=E)
        lab_manchester.configure(font=self.__FONT_STYLE)

        cbx_manchester = Checkbutton(frame)
        cbx_manchester.grid(column=1, row=4, padx=5, pady=5, sticky=W)
        if self.rf_object.getEnableMdmManchester() == 1:
            self._cbx_manchester_value.set(1)
        else:
            self._cbx_manchester_value.set(0)
        cbx_manchester.configure(onvalue=1,
                                 offvalue=0,
                                 variable=self._cbx_manchester_value)

        # save settings
        self._btn_save_settings = Button(frame,
                                         text='Save all Settings',
                                         command=self.__action_store_settings)
        self._btn_save_settings.grid(column=5, row=4, padx=5, pady=5)
        self._btn_save_settings.configure(font=self.__FONT_STYLE)
        self._btn_save_settings.bind(
            "<Enter>", lambda event: event.widget.config(fg='indian red'))
        self._btn_save_settings.bind(
            "<Leave>", lambda event: event.widget.config(fg='black'))
示例#40
0
    def __init__(self, parent):
        self.is_future = False
        #inputday
        hour = StringVar()
        hour.set('0--23')
        minute = StringVar()
        minute.set('0--59')
        self.btncheck_list = []
        self.plistback = []
        #self.judgepas = []
        self.varp = []  #num与它有关
        num = -1
        self.page = 0
        self.allpage = 0

        self.next = parent

        self.next.geometry('960x930+300+0')
        self.canvas = Canvas(self.next)
        self.canvas.place(relx=0, rely=0, relwidth=1, relheight=1)
        """
        self.vbar = Scrollbar(self.canvas, orient=VERTICAL)  # 竖直滚动条
        self.vbar.place(x=180, width=20, height=180)
        self.vbar.configure(command=self.canvas.yview)
        self.canvas.config( yscrollcommand=self.vbar.set)  # 设置
        self.canvas.create_window((90, 240), window=self.frame)  # create_window
        """
        self.frameAll = Frame(self.canvas, bg='#f0f0f0')
        self.frameAll.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.next.title('车站信息')
        self.nresulte = StringVar()
        self.nresulte.set('北京')  # 显示面板显示结果1,用于显示默认数字0
        self.nresulte1 = StringVar()
        self.nresulte1.set('天津')
        self.nresulte2 = StringVar()
        self.nresulte2.set('2018')
        self.nresulte3 = StringVar()
        self.nresulte3.set('07')
        self.nresulte4 = StringVar()
        self.nresulte4.set('01')
        self.nresulte5 = StringVar()
        self.nresulte5.set(strtime)

        def sendtimeInfor():
            print('我进来了')
            self.top.destroy()

        def show_success():
            self.book_tickets = Toplevel(self.next)
            self.book_tickets.title("抢票")
            self.book_tickets.geometry('480x130+300+0')
            l = Label(self.book_tickets,
                      font=('微软雅黑', 12),
                      fg='green',
                      bd='1',
                      anchor='w',
                      text='抢票成功!!!')
            l.pack()

        def check_book_f():
            if lo.myTickets.book_tickets_on_sale(self.tickets_list[5],
                                                 self.inputday,
                                                 self.plistback):
                show_success()
            print('future')

        def check_book_t():
            if lo.myTickets.book_tickets_on_sale(self.tickets_list[5],
                                                 self.inputday,
                                                 self.plistback):
                show_success()
            print('on sale')

        # self.nresulte = StringVar()
        # self.nresulte.set('请您输入用户名')
        # self.nresulte1 = StringVar()
        # self.nresulte1.set('请您输入密码')
        def sendInfor():

            value = self.entryfromdayyear.get()
            value2 = self.entryfromdaymonth.get()
            value3 = self.entryfromdayday.get()
            #print(value[0:4])
            print(value.isdigit())
            print(len(value))
            print(len(value2))
            if value.isdigit() == False or value2.isdigit(
            ) == False or value3.isdigit() == False or len(value) != 4 or len(
                    value2) != 2 or len(value3) != 2:
                self.nresulte2.set('2018')
                self.nresulte3.set('07')
                self.nresulte3.set('01')
                #print( self.entryfromday.get())
                self.entryfromdayyear = Entry(self.frame,
                                              font=('微软雅黑', 9),
                                              bg='white',
                                              bd='1',
                                              fg='red',
                                              textvariable=self.nresulte2)
                self.entryfromdayyear.place(relx=0.59,
                                            rely=0.17,
                                            width=50,
                                            height=30)
                self.entryfromdaymonth = Entry(self.frame,
                                               font=('微软雅黑', 9),
                                               bg='white',
                                               bd='1',
                                               fg='red',
                                               textvariable=self.nresulte3)
                self.entryfromdaymonth.place(relx=0.68,
                                             rely=0.17,
                                             width=30,
                                             height=30)
                self.entryfromdayday = Entry(self.frame,
                                             font=('微软雅黑', 9),
                                             bg='white',
                                             bd='1',
                                             fg='red',
                                             textvariable=self.nresulte4)
                self.entryfromdayday.place(relx=0.75,
                                           rely=0.17,
                                           width=30,
                                           height=30)

                lo.set_judgecheck(0)

            self.inputday = value + '-' + value2 + '-' + value3
            inputdaydt = datetime.datetime.strptime(self.inputday, '%Y-%m-%d')
            print(self.inputday)
            print(maxday)
            if self.inputday == maxday:
                self.is_future = True

            if self.is_future == True:
                self.top = Toplevel(self.next)
                self.top.title("抢票时间")
                self.top.geometry('480x130+300+0')
                l = Label(self.top,
                          font=('微软雅黑', 12),
                          fg='red',
                          bd='1',
                          anchor='w',
                          text='还无法抢' + self.inputday + '的票,请输入开始抢票时间')
                l.pack()

                lh = Label(self.top,
                           font=('微软雅黑', 12),
                           bg='#D2E9FF',
                           bd='1',
                           fg='black',
                           anchor='w',
                           text='时:')
                lh.place(relx=0.15, rely=0.2, width=70, height=30)
                print("我执行了")
                eh = Entry(self.top,
                           font=('微软雅黑', 12),
                           bg='white',
                           bd='1',
                           fg='#828282',
                           textvariable=hour)

                eh.place(relx=0.35, rely=0.2, width=150, height=30)
                lm = Label(self.top,
                           font=('微软雅黑', 12),
                           bg='#D2E9FF',
                           bd='1',
                           fg='black',
                           anchor='w',
                           text='分:')
                lm.place(relx=0.15, rely=0.45, width=70, height=30)
                em = Entry(self.top,
                           font=('微软雅黑', 12),
                           bg='white',
                           bd='1',
                           fg='#828282',
                           textvariable=minute)

                em.place(relx=0.35, rely=0.45, width=150, height=30)
                btnright = Button(self.top,
                                  font=(
                                      '微软雅黑',
                                      12,
                                  ),
                                  bg='#ffa042',
                                  fg='white',
                                  text='确  定',
                                  activeforeground='#00FFFF',
                                  command=sendtimeInfor)
                btnright.place(relx=0.35, rely=0.7, width=150, height=30)
            if inputdaydt >= todaytime + datetime.timedelta(
                    days=-1) and inputdaydt <= maxdaytime:
                print('good')
                self.labeldtx = Label(self.frametx,
                                      font=('微软雅黑', 12),
                                      bd='9',
                                      fg='red',
                                      anchor='w',
                                      text=' ')
                self.labeldtx.place(relx=0.5, rely=0.17, width=90, height=20)
                lo.set_judgecheck(1)
            else:
                self.labeldtx = Label(self.frametx,
                                      font=('微软雅黑', 12),
                                      bd='9',
                                      fg='red',
                                      anchor='w',
                                      text='时间超限')
                self.labeldtx.place(relx=0.5, rely=0.17, width=90, height=20)
                lo.set_judgecheck(0)

            print(lo.get_judgecheck())
            if lo.get_judgecheck() == 1:
                self.entryfromday = Entry(self.frame,
                                          font=('微软雅黑', 9),
                                          bg='white',
                                          bd='1',
                                          fg='black',
                                          textvariable=self.nresulte2)
                self.entryfromday.place(relx=0.59,
                                        rely=0.17,
                                        width=50,
                                        height=30)
                self.entryfromdayyear.place(relx=0.59,
                                            rely=0.17,
                                            width=50,
                                            height=30)
                self.entryfromdaymonth = Entry(self.frame,
                                               font=('微软雅黑', 9),
                                               bg='white',
                                               bd='1',
                                               fg='black',
                                               textvariable=self.nresulte3)
                self.entryfromdaymonth.place(relx=0.68,
                                             rely=0.17,
                                             width=30,
                                             height=30)
                self.entryfromdayday = Entry(self.frame,
                                             font=('微软雅黑', 9),
                                             bg='white',
                                             bd='1',
                                             fg='black',
                                             textvariable=self.nresulte4)
                self.entryfromdayday.place(relx=0.75,
                                           rely=0.17,
                                           width=30,
                                           height=30)

                self.tickets_list = lo.myTickets.get_tickets_info(
                    self.entryfrom.get(), self.entryto.get(), self.inputday,
                    self.is_future)

                numtl = 0
                #self.mylb.delete(0,END)
                self.tllen = len(self.tickets_list)

                self.page = 1
                self.allpage = int((self.tllen) / 20) + 1
                for item in self.tickets_list[0:20]:
                    placey = numtl * 0.05
                    string = '  '
                    for k, v in item.items():
                        if k != 'bookable' and k != 'book_btn':
                            string = string + '{:^8}'.format(v)
                    #print(string)

                    self.stationtickets_list = Label(self.mylb,
                                                     font=('微软雅黑', 10),
                                                     bg='white',
                                                     bd='9',
                                                     width=90,
                                                     height=1,
                                                     fg='black',
                                                     anchor='w',
                                                     text=string)
                    self.stationtickets_list.place(relx=0, rely=placey)

                    if item['bookable'] == False:
                        if self.is_future == True:

                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_f)
                            self.btncheck.place(relx=0.88, rely=placey)
                        else:
                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_t)
                            self.btncheck.place(relx=0.88, rely=placey)
                    else:
                        self.btncheck = Button(self.mylb,
                                               font=('微软雅黑', 11),
                                               width=9,
                                               height=1,
                                               bg='#ffa042',
                                               fg='black',
                                               text='预  订',
                                               activeforeground='#00FFFF',
                                               command=check_book_t)
                        self.btncheck.place(relx=0.88, rely=placey)

                    #strnum = str(numtl)+'  '+string
                    numtl = numtl + 1
                    print('here')
                    #print(strnum)
                    self.mylb.insert(END, self.stationtickets_list)
                    self.mylb.insert(END, self.btncheck)
                    self.labelnum = Label(self.frameAll,
                                          font=('微软雅黑', 12, 'bold'),
                                          fg='black',
                                          text=self.page)
                    self.labelnum.place(relx=0.475,
                                        rely=0.92,
                                        width=20,
                                        height=30)
                    self.labelnum3 = Label(self.frameAll,
                                           font=('微软雅黑', 12, 'bold'),
                                           fg='black',
                                           text=self.allpage)
                    self.labelnum3.place(relx=0.505,
                                         rely=0.92,
                                         width=20,
                                         height=30)
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        fg='black',
                                        text='上 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_last)
                    self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
                    '''
                    self.frame4 = Frame(self.frameAll, width=150, height=300)
                    self.frame4.place(relx=0.03,rely=0.26)
                    '''

            lo.set_judgecheck(-1)

        def bindcbtnpas():

            for num in range(len(self.varp)):
                print(self.varp[num].get())
                if self.varp[num].get() == 1:
                    a = 0
                    for num1 in self.plistback:
                        if self.passengers[num] == num1:
                            a = 1
                    if a == 0:
                        self.plistback.append((self.passengers[num]))
                if self.varp[num].get() == 0:
                    b = 0
                    for num1 in self.plistback:
                        if self.passengers[num] == num1:
                            b = 1
                    if b == 1:
                        self.plistback.remove((self.passengers[num]))
            print(self.plistback)

        self.frame = Frame(self.frameAll, bg='#D2E9FF', width=950, height=45)
        self.frame.place(relx=0.2, rely=0.03)
        self.frametx = Frame(self.frameAll, width=950, height=37)
        self.frametx.place(relx=0.2, rely=0.08)
        # place,pace,grid
        self.labely = Label(self.frame,
                            font=('微软雅黑', 12),
                            bg='#D2E9FF',
                            bd='9',
                            fg='black',
                            anchor='w',
                            text='出发地:')
        self.labely.place(relx=0.05, rely=0.17, width=70, height=30)
        self.labelm = Label(self.frame,
                            font=('微软雅黑', 12),
                            bg='#D2E9FF',
                            bd='9',
                            fg='black',
                            anchor='w',
                            text='目的地:')
        self.labelm.place(relx=0.275, rely=0.17, width=70, height=30)
        self.labeld = Label(self.frame,
                            font=('微软雅黑', 12),
                            bg='#D2E9FF',
                            bd='9',
                            fg='black',
                            anchor='w',
                            text='出发日期:')
        self.labeld.place(relx=0.5, rely=0.17, width=90, height=30)
        self.labeldtx = Label(self.frametx,
                              font=('微软雅黑', 9),
                              bd='9',
                              fg='blue',
                              anchor='w',
                              textvariable=self.nresulte5)
        self.labeldtx.place(relx=0.05, rely=0.1, width=250, height=30)
        self.labeldy = Label(self.frame,
                             font=('微软雅黑', 12),
                             bg='#D2E9FF',
                             bd='9',
                             fg='black',
                             anchor='w',
                             text='年')
        self.labeldy.place(relx=0.64, rely=0.17, width=90, height=30)
        self.labeldm = Label(self.frame,
                             font=('微软雅黑', 12),
                             bg='#D2E9FF',
                             bd='9',
                             fg='black',
                             anchor='w',
                             text='月')
        self.labeldm.place(relx=0.71, rely=0.17, width=90, height=30)
        self.labeldd = Label(self.frame,
                             font=('微软雅黑', 12),
                             bg='#D2E9FF',
                             bd='9',
                             fg='black',
                             anchor='w',
                             text='日')
        self.labeldd.place(relx=0.78, rely=0.17, width=90, height=30)
        self.entryfrom = Entry(self.frame,
                               font=('微软雅黑', 9),
                               bg='white',
                               bd='1',
                               fg='#828282',
                               textvariable=self.nresulte)

        self.entryfrom.place(relx=0.12, rely=0.17, width=150, height=30)
        self.entryto = Entry(self.frame,
                             font=('微软雅黑', 9),
                             bg='white',
                             bd='1',
                             fg='#828282',
                             textvariable=self.nresulte1)
        self.entryto.place(relx=0.345, rely=0.17, width=150, height=30)
        self.entryfromdayyear = Entry(self.frame,
                                      font=('微软雅黑', 9),
                                      bg='white',
                                      bd='1',
                                      fg='#828282',
                                      textvariable=self.nresulte2)
        self.entryfromdayyear.place(relx=0.59, rely=0.17, width=50, height=30)
        self.entryfromdaymonth = Entry(self.frame,
                                       font=('微软雅黑', 9),
                                       bg='white',
                                       bd='1',
                                       fg='#828282',
                                       textvariable=self.nresulte3)
        self.entryfromdaymonth.place(relx=0.68, rely=0.17, width=30, height=30)
        self.entryfromdayday = Entry(self.frame,
                                     font=('微软雅黑', 9),
                                     bg='white',
                                     bd='1',
                                     fg='#828282',
                                     textvariable=self.nresulte4)
        self.entryfromdayday.place(relx=0.75, rely=0.17, width=30, height=30)
        self.btncheck = Button(self.frame,
                               font=(
                                   '微软雅黑',
                                   12,
                               ),
                               bg='#ffa042',
                               fg='white',
                               text='查  询',
                               activeforeground='#00FFFF',
                               command=sendInfor)
        self.btncheck.place(relx=0.85, rely=0.17, width=80, height=30)
        '''
            
        def bindcbtn():

            if var.get() == 1:
                print('a')
                # 跳出函数
            else:
                print('b')
            if var1.get() == 1:
                print('a1')
            else:
                print('b1')
            if var2.get() == 1:
                print('a2')
            else:
                print('b2')
            if var3.get() == 1:
                print('a3')
            else:
                print('b3')
            if var4.get() == 1:
                print('a4')
            else:
                print('b4')
            if var5.get() == 1:
                print('a5')
            else:
                print('b5')


        self.frame1 = Frame(self.frameAll, bg='white', width=950, height=45, bd='1')
        self.frame1.place(relx=0.2, rely=0.12)

        var = IntVar()
        var1 = IntVar()
        var2 = IntVar()
        var3 = IntVar()
        var4 = IntVar()
        var5 = IntVar()
        

        self.checkbutton = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                       text='全部', variable=var, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton.place(relx=0.05, rely=0.17, width=70, height=30)
        #self.checkbutton.select()
        self.checkbutton1 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='GC-高铁/城际', variable=var1, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton1.place(relx=0.2, rely=0.17, width=110, height=30)
        self.checkbutton2 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='D-动车', variable=var2, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton2.place(relx=0.35, rely=0.17, width=70, height=30)
        self.checkbutton3 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='Z-直达', variable=var3, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton3.place(relx=0.5, rely=0.17, width=70, height=30)
        self.checkbutton4 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='T-特快', variable=var4, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton4.place(relx=0.65, rely=0.17, width=70, height=30)
        self.checkbutton5 = Checkbutton(self.frame1, font=('微软雅黑', 9), bg='white', bd='9', fg='black', anchor='w',
                                        text='K-快速', variable=var5, onvalue=1, offvalue=0, command=bindcbtn)
        self.checkbutton5.place(relx=0.8, rely=0.17, width=70, height=30)

        
        '''

        self.passengers = lo.myTickets._get_passengers()

        self.frame2 = Frame(self.frameAll, width=150, height=300)
        self.frame2.place(relx=0.03, rely=0.03)
        for pas in self.passengers:
            #self.judge.append(0)
            num = num + 1
            self.varp.append(IntVar())
            self.checkbuttonp = Checkbutton(self.frame2,
                                            font=('微软雅黑', 9),
                                            text=pas,
                                            anchor='w',
                                            variable=self.varp[num],
                                            onvalue=1,
                                            offvalue=0,
                                            command=bindcbtnpas)
            self.checkbuttonp.grid()
            '''
        'trainNumber':'',
                'fromStation':'',
                'toStation':'',
                'departTime':'',
                'arriveTime':'',
                'period':'',
                'specialSeat':'',
                'oneClassSeat':'',
                'twoClassSeat':'',
                'advancedSoftSleeper':'',
                'softSleeper':'',
                'hardSleeper':'',
                'motionSleeper':'',
                'softSeat':'',
                'hardSeat':'',
                'noSeat':'',
                'bookable':False,
                'book_btn':None 
        '''
        self.frame3 = Frame(self.frameAll, bg='#D2E9FF', width=950, height=40)
        self.frame3.place(relx=0.2, rely=0.12)
        self.stationlabal = Label(
            self.frame3,
            font=('微软雅黑', 10, 'bold'),
            anchor='w',
            bg='#D2E9FF',
            fg='black',
            text=
            '   车次   出发站   到达站   出发时间   到达时间   历时   特等座   一等座   二等座   高级软卧   软卧   硬卧   动卧   软座   硬座   无座'
        )
        self.stationlabal.place(relx=0, rely=0, relwidth=1, relheight=1)
        self.mylb = Listbox(self.frameAll,
                            font=('微软雅黑', 15),
                            bd='0',
                            width=79,
                            height=20)
        #self.sl = Scrollbar(self.canvas)
        #self.sl.pack(side=RIGHT, fill=Y)
        #self.mylb['yscrollcommand'] = self.sl.set
        #self.sl['command']=self.mylb.yview
        self.mylb.place(relx=0.2, rely=0.21)
        for item in range(0, 20):
            self.mylb.insert(END, ' ')

        def page_last():
            if self.page > 1:

                self.page = self.page - 1
                if self.page < self.allpage:
                    self.btndown = Button(self.frameAll,
                                          font=(
                                              '微软雅黑',
                                              12,
                                          ),
                                          bg='#ffa042',
                                          fg='black',
                                          text='下 一 页',
                                          activeforeground='#00FFFF',
                                          command=page_next)
                    self.btndown.place(relx=0.52,
                                       rely=0.92,
                                       width=80,
                                       height=30)
                if self.page == 1:
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        fg='black',
                                        text='上 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_last)
                    self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
                self.labelnum = Label(self.frameAll,
                                      font=('微软雅黑', 12, 'bold'),
                                      fg='black',
                                      text=self.page)
                self.labelnum.place(relx=0.475, rely=0.92, width=20, height=30)
                numtl = 0
                self.begin = (self.page - 1) * 20
                self.end = self.page * 20
                for item in self.tickets_list[self.begin:self.end]:
                    placey = numtl * 0.05
                    string = '  '
                    for k, v in item.items():
                        if k != 'bookable' and k != 'book_btn':
                            string = string + '{:^8}'.format(v)

                    self.stationtickets_list = Label(self.mylb,
                                                     font=('微软雅黑', 10),
                                                     bg='white',
                                                     bd='9',
                                                     width=90,
                                                     height=1,
                                                     fg='black',
                                                     anchor='w',
                                                     text=string)
                    self.stationtickets_list.place(relx=0, rely=placey)

                    if item['bookable'] == False:
                        if self.is_future == True:

                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_f)
                            self.btncheck.place(relx=0.88, rely=placey)
                        else:
                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_t)
                            self.btncheck.place(relx=0.88, rely=placey)
                    else:
                        self.btncheck = Button(self.mylb,
                                               font=('微软雅黑', 11),
                                               width=9,
                                               height=1,
                                               bg='#ffa042',
                                               fg='black',
                                               text='预  订',
                                               activeforeground='#00FFFF',
                                               command=check_book_t)
                        self.btncheck.place(relx=0.88, rely=placey)
                    #strnum = str(numtl)+'  '+string
                    numtl = numtl + 1
                    #print('here')

                    self.mylb.insert(END, self.stationtickets_list)
                    self.mylb.insert(END, self.btncheck)

        def page_next():
            if self.page < self.allpage:

                self.page = self.page + 1
                if self.page > 1:
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        bg='#ffa042',
                                        fg='black',
                                        text='上 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_last)
                    self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
                if self.page == self.allpage:
                    self.btnup = Button(self.frameAll,
                                        font=(
                                            '微软雅黑',
                                            12,
                                        ),
                                        fg='black',
                                        text='下 一 页',
                                        activeforeground='#00FFFF',
                                        command=page_next)
                    self.btnup.place(relx=0.52, rely=0.92, width=80, height=30)
                    for item in range(20 - self.tllen // 20):
                        placeybug = 0.95 - item * 0.05
                        self.stationtickets_list = Label(self.mylb,
                                                         font=('微软雅黑', 12),
                                                         bg='white',
                                                         bd='9',
                                                         width=100,
                                                         height=1,
                                                         fg='black',
                                                         anchor='w',
                                                         text=' ')
                        self.stationtickets_list.place(relx=0, rely=placeybug)
                self.labelnum = Label(self.frameAll,
                                      font=('微软雅黑', 12, 'bold'),
                                      fg='black',
                                      text=self.page)
                self.labelnum.place(relx=0.475, rely=0.92, width=20, height=30)
                numtl = 0
                self.begin = (self.page - 1) * 20
                self.end = self.page * 20
                for item in self.tickets_list[self.begin:self.end]:
                    placey = numtl * 0.05
                    string = '  '
                    for k, v in item.items():
                        if k != 'bookable' and k != 'book_btn':
                            string = string + '{:^8}'.format(v)

                    self.stationtickets_list = Label(self.mylb,
                                                     font=('微软雅黑', 10),
                                                     bg='white',
                                                     bd='9',
                                                     width=90,
                                                     height=1,
                                                     fg='black',
                                                     anchor='w',
                                                     text=string)
                    self.stationtickets_list.place(relx=0, rely=placey)

                    if item['bookable'] == False:
                        if self.is_future == True:

                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_f)
                            self.btncheck.place(relx=0.88, rely=placey)
                        else:
                            self.btncheck = Button(self.mylb,
                                                   font=('微软雅黑', 11),
                                                   width=9,
                                                   height=1,
                                                   fg='black',
                                                   text='预  订',
                                                   activeforeground='#00FFFF',
                                                   command=check_book_t)
                            self.btncheck.place(relx=0.88, rely=placey)
                    else:
                        self.btncheck = Button(self.mylb,
                                               font=('微软雅黑', 11),
                                               width=9,
                                               height=1,
                                               bg='#ffa042',
                                               fg='black',
                                               text='预  订',
                                               activeforeground='#00FFFF',
                                               command=check_book_t)
                        self.btncheck.place(relx=0.88, rely=placey)

                    #strnum = str(numtl)+'  '+string
                    numtl = numtl + 1
                    #print('here')
                    #print(self.page)
                    self.mylb.insert(END, self.stationtickets_list)
                    self.mylb.insert(END, self.btncheck)
            else:
                print('wo zai zhe li')

        self.btnup = Button(self.frameAll,
                            font=(
                                '微软雅黑',
                                12,
                            ),
                            bg='#ffa042',
                            fg='black',
                            text='上 一 页',
                            activeforeground='#00FFFF',
                            command=page_last)
        self.btnup.place(relx=0.42, rely=0.92, width=80, height=30)
        self.btndown = Button(self.frameAll,
                              font=(
                                  '微软雅黑',
                                  12,
                              ),
                              bg='#ffa042',
                              fg='black',
                              text='下 一 页',
                              activeforeground='#00FFFF',
                              command=page_next)
        self.btndown.place(relx=0.52, rely=0.92, width=80, height=30)
        self.labelnum = Label(self.frameAll,
                              font=('微软雅黑', 12, 'bold'),
                              fg='black',
                              text='-')
        self.labelnum.place(relx=0.475, rely=0.92, width=20, height=30)
        self.labelnum2 = Label(self.frameAll,
                               font=('微软雅黑', 12, 'bold'),
                               fg='black',
                               text='/')
        self.labelnum2.place(relx=0.493, rely=0.92, width=10, height=30)
        self.labelnum3 = Label(self.frameAll,
                               font=('微软雅黑', 12, 'bold'),
                               fg='black',
                               text='-')
        self.labelnum3.place(relx=0.50, rely=0.92, width=20, height=30)
        """
root.title("TT")
root.geometry("500x200+100+200")

frame = Frame(root, height=720, width=720, bd=4)
frame.grid()
sname = StringVar()
l1 = Label(frame, text="Enter Subject name:-")
l1.grid(row=0, column=0, sticky="e")
e1 = Entry(frame, textvariable=sname)
e1.grid(row=0, column=1)
staff = StringVar() 
l2 = Label(frame, text="Enter Staff name:-")
l2.grid(row=1, column=0, sticky="e")
e2 = Entry(frame, textvariable=staff)
e2.grid(row=1, column=1)
h = IntVar()
l3 = Label(frame, text="Enter Number of hours:-")
l3.grid(row=2, column=0, sticky="e")
e3 = Entry(frame, textvariable=h)
e3.grid(row=2, column=1)
d = StringVar()
l4 = Label(frame, text="Theory/Practical:-")
l4.grid(row=3, column=0, sticky="e")
e4 = Entry(frame, textvariable=d)
e4.grid(row=3, column=1)
y = IntVar()
l5 = Label(frame, text="Year:-")
l5.grid(row=4, column=0, sticky="e")
e5 = Entry(frame, textvariable=y)
e5.grid(row=4, column=1)
    def refreshSettings(self):

        self.useManualPosition = False
        self.settingValues = settings.Settings()

        self.showoutput = int(
            self.settingValues.getDebugSettingValue('showoutput'))

        self.timeinmins = int(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoatstart = int(
            self.settingValues.getAppSettingValue('autoonatstart'))
        self.autooption = int(
            self.settingValues.getAppSettingValue('autoselectedoption'))

        self.autocombo.current(self.autooption)  #set the selected item

        self.MAX_TIMER = self.timeinmins * 60

        self.serverPortVar = StringVar()
        self.serverVar = IntVar()

        self.serverPortVar.set(
            int(self.settingValues.getNetworkSettingValue('serverport')))
        self.serverVar.set(
            self.settingValues.getNetworkSettingValue('serverip'))

        self.gpsOption = self.settingValues.getGPSHardwareSettingValue(
            'option')

        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()

        self.gpsComPortVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpscomport'))
        self.gpsComPortSpeedVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpsportspeed'))
        self.maidPreceision.set(
            self.settingValues.getAppSettingValue('precision'))
        self.autoTimeVar.set(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoGridToJS8Call.set(
            self.settingValues.getAppSettingValue('autoonatstart'))

        self.autoGridCheck.configure(text="Enable Auto update every " +
                                     str(self.timeinmins) + " mins.")

        if self.gpsOption == 'None':
            self.autoGridCheck.configure(state='disabled')
            self.autoGridToJS8Call.set(0)
        else:
            self.autoGridCheck.configure(state='normal')

        if self.gpsl != None:
            self.gpsl.setPrecision(
                int(self.settingValues.getAppSettingValue('precision')))
            self.gpsl.setShowDebug(self.showoutput)

        if self.gpsOptionBeforeRefresh != self.gpsOption:
            if self.gpsl != None:
                print('Shutting down GPS Listener')

                #self.gpsl.destroy()
                if isinstance(self.gpsl, networkGPSListener.netWorkGPS):
                    self.gpsl.teminate()

                self.gpsl.setReadGPS(False)
                self.gpsl.join()
                self.gpsl = None

            if self.gpsOption != 'None':
                print('Determine GPS Listener')
                if self.gpsOption == 'GPSD':
                    print('Starting GPSD GPS Listener')
                    self.gpsl = gpsdGPSListener.GpsListener(
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                elif self.gpsOption == 'Network':
                    print('Starting Network GPS Listener')
                    self.gpsl = networkGPSListener.netWorkGPS(
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpscomport'),
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpsportspeed'),
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                elif self.gpsOption == 'Windows Location Services':
                    print('Using Windows Location Services')
                    self.gpsl = windowsLocation.locationservices(
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                elif self.gpsOption == 'Manual':
                    print('Manual Position, not suing GPS')

                    self.useManualPosition = True
                    self.manualposition = self.settingValues.getGPSHardwareSettingValue(
                        'gpscomport')
                else:
                    print('Running serial gps again')
                    self.gpsl = serialGPSlistener.GPSListener(
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpscomport'),
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpsportspeed'),
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                if self.gpsl != None:
                    self.gpsl.start()
            else:
                print('Setting thread to None')
                self.gpsl = None
        self.gpsOptionBeforeRefresh = self.gpsOption
示例#43
0
def nominee():

    global tbalance

    tbalance = IntVar(window3)
    nomname = tkinter.Label(window3,
                            text='Name of nominee :',
                            font=('Gabriola'),
                            bg='light blue',
                            fg='black')
    nomname.place(x=10, y=465)
    fnameno = tkinter.Label(window3,
                            text='Frist Name :',
                            font=('Gabriola'),
                            bg='light blue',
                            fg='black')
    fnameno.place(x=10, y=495)
    nomname1 = tkinter.Entry(window3, bd=4)
    nomname1.place(x=100, y=505, height=20, width=100)
    mnameno = tkinter.Label(window3,
                            text='Middle Name :',
                            font=('Gabriola'),
                            bg='light blue',
                            fg='black')
    mnameno.place(x=230, y=495)
    mmnameno = tkinter.Entry(window3, bd=4)
    mmnameno.place(x=330, y=505, height=20, width=100)
    lnameno = tkinter.Label(window3,
                            text='Last Name :',
                            font=('Gabriola'),
                            bg='light blue',
                            fg='black')
    lnameno.place(x=450, y=495)
    llnameno = tkinter.Entry(window3, bd=4)
    llnameno.place(x=530, y=505, height=20, width=100)
    dobno = tkinter.Label(window3,
                          text='Date of Birth :',
                          font=('Gabriola'),
                          bg='light blue',
                          fg='black')
    dobno.place(x=10, y=545)
    dno = tkinter.Label(window3,
                        text='Date :',
                        font=('Gabriola'),
                        bg='light blue',
                        fg='black')
    dno.place(x=95, y=545)
    combono = Combobox(window3)
    combono['values'] = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
                         17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
                         30, 31)
    combono.current()
    combono.place(x=140, y=555, height=20, width=50)
    mno = tkinter.Label(window3,
                        text='Month :',
                        font=('Gabriola'),
                        bg='light blue',
                        fg='black')
    mno.place(x=200, y=545)
    combo1no = Combobox(window3)
    combo1no['values'] = ('January', 'Feberary', 'March', 'April', 'May',
                          'June', 'July', 'August', 'Semptember', 'October',
                          'November', 'December')
    combo1no.current()
    combo1no.place(x=260, y=555, height=20, width=75)
    yno = tkinter.Label(window3,
                        text='Year :',
                        font=('Gabriola'),
                        bg='light blue',
                        fg='black')
    yno.place(x=350, y=545)
    yyno = tkinter.Entry(window3, bd=4)
    yyno.place(x=400, y=555, height=20, width=75)
    bal = tkinter.Label(window3,
                        text='Opening balance :',
                        font=('Gabriola'),
                        bg='light blue',
                        fg='black')
    bal.place(x=15, y=600)
    balno = tkinter.Entry(window3, bd=4, textvariable=tbalance)
    balno.place(x=120, y=610, height=20, width=100)

    submit()
示例#44
0
class CheckBar(Frame):
    """ Tkinter based class for generating a row of check-buttons
    which a user can select. The methods used to generate the plots
    are called from here.
    """
    def __init__(self, parent=None, picks=None):
        Frame.__init__(self, parent)

        self.frame = parent

        picks = picks or list()

        self.check_btn = dict()
        self.check_vars = list()

        self.board_num = IntVar()
        self.boards_shown = 0

        self.fig = object()
        self.cnv = object()
        self.label_txt = object()
        self.shot_label = object()
        self.animator_obj = object()

        self.xml_info = dict()

        self.boards = {
            0: 'SSP',
            1: 'XGRAD',
            2: 'YGRAD',
            3: 'ZGRAD',
            4: 'RHO1',
            5: 'RHO2',
            6: 'THETA1',
            7: 'THETA2'
        }

        for i, pick in enumerate(picks):
            self.check_vars.append(IntVar())
            self.check_vars[i].set(0)
            self.check_btn[i] = Checkbutton(self.frame,
                                            text=pick,
                                            variable=self.check_vars[i])

        for i, button in enumerate(self.check_btn):
            self.check_btn[i]["command"] = \
                lambda board=self.check_vars[i], id_num=button: self.toggle(board, id_num)

            self.check_btn[i].pack(side="left",
                                   anchor="nw",
                                   fill="x",
                                   expand=True)

    def toggle(self, board, id_num):

        self.board_num.set(id_num)

        if board.get() == 1:
            board.set(1)
            self.boards_shown += 1
            shot_data = self.data_gen(id_num)
            self.animator_obj.add_shots(self.check_btn[id_num], shot_data)
            self.animator_obj.add_subplot(self.check_btn[id_num],
                                          self.boards_shown,
                                          self.boards[id_num])
            self.play_choice()

        else:
            board.set(0)
            self.boards_shown -= 1
            self.animator_obj.remove_shots(self.check_btn[id_num])
            self.animator_obj.remove_subplot(self.check_btn[id_num])

    def data_gen(self, board_num):
        # Provides the x, y information from all shot for a board
        exciter_data = board_waveform(self.xml_info["waveforms"][0], board_num,
                                      self.xml_info["xml_count"])
        return exciter_data

    def play_choice(self):
        iterator = self.animator_obj.new_frame_seq()
        self.animator_obj.pause = False
        self.animator_obj.display_state.set("Stop")

        self.animator_obj._start()
        self.cnv()
        for t in iterator:
            self.animator_obj._draw_frame(t)
            self.animator_obj._post_draw(t)
示例#45
0
# color code box

color_box = tkinter.Label(input_frame, bg='black', height=6, width=15)
color_tup = tkinter.Label(input_frame, text='(0), (0), (0)')
color_hex = tkinter.Label(input_frame, text='#FFFFFF')

# pack them
color_box.grid(row=1, column=3, columnspan=2,
               padx=35, pady=10, ipadx=10, ipady=10)
color_tup.grid(row=2, column=3, columnspan=2)
color_hex.grid(row=3, column=3, columnspan=2)

# doing the output frame
stored_colors = {}
stored_color = IntVar()

for i in range(6):
    radio = tkinter.Radiobutton(output_frame, variable=stored_color, value=i)
    radio.grid(row=i, column=0, sticky='w')

    recall_button = tkinter.Button(output_frame, text='Recall', state=DISABLED)
    recall_button.grid(row=i, column=1, padx=20, )

    new_color_tuple = tkinter.Label(output_frame, text='(255), (255), (255)')
    new_color_hex = tkinter.Label(output_frame, text='#FFFFFF')

    new_outer_color_box = tkinter.Label(
        output_frame, bg='black', height=1, width=3)
    new_inner_color_box = tkinter.Label(
        output_frame, bg='white', height=1, width=3)
示例#46
0
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """

    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title("Shift Reduce Parser Application")

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10)  # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1["text"] = ""

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget("size"))

        self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = Font(family="helvetica", size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill="both", side="left", padx=2)
        self._prodlist_label = Label(
            self._prodframe, font=self._boldfont, text="Available Reductions"
        )
        self._prodlist_label.pack()
        self._prodlist = Listbox(
            self._prodframe,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._prodlist.pack(side="right", fill="both", expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert("end", (" %s" % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:  # len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient="vertical")
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a production, apply it.
        self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind("<Motion>", self._highlight_hover)
        self._prodlist.bind("<Leave>", self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind("<Control-q>", self.destroy)
        self._top.bind("<Control-x>", self.destroy)
        self._top.bind("<Alt-q>", self.destroy)
        self._top.bind("<Alt-x>", self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind("<space>", self.step)
        self._top.bind("<s>", self.shift)
        self._top.bind("<Alt-s>", self.shift)
        self._top.bind("<Control-s>", self.shift)
        self._top.bind("<r>", self.reduce)
        self._top.bind("<Alt-r>", self.reduce)
        self._top.bind("<Control-r>", self.reduce)
        self._top.bind("<Delete>", self.reset)
        self._top.bind("<u>", self.undo)
        self._top.bind("<Alt-u>", self.undo)
        self._top.bind("<Control-u>", self.undo)
        self._top.bind("<Control-z>", self.undo)
        self._top.bind("<BackSpace>", self.undo)

        # Misc
        self._top.bind("<Control-p>", self.postscript)
        self._top.bind("<Control-h>", self.help)
        self._top.bind("<F1>", self.help)
        self._top.bind("<Control-g>", self.edit_grammar)
        self._top.bind("<Control-t>", self.edit_sentence)

        # Animation speed control
        self._top.bind("-", lambda e, a=self._animate: a.set(20))
        self._top.bind("=", lambda e, a=self._animate: a.set(10))
        self._top.bind("+", lambda e, a=self._animate: a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill="none", side="bottom")
        Button(
            buttonframe,
            text="Step",
            background="#90c0d0",
            foreground="black",
            command=self.step,
        ).pack(side="left")
        Button(
            buttonframe,
            text="Shift",
            underline=0,
            background="#90f090",
            foreground="black",
            command=self.shift,
        ).pack(side="left")
        Button(
            buttonframe,
            text="Reduce",
            underline=0,
            background="#90f090",
            foreground="black",
            command=self.reduce,
        ).pack(side="left")
        Button(
            buttonframe,
            text="Undo",
            underline=0,
            background="#f0a0a0",
            foreground="black",
            command=self.undo,
        ).pack(side="left")

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(
            label="Reset Parser", underline=0, command=self.reset, accelerator="Del"
        )
        filemenu.add_command(
            label="Print to Postscript",
            underline=0,
            command=self.postscript,
            accelerator="Ctrl-p",
        )
        filemenu.add_command(
            label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x"
        )
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(
            label="Edit Grammar",
            underline=5,
            command=self.edit_grammar,
            accelerator="Ctrl-g",
        )
        editmenu.add_command(
            label="Edit Text",
            underline=5,
            command=self.edit_sentence,
            accelerator="Ctrl-t",
        )
        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(
            label="Step", underline=1, command=self.step, accelerator="Space"
        )
        rulemenu.add_separator()
        rulemenu.add_command(
            label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s"
        )
        rulemenu.add_command(
            label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r"
        )
        rulemenu.add_separator()
        rulemenu.add_command(
            label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u"
        )
        menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(
            label="Show Grammar",
            underline=0,
            variable=self._show_grammar,
            command=self._toggle_grammar,
        )
        viewmenu.add_separator()
        viewmenu.add_radiobutton(
            label="Tiny",
            variable=self._size,
            underline=0,
            value=10,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Small",
            variable=self._size,
            underline=0,
            value=12,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Medium",
            variable=self._size,
            underline=0,
            value=14,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Large",
            variable=self._size,
            underline=0,
            value=18,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Huge",
            variable=self._size,
            underline=0,
            value=24,
            command=self.resize,
        )
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(
            label="No Animation", underline=0, variable=self._animate, value=0
        )
        animatemenu.add_radiobutton(
            label="Slow Animation",
            underline=0,
            variable=self._animate,
            value=20,
            accelerator="-",
        )
        animatemenu.add_radiobutton(
            label="Normal Animation",
            underline=0,
            variable=self._animate,
            value=10,
            accelerator="=",
        )
        animatemenu.add_radiobutton(
            label="Fast Animation",
            underline=0,
            variable=self._animate,
            value=4,
            accelerator="+",
        )
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        helpmenu.add_command(
            label="Instructions", underline=0, command=self.help, accelerator="F1"
        )
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3)
        self._lastoper_label = Label(
            feedbackframe, text="Last Operation:", font=self._font
        )
        self._lastoper_label.pack(side="left")
        lastoperframe = Frame(feedbackframe, relief="sunken", border=1)
        lastoperframe.pack(fill="x", side="right", expand=1, padx=5)
        self._lastoper1 = Label(
            lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font
        )
        self._lastoper2 = Label(
            lastoperframe,
            anchor="w",
            width=30,
            foreground="#004040",
            background="#f0f0f0",
            font=self._font,
        )
        self._lastoper1.pack(side="left")
        self._lastoper2.pack(side="left", fill="x", expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(
            parent,
            background="white",
            width=525,
            closeenough=10,
            border=2,
            relief="sunken",
        )
        self._cframe.pack(expand=1, fill="both", side="top", pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(
            0, 0, 0, 0, fill="#c0f0f0", outline="black"
        )
        self._exprline = canvas.create_line(0, 0, 0, 0, dash=".")
        self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080")
        size = self._size.get() + 4
        self._stacklabel = TextWidget(
            canvas, "Stack", color="#004040", font=self._boldfont
        )
        self._rtextlabel = TextWidget(
            canvas, "Remaining Text", color="#004040", font=self._boldfont
        )
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas["scrollregion"].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2 - y1 + 10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4)
        self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5 - x1, 3 - y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2 - x2 - 5, 3 - y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {
                    "tree_color": "#4080a0",
                    "tree_width": 2,
                    "node_font": self._boldfont,
                    "node_color": "#006060",
                    "leaf_color": "#006060",
                    "leaf_font": self._font,
                }
                widget = tree_to_treesegment(self._canvas, tok, **attribs)
                widget.label()["color"] = "#000000"
            else:
                widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width() + 25)
        rlabelwidth = self._rtextlabel.width() + 10
        if stackx >= cx2 - max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4 + cx2 - rtextwidth, 0)
        self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0)

        midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:

            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx:
                    self.shift()
                else:
                    self._redraw()

            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2] + 50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, "end")
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        if self._top is None:
            return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1["text"] = "Reset App"
        self._lastoper2["text"] = ""
        self._redraw()

    def step(self, *e):
        if self.reduce():
            return True
        elif self.shift():
            return True
        else:
            if list(self._parser.parses()):
                self._lastoper1["text"] = "Finished:"
                self._lastoper2["text"] = "Success"
            else:
                self._lastoper1["text"] = "Finished:"
                self._lastoper2["text"] = "Failure"

    def shift(self, *e):
        if self._animating_lock:
            return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1["text"] = "Shift:"
            self._lastoper2["text"] = "%r" % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return True
        return False

    def reduce(self, *e):
        if self._animating_lock:
            return
        production = self._parser.reduce()
        if production:
            self._lastoper1["text"] = "Reduce:"
            self._lastoper2["text"] = "%s" % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock:
            return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle():
            return
        self._top.mainloop(*args, **kwargs)

    #########################################
    ##  Menubar callbacks
    #########################################

    def resize(self, size=None):
        if size is not None:
            self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))

        # self._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        # self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        # self._lastoper_label['font'] = ('helvetica', -size)
        # self._lastoper1['font'] = ('helvetica', -size)
        # self._lastoper2['font'] = ('helvetica', -size)
        # self._prodlist['font'] = ('helvetica', -size)
        # self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(
                self._top,
                "Help: Shift-Reduce Parser Application",
                (__doc__ or "").strip(),
                width=75,
                font="fixed",
            )
        except:
            ShowText(
                self._top,
                "Help: Shift-Reduce Parser Application",
                (__doc__ or "").strip(),
                width=75,
            )

    def about(self, *e):
        ABOUT = "NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper"
        TITLE = "About: Shift-Reduce Parser Application"
        try:
            from tkinter.messagebox import Message

            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, "end")
        for production in self._productions:
            self._prodlist.insert("end", (" %s" % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = "Edit Text"
        instr = "Enter a new sentence to parse."
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split()  # [XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(
                fill="both", side="left", padx=2, after=self._feedbackframe
            )
            self._lastoper1["text"] = "Show Grammar"
        else:
            self._prodframe.pack_forget()
            self._lastoper1["text"] = "Hide Grammar"
        self._lastoper2["text"] = ""

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1:
            return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1["text"] = "Reduce:"
            self._lastoper2["text"] = "%s" % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, "end")
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0:
            return

        self._reduce_menu.delete(0, "end")
        for production in productions:
            self._reduce_menu.add_command(label=str(production), command=self.reduce)
        self._reduce_menu.post(
            self._canvas.winfo_pointerx(), self._canvas.winfo_pointery()
        )

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0:
            left = 5
        else:
            left = self._stackwidgets[-1].bbox()[2] + 10

        # Start animating.
        dt = self._animate.get()
        dx = (left - right) * 1.0 / dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1])  # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].label().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist * 2.0 / dt
        self._animate_reduce_frame(dt / 2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy)
        else:
            del self._stackwidgets[-len(widgets) :]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree):
                raise ValueError()
            label = TextWidget(
                self._canvas, str(tok.label()), color="#006060", font=self._boldfont
            )
            widget = TreeSegmentWidget(self._canvas, label, widgets, width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2 - y1 + 10
            if not self._stackwidgets:
                x = 5
            else:
                x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

            #             # Delete the old widgets..
            #             del self._stackwidgets[-len(widgets):]
            #             for widget in widgets:
            #                 self._cframe.destroy_widget(widget)
            #
            #             # Make a new one.
            #             tok = self._parser.stack()[-1]
            #             if isinstance(tok, Tree):
            #                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
            #                            'node_font': bold, 'node_color': '#006060',
            #                            'leaf_color': '#006060', 'leaf_font':self._font}
            #                 widget = tree_to_treesegment(self._canvas, tok.type(),
            #                                              **attribs)
            #                 widget.node()['color'] = '#000000'
            #             else:
            #                 widget = TextWidget(self._canvas, tok.type(),
            #                                     color='#000000', font=self._font)
            #             widget.bind_click(self._popup_reduce)
            #             (x1, y1, x2, y2) = self._stacklabel.bbox()
            #             y = y2-y1+10
            #             if not self._stackwidgets: x = 5
            #             else: x = self._stackwidgets[-1].bbox()[2] + 10
            #             self._cframe.add_widget(widget, x, y)
            #             self._stackwidgets.append(widget)

            # self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index:
            return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.label()["color"] = "#00a000"
                else:
                    stackwidget["color"] = "#00a000"

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1:
            return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.label()["color"] = "black"
            else:
                stackwidget["color"] = "black"
示例#47
0
class ColorSchemeTab(Tab):
    def __init__(self, master):
        super().__init__(master)
        self.name = None  # currently unused, but will be for saving and loading
        # dictionary of default colors for initialization and the reset button:
        self._default = {
            'r': [255, 255, 255, 220, 75, 3, 3, 30, 125, 220, 255],
            'g': [0, 150, 255, 255, 255, 255, 145, 3, 3, 3, 0],
            'b': [0, 0, 0, 3, 3, 240, 255, 255, 255, 255, 0]
        }
        self.n_updates = 0
        # self.backgroundcolor = self.rgb_tk((0, 0, 0))
        self._resetcolors = True  # this tells the color boxes to fill themselves with the defaults
        self._colordict = deepcopy(
            self._default
        )  # this is master list of colors that you use and edit. Starts as default

        # variables for the background color:
        self._bg_red = StringVar()
        self._bg_green = StringVar()
        self._bg_blue = StringVar()
        # putting them all into a single object:
        self._bg_vars = {
            'r': self._bg_red,
            'g': self._bg_green,
            'b': self._bg_blue
        }
        # this will be the swatch that shows you the color
        self._bg_color_example = None

        # label the background control area
        backgroundlabel = Label(self, text="Background:", font=self.h1)
        backgroundlabel.grid(row=2,
                             column=3,
                             columnspan=300,
                             pady=(10, 5),
                             sticky="nw")
        # setup the controls for the background color
        self.setup_background_color_area()

        # label the pattern color control area
        patternlabel = Label(self, text="Pattern:", font=self.h1)
        patternlabel.grid(row=6,
                          column=3,
                          columnspan=300,
                          pady=(10, 5),
                          sticky="nw")

        # initializing and setting the main parameters
        self._totalcolors = Parameter(
            self,
            label="Total Colors (fade smoothness)",
            from_=1,
            to=300,
            command=self.check_ratio_tot,
            row=9
        )  # this one sets the number of transitionary colors beginning to end of the selected colors
        self._totalcolors.set(100)
        self._colorstops = Parameter(
            self,
            label="Number of Stops",
            from_=2,
            to=11,
            command=self.update_colorstops,
            row=10
        )  # this one sets the number of colors you define specifically
        self._colorstops.set(11)

        settodefaultcolors = Button(
            self,
            text='Load Default Colors',
            command=self.reset_colors_to_default
        )  # resets colordict back to the default rainbow set
        settodefaultcolors.grid(row=18, column=3, columnspan=300)
        reversecolors = Button(
            self, text='Reverse Order', command=self.reverse_color_order
        )  # this button flips the order of the entire color dictionary
        reversecolors.grid(row=18, column=500, columnspan=300)

        # This comes from the Tab class, and it is a Separate frame that can
        # keep spacing independent from controls on the rest of the tab. this
        # is where the color boxes will go.
        self._spacedarea.grid(row=20, column=0, columnspan=800)

        self._colorshiftvar = IntVar()
        self._colorshift = Parameter(
            self,
            label="Shift Position",
            from_=-6,
            to=6,
            row=25,
            command=self.shift_color,
            bigincrement=1,
            variable=self._colorshiftvar
        )  # this control shifts the position of the colors in the dictionary
        self._previousshift = 0  # this is for determining the interval of shift (-1 or 1)

        self._hueshiftvar = IntVar(
        )  # using a variable with this one so that I can reset hue shift to zero on loading without triggering the callback.
        self._hueshift = Parameter(self,
                                   label="Shift Hue",
                                   from_=-127,
                                   to=127,
                                   row=27,
                                   command=self.shift_hue,
                                   bigincrement=2,
                                   resolution=2,
                                   variable=self._hueshiftvar)
        self._previoushue = 0

        # label the effects section of the tab
        effectslabel = Label(self, text="Effects:", font=self.h2)
        effectslabel.grid(row=28,
                          column=3,
                          columnspan=200,
                          pady=(10, 5),
                          padx=(10, 0))

        # creating the buttons for each color transformation
        shiftlightnessbutton = Button(
            self,
            text="Shift Lightness",
            command=lambda: ShiftLightnessDialog(self.shift_lightness))
        ramplightnessbutton = Button(
            self,
            text="Ramp Lightness",
            command=lambda: RampLightnessDialog(self.ramp_lightness))

        shiftlightnessbutton.grid(row=30,
                                  column=3,
                                  columnspan=200,
                                  pady=10,
                                  padx=(5, 0))
        ramplightnessbutton.grid(row=30, column=210, columnspan=200)

    @property
    def colorscheme(self):
        # returns a spirogen ColorScheme object with the current parameters
        scheme = ColorScheme(self.currentcolors, self._totalcolors.get())
        return scheme

    @property
    def currentcolors(self):
        # this returns the set of color dictionary that you are actually using
        colors = {'r': [], 'g': [], 'b': []}
        for key in colors:
            colors[key] = self.colordict[key][:self._colorstops.get()]
        return colors

    @property
    def backgroundcolor(self):
        # gets the rgb value tuple
        return self.make_bg_color()

    @property
    def colordict(self):
        # getter for colordict
        return self._colordict

    @property
    def hsv_colordict(self):
        hsv_dict = {'h': [], 's': [], 'v': []}
        for i in range(len(self.colordict['r'])):
            rgb = [self.colordict[k][i] / 255 for k in self.colordict.keys()]
            hsv = [*rgb_to_hsv(rgb)]
            for j, k in enumerate(hsv_dict):
                hsv_dict[k].append(hsv[j])
        return hsv_dict

    @colordict.setter
    def colordict(self, val):
        self._colordict = val

    def colordict_from_hsv(self, hsv_dict):
        colordict = {'r': [], 'g': [], 'b': []}
        for i in range(len(hsv_dict['h'])):
            hsv = [hsv_dict[k][i] for k in hsv_dict]
            rgb = [int(round(col * 255)) for col in hsv_to_rgb(hsv)]
            for j, k in enumerate(colordict):
                colordict[k].append(rgb[j])
        return colordict

    def shift_hue(self, *args):
        shift = self._hueshift.get()  # hue is between the range of 0 and 1
        prevshift = self._previoushue
        shift = (prevshift - shift) / 255
        hsv_dict = self.hsv_colordict
        hsv_dict['h'] = [(val + shift) % 1 for val in hsv_dict['h']]
        rgb = self.colordict_from_hsv(hsv_dict)
        self.colordict = rgb
        self.update_color_boxes()
        self._previoushue = self._hueshift.get()

    def setup_background_color_area(self):
        # creates and places the controls for the backgorund color section

        # binding these variables to the method that groups the colors together,
        # so that the swatch updates in real time with changes.
        self._bg_red.trace('w', self.make_bg_color)
        self._bg_green.trace('w', self.make_bg_color)
        self._bg_blue.trace('w', self.make_bg_color)

        self._bg_color_example = ColorSwatch(
            self,
            self._bg_red,
            self._bg_green,
            self._bg_blue,
            height=20,
            curcolors=self.colordict,
            defaultcolors=self._default,
            width=25,
            highlightbackground='black',
            highlightthickness=1,
            func=self.open_editor)  # this is the swatch preview of the color

        # setting default background color to black
        self._bg_red.set(0)
        self._bg_green.set(0)
        self._bg_blue.set(0)

        rlabel = Label(self, text='R:')
        glabel = Label(self, text='G:')
        blabel = Label(self, text='B:')
        rbox = Entry(self, textvariable=self._bg_red, width=5)
        gbox = Entry(self, textvariable=self._bg_green, width=5)
        bbox = Entry(self, textvariable=self._bg_blue, width=5)

        rlabel.grid(row=3, column=80, columnspan=60)
        rbox.grid(row=4, column=80, columnspan=60)
        glabel.grid(row=3, column=150, columnspan=60)
        gbox.grid(row=4, column=150, columnspan=60)
        blabel.grid(row=3, column=220, columnspan=60)
        bbox.grid(row=4, column=220, columnspan=60)
        self._bg_color_example.grid(row=4, column=300)

    def make_bg_color(self, *args):
        # get the value of each bg_color variable
        rstr = self._bg_red.get()
        gstr = self._bg_green.get()
        bstr = self._bg_blue.get()
        # if none of the boxes are empty:
        if all(map(lambda x: x != '', [rstr, gstr, bstr])):
            try:  # try to convert them to integers:
                r = round(float(rstr))
                g = round(float(gstr))
                b = round(float(bstr))
                color = self.rgb_tk(
                    (self._bg_red.get(), self._bg_green.get(),
                     self._bg_blue.get()))  # create a tkinter compatible color
                self._bg_color_example.updatecolor(
                    color)  # set the swatch to that color
                return self.rgb_tk(
                    (r, g, b))  # return a spirogen compatible color
            except ValueError:  # if the values could not be converted:
                # let the user know
                print('Color values must be numbers between 0 and 255')

    def reset_colors_to_default(self):
        # this method is run by the reset colors button, and is self explanitory
        self.update_color_boxes()
        self._resetcolors = True
        self._colorshift.set(0)
        self._colorshift.set(0)
        self.colordict = deepcopy(self._default)
        self.update_color_boxes()

    def update_colorstops(self, *args):
        self.check_ratio_stops(*args)  #
        self.make_color_boxes()

    def shift_color(self, *args):
        colordict = {k: self.colordict[k].copy() for k in self.colordict}
        amt = self._colorshift.get()
        prev = self._previousshift
        self._previousshift = amt
        if amt < prev:
            interval = -1
        else:
            interval = 1
        if amt == 0:
            amt = 1
        for j in range(abs(amt)):
            for color in colordict:
                for i in range(len(colordict[color])):
                    ind = (i - interval) % len(colordict[color])
                    colordict[color][i] = self.colordict[color][ind]
        self.colordict = colordict
        self.update_color_boxes()

    def reverse_color_order(self, *args):
        colordict = deepcopy(self.colordict)
        for key in colordict:
            for i in range(len(colordict[key])):
                colordict[key][i] = self.colordict[key][-i - 1]
        self.colordict = colordict
        self.update_color_boxes()

    def is_default_colors(self):
        for key in self.colordict:
            if key == 'r':
                def_r = self.colordict[key]
                r = self.colordict[key]
            elif key == 'g':
                def_g = self.colordict[key]
                g = self.colordict[key]
            elif key == 'b':
                def_b = self.colordict[key]
                b = self.colordict[key]
        r_match = all(map(lambda x: r.count(x) == def_r.count(x), r))
        g_match = all(map(lambda x: g.count(x) == def_g.count(x), g))
        b_match = all(map(lambda x: b.count(x) == def_b.count(x), b))
        return all([r_match, g_match, b_match])

    def check_ratio_tot(self, tot):
        tot = int(tot)
        if tot < self._colorstops.get():
            self._colorstops.set(tot)

    def check_ratio_stops(self, stops):
        stops = int(stops)
        if stops > self._totalcolors.get():
            self._totalcolors.set(stops)

    @staticmethod
    def rgb_tk(rgb):
        rgb = tuple([round(float(i)) for i in rgb])
        output = "#%02x%02x%02x" % rgb
        return output

    def remove_old_color_boxes(self):
        prevparams = []
        if 'colorparams' in self._progparams.keys():
            for group in self._progparams['colorparams']:
                entry = []
                for key in group:
                    if key == 'vals':
                        entry += (w.get() for w in group[key].values())
                    elif key == 'boxes':
                        for widget in group[key].values():
                            widget.grid_forget()
                    else:
                        widget = group[key]
                        widget.grid_forget()
                prevparams.append(entry)

        self._progparams['colorparams'] = []
        return prevparams

    def make_color_boxes(self):
        """
        This method creates the rgb input boxes and swatches based on the numer
        of stops set by the user.
        """
        n = self._colorstops.get()
        self.remove_old_color_boxes()

        r_row, g_row, b_row = 10, 14, 18

        label_r = Label(self._spacedarea, text="R")
        label_g = Label(self._spacedarea, text="G")
        label_b = Label(self._spacedarea, text="B")

        label_r.grid(row=r_row, column=0, padx=(0, 10))
        label_g.grid(row=g_row, column=0, padx=(0, 10))
        label_b.grid(row=b_row, column=0, padx=(0, 10))

        for i in range(n):
            col_label = Label(self._spacedarea, text=str(i + 1))

            red = StringVar()
            redbox = Entry(self._spacedarea, width=3, textvariable=red)
            green = StringVar()
            greenbox = Entry(self._spacedarea, width=3, textvariable=green)
            blue = StringVar()
            bluebox = Entry(self._spacedarea, width=3, textvariable=blue)

            red.set(self.colordict['r'][i])
            green.set(self.colordict['g'][i])
            blue.set(self.colordict['b'][i])

            color = self.rgb_tk((red.get(), green.get(), blue.get()))

            examplebox = ColorSwatch(self._spacedarea,
                                     red,
                                     green,
                                     blue,
                                     color=color,
                                     curcolors=self.colordict,
                                     defaultcolors=self._default,
                                     func=self.open_editor)
            red.trace(
                'w',
                partial(self.update_color_dict,
                        index=i,
                        key='r',
                        swatch=examplebox,
                        color=color))
            green.trace(
                'w',
                partial(self.update_color_dict,
                        index=i,
                        key='g',
                        swatch=examplebox,
                        color=color))
            blue.trace(
                'w',
                partial(self.update_color_dict,
                        index=i,
                        key='b',
                        swatch=examplebox,
                        color=color))

            col = 20 * (
                i + 1
            )  # just so that I have flexibility in positioning things later if I make changes
            col_label.grid(row=8, column=col, pady=10, padx=1)
            redbox.grid(row=r_row, column=col)
            greenbox.grid(row=g_row, column=col)
            bluebox.grid(row=b_row, column=col)

            examplebox.grid(row=20, column=col, pady=10)

            self._progparams['colorparams'].append({
                'boxes': {
                    'r': redbox,
                    'g': greenbox,
                    'b': bluebox
                },
                'vals': {
                    'r': red,
                    'g': green,
                    'b': blue
                },
                'label': col_label,
                'example': examplebox
            })
            # self.resetcolors = False
            # pass
            # self.progparams['curveboxes'].append([curvebox, label2])

    def update_color_dict(self, *args, index, key, swatch, color):
        # if False:
        colparams = [l.copy() for l in self._progparams['colorparams']]
        values = [i['vals'] for i in colparams]
        examples = [i['example'] for i in colparams]
        # newcols = deepcopy(self.colordict)
        newcols = {k: self.colordict[k].copy() for k in self.colordict}
        if index < len(values):
            group = values[index]
            # rgb = []
            ind = (index - 1) % len(
                self.colordict[key]
            )  # set the index to edit, based on remainder of the index - shift amount
            strval = group[key].get()
            if strval != '':
                val = round(float(strval))
                self._colordict[key][ind] = val
                newcols[key][index] = val
        self._colordict = newcols
        self.update_swatches()

    def update_color_boxes(self):
        # self.make_color_boxes()
        for i in range(len(self._progparams['colorparams'])):
            group = self._progparams['colorparams'][i]
            rgb = []
            for key in group['vals']:
                val = self.colordict[key][i]
                rgb.append(val)
                group['vals'][key].set(val)
            group['example'].updatecolor(self.rgb_tk(rgb))

    def update_swatches(self):
        for i in range(len(self._progparams['colorparams'])):
            group = self._progparams['colorparams'][i]
            rgb = []
            for key in group['vals']:
                val = self.colordict[key][i]
                rgb.append(val)
                # group['vals'][key].set(val)
            group['example'].updatecolor(self.rgb_tk(rgb))

    def open_editor(self, targetswatch):
        ColorSwatchDialog(targetswatch,
                          curcolors=self.colordict,
                          defaultcolors=self._default)

    def shift_lightness(self, amount):
        scheme = ColorScheme(self.colordict, self._colorstops.get())
        scheme.shiftlightness(amount)
        self.colordict = scheme.colors
        self.update_color_boxes()

    def ramp_lightness(self, amount, direction, goto):
        scheme = ColorScheme(self.colordict, self._colorstops.get())
        scheme.ramplightness(amount, direction, goto)
        self.colordict = scheme.colors
        self.update_color_boxes()

    def save(self, mode, name):
        if mode == 'colors':
            self.name = name
        output = {
            'background': {
                'r': self._bg_red.get(),
                'g': self._bg_green.get(),
                'b': self._bg_blue.get()
            },
            'totalcolors': self._totalcolors.get(),
            'nstops': self._colorstops.get(),
            'colordict': self.colordict,
            'id': self.name
        }

        return self.name, output

    def load(self, name, data):
        self.make_color_boxes()
        self._hueshiftvar.set(0)
        self._previoushue = 0
        self._previousshift = 0
        self._colorshiftvar.set(0)
        for k in data["background"]:
            self._bg_vars[k].set(data["background"][k])
        self._totalcolors.set(int(data["totalcolors"]))
        self._colorstops.set(int(data["nstops"]))
        self.colordict = data["colordict"]
        self.update_color_boxes()
        self.name = name
示例#48
0
class Options(Frame):
    """ Options form """
    def __init__(self, master, ordinances=False, **kwargs):
        super().__init__(master, **kwargs)
        self.ancestors = IntVar()
        self.ancestors.set(4)
        self.descendants = IntVar()
        self.spouses = IntVar()
        self.ordinances = IntVar()
        self.contributors = IntVar()
        self.start_indis = StartIndis(self)
        self.fid = StringVar()
        btn = Frame(self)
        entry_fid = EntryWithMenu(btn, textvariable=self.fid, width=16)
        entry_fid.bind("<Key>", self.enter)
        label_ancestors = Label(self,
                                text=_("Number of generations to ascend"))
        entry_ancestors = EntryWithMenu(self,
                                        textvariable=self.ancestors,
                                        width=5)
        label_descendants = Label(self,
                                  text=_("Number of generations to descend"))
        entry_descendants = EntryWithMenu(self,
                                          textvariable=self.descendants,
                                          width=5)
        btn_add_indi = Button(btn,
                              text=_("Add a FamilySearch ID"),
                              command=self.add_indi)
        btn_spouses = Checkbutton(
            self,
            text="\t" + _("Add spouses and couples information"),
            variable=self.spouses,
        )
        btn_ordinances = Checkbutton(self,
                                     text="\t" + _("Add Temple information"),
                                     variable=self.ordinances)
        btn_contributors = Checkbutton(
            self,
            text="\t" + _("Add list of contributors in notes"),
            variable=self.contributors,
        )
        self.start_indis.grid(row=0, column=0, columnspan=3)
        entry_fid.grid(row=0, column=0, sticky="w")
        btn_add_indi.grid(row=0, column=1, sticky="w")
        btn.grid(row=1, column=0, columnspan=2, sticky="w")
        entry_ancestors.grid(row=2, column=0, sticky="w")
        label_ancestors.grid(row=2, column=1, sticky="w")
        entry_descendants.grid(row=3, column=0, sticky="w")
        label_descendants.grid(row=3, column=1, sticky="w")
        btn_spouses.grid(row=4, column=0, columnspan=2, sticky="w")
        if ordinances:
            btn_ordinances.grid(row=5, column=0, columnspan=3, sticky="w")
        btn_contributors.grid(row=6, column=0, columnspan=3, sticky="w")
        entry_ancestors.focus_set()

    def add_indi(self):
        """ add a fid """
        if self.start_indis.add_indi(self.fid.get()):
            self.fid.set("")

    def enter(self, evt):
        """ enter event """
        if evt.keysym in {"Return", "KP_Enter"}:
            self.add_indi()
示例#49
0
                           command=write_today_game)
load_button_3.place(relx=0, rely=0.65, relwidth=0.51, relheight=0.35)

load_button_4 = ttk.Button(lower_frame, text='Очистить', command=clear)
load_button_4.place(relx=0.5, rely=0.65, relwidth=0.5, relheight=0.35)

global requests
session = requests.Session()  # иллюзия непрерывности во времени
requests = session.get(URL, headers=headers)  # эмулируем открытие

soup = bs(requests.content, 'lxml')
# Контейнер в котором хранятся наши элементы
div = soup.find('div', id='score-data')

leagues = div.find_all('h4')  # Находим все лиги
cbtn_states = []
for league in leagues:
    league = league.text
    league_data.append(league)
    cbtn_state = IntVar()
    # все привязанные переменные сохраняем в список
    cbtn_states.append(cbtn_state)
    cbtn = ttk.Checkbutton(scroll_frame, text=league, variable=cbtn_state)
    # Делаем, чтобы при нажатии в обработчик передавался сам виджет:
    cbtn.config(command=lambda widget=cbtn: chk_btn_click(widget))
    cbtn.pack(expand=1, fill=BOTH)

scroll_frame.update()

root.mainloop()
示例#50
0
    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

        filemenu = Menu(menubar, tearoff=0, borderwidth=0)
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-q')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20',
                                   variable=self._result_size,
                                   underline=0,
                                   value=20,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50',
                                   variable=self._result_size,
                                   underline=0,
                                   value=50,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100',
                                   variable=self._result_size,
                                   underline=0,
                                   value=100,
                                   command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count',
                             underline=0,
                             menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(label='60 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=60,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='80 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=80,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='100 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=100,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label='Before', underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(label='70 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=70,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='90 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=90,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='110 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=110,
                                   command=self.set_cntx_af_len)
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label='After', underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label='Context', underline=0, menu=cntxmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        self.top.config(menu=menubar)
示例#51
0
class CheckBox(TextWidget):
    def __init__(self,
                 master,
                 text,
                 command=None,
                 grid=None,
                 align=None,
                 args=None,
                 visible=True,
                 enabled=None):

        description = "[CheckBox] object with text \"" + text + "\""

        self._text = str(text)
        self._value = IntVar()
        tk = Checkbutton(master.tk, text=text, variable=self._value)

        super(CheckBox, self).__init__(master, tk, description, grid, align,
                                       visible, enabled)

        # Set the command callback
        self.tk.config(command=self._command_callback)
        self.update_command(command, args)

    # PROPERTIES
    # ----------------------------------
    # Whether the box is checked or not
    @property
    def value(self):
        return (self._value.get())

    # Set whether the box is checked or not
    @value.setter
    def value(self, value):
        try:
            value = int(value)
            if value in [0, 1]:
                self._value.set(value)

        except ValueError:
            utils.error_format("You can only set the value of " +
                               self.description +
                               " to either 0 (not checked) or 1 (checked)")

    # The text associated with this box
    @property
    def text(self):
        return (self._text)

    # Set whether the box is checked or not
    @text.setter
    def text(self, text):
        self._text = str(text)
        self.tk.config(text=self._text)
        self.description = "[CheckBox] object with text \"" + str(
            self._text) + "\""

    # METHODS
    # -------------------------------------------

    def toggle(self):
        self.tk.toggle()

    def update_command(self, command, args=None):
        if command is None:
            self._command = lambda: None
        else:
            if args is None:
                self._command = command
            else:
                self._command = utils.with_args(command, *args)

    def _command_callback(self):
        self._command()

    # DEPRECATED METHODS
    # --------------------------------------------
    # Return text associated with this checkbox
    def get_text(self):
        return self._text
        utils.deprecated(
            "CheckBox get_text() is deprecated. Please use the text property instead."
        )

    # Return the value (1 or 0) of the box
    def get_value(self):
        return self._value.get()
        utils.deprecated(
            "CheckBox get_value() is deprecated. Please use the value property instead."
        )

    # Change text
    def change_text(self, newtext):
        self._text = str(newtext)
        self.tk.config(text=self._text)
        self.description = "[CheckBox] object with text " + str(self._text)
        utils.deprecated(
            "CheckBox change_text() is deprecated. Please use the text property instead."
        )
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        self.seq = 1

        self.settingValues = settings.Settings()

        self.showoutput = int(
            self.settingValues.getDebugSettingValue('showoutput'))

        self.timeinmins = int(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoatstart = int(
            self.settingValues.getAppSettingValue('autoonatstart'))
        self.autooption = int(
            self.settingValues.getAppSettingValue('autoselectedoption'))

        #self.autocombo.set(self.autooption)

        self.MAX_TIMER = self.timeinmins * 60

        self.serverPortVar = StringVar()
        self.serverVar = IntVar()

        self.serverPortVar.set(
            int(self.settingValues.getNetworkSettingValue('serverport')))
        self.serverVar.set(
            self.settingValues.getNetworkSettingValue('serverip'))

        self.api = js8callAPIsupport.js8CallUDPAPICalls(
            self.settingValues.getNetworkSettingValue('serverip'),
            int(self.settingValues.getNetworkSettingValue('serverport')))

        self.gpsOption = self.settingValues.getGPSHardwareSettingValue(
            'option')

        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()

        self.gpsComPortSpeedVar = self.settingValues.getGPSHardwareSettingValue(
            'gpsportspeed')
        self.gpsComPortVar = self.settingValues.getGPSHardwareSettingValue(
            'gpscomport')

        self.gpsOptionBeforeRefresh = self.gpsOption

        self.useManualPosition = False

        self.gpsl = None

        if self.gpsOption != "None":
            print("GPS Option " + self.gpsOption)
            if self.gpsOption == 'GPSD':
                self.gpsl = gpsdGPSListener.GpsListener(
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)
            elif self.gpsOption == 'Network':
                self.gpsl = networkGPSListener.netWorkGPS(
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpscomport'),
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpsportspeed'),
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)
            elif self.gpsOption == 'Windows Location Services':
                print('Using Windows Location Services')
                self.gpsl = windowsLocation.locationservices(
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)

            elif self.gpsOption == 'Manual':
                self.useManualPosition = True
                self.manualposition = self.settingValues.getGPSHardwareSettingValue(
                    'gpscomport')
            else:
                self.gpsl = serialGPSlistener.GPSListener(
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpscomport'),
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpsportspeed'),
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)

            if self.gpsl != None:
                self.gpsl.start()

        self.geometry(str(WIDTH) + "x" + str(HEIGHT))
        self.title("JS8Call Utilities by M0IAX")

        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()
        self.maidPreceision = StringVar()
        self.autoTimeVar = StringVar()
        self.autoGridToJS8Call = IntVar()

        self.var1 = StringVar()
        self.var2 = StringVar()
        self.latlonvar = StringVar()

        #set default values
        self.gpsComPortVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpscomport'))
        self.gpsComPortSpeedVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpsportspeed'))
        self.maidPreceision.set(
            self.settingValues.getAppSettingValue('precision'))
        self.autoTimeVar.set(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoGridToJS8Call.set(
            self.settingValues.getAppSettingValue('autoonatstart'))

        if self.useManualPosition:
            self.var1.set(self.manualposition)

        #Main window frame
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (GPSPage, MessagePage, SettingsPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky='nsew')

        self.show_frame(GPSPage)

        bottomFrame = Frame(self)
        bottomFrame.pack()

        self.autocombo = Combobox(bottomFrame, state='readonly', width=45)
        self.autocombo.state = 'disabled'
        self.autocombo.bind('<<ComboboxSelected>>', self.autocomboChange)
        self.autocombo['values'] = (
            "Auto update JS8Call Grid", "Auto TX Grid to APRSIS",
            "Auto TX Grid to APRSIS and Update JS8Call Grid")

        self.autocombo.current(self.autooption)  #set the selected item
        #self.autocombo.place(relx=0.05,rely=0.63, relwidth=0.9,relheight=0.1)
        self.autocombo.grid(row=0, column=0, sticky=W + E + N + S)

        self.autoGridToJS8Call = IntVar(value=self.autoatstart)
        self.autoGridCheck = Checkbutton(bottomFrame,
                                         text="Enable Auto update every " +
                                         str(self.timeinmins) + " mins.",
                                         variable=self.autoGridToJS8Call,
                                         command=self.cb)
        #self.autoGridCheck.place(relx=0.05,rely=0.71, relwidth=0.9,relheight=0.1)
        self.autoGridCheck.grid(row=1,
                                column=0,
                                sticky=W + E + N + S,
                                padx=5,
                                pady=5)

        if self.gpsOption == 'None':
            self.autoGridCheck.configure(state='disabled')
            self.autoGridToJS8Call.set(0)
        else:
            self.autoGridCheck.configure(state='normal')

        self.timer = 60  #Set timer to 60 for the first tx GPS should have a lock in that time
        self.timerStr = StringVar()

        self.timerStr.set("Timer Not Active")
        self.timerlabel = Label(bottomFrame, textvariable=self.timerStr)
        #self.timerlabel.place(relx=0.05,rely=0.81, relwidth=0.9,relheight=0.1)
        self.timerlabel.grid(row=2, column=0, sticky=W + E + N + S)

        buttonFrame = Frame(self)
        buttonFrame.pack()

        self.nav_buttons(buttonFrame, self)

        self.update_timer()
示例#53
0
class ConcordanceSearchView(object):
    _BACKGROUND_COLOUR = '#FFF'  #white

    #Colour of highlighted results
    _HIGHLIGHT_WORD_COLOUR = '#F00'  #red
    _HIGHLIGHT_WORD_TAG = 'HL_WRD_TAG'

    _HIGHLIGHT_LABEL_COLOUR = '#C0C0C0'  # dark grey
    _HIGHLIGHT_LABEL_TAG = 'HL_LBL_TAG'

    #Percentage of text left of the scrollbar position
    _FRACTION_LEFT_TEXT = 0.30

    def __init__(self):
        self.queue = q.Queue()
        self.model = ConcordanceSearchModel(self.queue)
        self.top = Tk()
        self._init_top(self.top)
        self._init_menubar()
        self._init_widgets(self.top)
        self.load_corpus(self.model.DEFAULT_CORPUS)
        self.after = self.top.after(POLL_INTERVAL, self._poll)

    def _init_top(self, top):
        top.geometry('950x680+50+50')
        top.title('NLTK Concordance Search')
        top.bind('<Control-q>', self.destroy)
        top.protocol('WM_DELETE_WINDOW', self.destroy)
        top.minsize(950, 680)

    def _init_widgets(self, parent):
        self.main_frame = Frame(
            parent,
            dict(background=self._BACKGROUND_COLOUR, padx=1, pady=1, border=1))
        self._init_corpus_select(self.main_frame)
        self._init_query_box(self.main_frame)
        self._init_results_box(self.main_frame)
        self._init_paging(self.main_frame)
        self._init_status(self.main_frame)
        self.main_frame.pack(fill='both', expand=True)

    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

        filemenu = Menu(menubar, tearoff=0, borderwidth=0)
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-q')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(label='20',
                                   variable=self._result_size,
                                   underline=0,
                                   value=20,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='50',
                                   variable=self._result_size,
                                   underline=0,
                                   value=50,
                                   command=self.set_result_size)
        rescntmenu.add_radiobutton(label='100',
                                   variable=self._result_size,
                                   underline=0,
                                   value=100,
                                   command=self.set_result_size)
        rescntmenu.invoke(1)
        editmenu.add_cascade(label='Result Count',
                             underline=0,
                             menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(label='60 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=60,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='80 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=80,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.add_radiobutton(label='100 characters',
                                   variable=self._cntx_bf_len,
                                   underline=0,
                                   value=100,
                                   command=self.set_cntx_bf_len)
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label='Before', underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(label='70 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=70,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='90 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=90,
                                   command=self.set_cntx_af_len)
        cntxafmenu.add_radiobutton(label='110 characters',
                                   variable=self._cntx_af_len,
                                   underline=0,
                                   value=110,
                                   command=self.set_cntx_af_len)
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label='After', underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label='Context', underline=0, menu=cntxmenu)

        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        self.top.config(menu=menubar)

    def set_result_size(self, **kwargs):
        self.model.result_count = self._result_size.get()

    def set_cntx_af_len(self, **kwargs):
        self._char_after = self._cntx_af_len.get()

    def set_cntx_bf_len(self, **kwargs):
        self._char_before = self._cntx_bf_len.get()

    def _init_corpus_select(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.var = StringVar(innerframe)
        self.var.set(self.model.DEFAULT_CORPUS)
        Label(innerframe,
              justify=LEFT,
              text=' Corpus: ',
              background=self._BACKGROUND_COLOUR,
              padx=2,
              pady=1,
              border=0).pack(side='left')

        other_corpora = list(self.model.CORPORA.keys()).remove(
            self.model.DEFAULT_CORPUS)
        om = OptionMenu(innerframe,
                        self.var,
                        self.model.DEFAULT_CORPUS,
                        command=self.corpus_selected,
                        *self.model.non_default_corpora())
        om['borderwidth'] = 0
        om['highlightthickness'] = 1
        om.pack(side='left')
        innerframe.pack(side='top', fill='x', anchor='n')

    def _init_status(self, parent):
        self.status = Label(parent,
                            justify=LEFT,
                            relief=SUNKEN,
                            background=self._BACKGROUND_COLOUR,
                            border=0,
                            padx=1,
                            pady=0)
        self.status.pack(side='top', anchor='sw')

    def _init_query_box(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        another = Frame(innerframe, background=self._BACKGROUND_COLOUR)
        self.query_box = Entry(another, width=60)
        self.query_box.pack(side='left', fill='x', pady=25, anchor='center')
        self.search_button = Button(another,
                                    text='Search',
                                    command=self.search,
                                    borderwidth=1,
                                    highlightthickness=1)
        self.search_button.pack(side='left',
                                fill='x',
                                pady=25,
                                anchor='center')
        self.query_box.bind('<KeyPress-Return>',
                            self.search_enter_keypress_handler)
        another.pack()
        innerframe.pack(side='top', fill='x', anchor='n')

    def search_enter_keypress_handler(self, *event):
        self.search()

    def _init_results_box(self, parent):
        innerframe = Frame(parent)
        i1 = Frame(innerframe)
        i2 = Frame(innerframe)
        vscrollbar = Scrollbar(i1, borderwidth=1)
        hscrollbar = Scrollbar(i2, borderwidth=1, orient='horiz')
        self.results_box = Text(i1,
                                font=tkinter.font.Font(family='courier',
                                                       size='16'),
                                state='disabled',
                                borderwidth=1,
                                yscrollcommand=vscrollbar.set,
                                xscrollcommand=hscrollbar.set,
                                wrap='none',
                                width='40',
                                height='20',
                                exportselection=1)
        self.results_box.pack(side='left', fill='both', expand=True)
        self.results_box.tag_config(self._HIGHLIGHT_WORD_TAG,
                                    foreground=self._HIGHLIGHT_WORD_COLOUR)
        self.results_box.tag_config(self._HIGHLIGHT_LABEL_TAG,
                                    foreground=self._HIGHLIGHT_LABEL_COLOUR)
        vscrollbar.pack(side='left', fill='y', anchor='e')
        vscrollbar.config(command=self.results_box.yview)
        hscrollbar.pack(side='left', fill='x', expand=True, anchor='w')
        hscrollbar.config(command=self.results_box.xview)
        #there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
        Label(i2, text='   ',
              background=self._BACKGROUND_COLOUR).pack(side='left', anchor='e')
        i1.pack(side='top', fill='both', expand=True, anchor='n')
        i2.pack(side='bottom', fill='x', anchor='s')
        innerframe.pack(side='top', fill='both', expand=True)

    def _init_paging(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.prev = prev = Button(innerframe,
                                  text='Previous',
                                  command=self.previous,
                                  width='10',
                                  borderwidth=1,
                                  highlightthickness=1,
                                  state='disabled')
        prev.pack(side='left', anchor='center')
        self.next = next = Button(innerframe,
                                  text='Next',
                                  command=self.__next__,
                                  width='10',
                                  borderwidth=1,
                                  highlightthickness=1,
                                  state='disabled')
        next.pack(side='right', anchor='center')
        innerframe.pack(side='top', fill='y')
        self.current_page = 0

    def previous(self):
        self.clear_results_box()
        self.freeze_editable()
        self.model.prev(self.current_page - 1)

    def __next__(self):
        self.clear_results_box()
        self.freeze_editable()
        self.model.next(self.current_page + 1)

    def about(self, *e):
        ABOUT = ("NLTK Concordance Search Demo\n")
        TITLE = 'About: NLTK Concordance Search Demo'
        try:
            from tkinter.messagebox import Message
            Message(message=ABOUT, title=TITLE, parent=self.main_frame).show()
        except:
            ShowText(self.top, TITLE, ABOUT)

    def _bind_event_handlers(self):
        self.top.bind(CORPUS_LOADED_EVENT, self.handle_corpus_loaded)
        self.top.bind(SEARCH_TERMINATED_EVENT, self.handle_search_terminated)
        self.top.bind(SEARCH_ERROR_EVENT, self.handle_search_error)
        self.top.bind(ERROR_LOADING_CORPUS_EVENT,
                      self.handle_error_loading_corpus)

    def _poll(self):
        try:
            event = self.queue.get(block=False)
        except q.Empty:
            pass
        else:
            if event == CORPUS_LOADED_EVENT:
                self.handle_corpus_loaded(event)
            elif event == SEARCH_TERMINATED_EVENT:
                self.handle_search_terminated(event)
            elif event == SEARCH_ERROR_EVENT:
                self.handle_search_error(event)
            elif event == ERROR_LOADING_CORPUS_EVENT:
                self.handle_error_loading_corpus(event)
        self.after = self.top.after(POLL_INTERVAL, self._poll)

    def handle_error_loading_corpus(self, event):
        self.status['text'] = 'Error in loading ' + self.var.get()
        self.unfreeze_editable()
        self.clear_all()
        self.freeze_editable()

    def handle_corpus_loaded(self, event):
        self.status['text'] = self.var.get() + ' is loaded'
        self.unfreeze_editable()
        self.clear_all()
        self.query_box.focus_set()

    def handle_search_terminated(self, event):
        #todo: refactor the model such that it is less state sensitive
        results = self.model.get_results()
        self.write_results(results)
        self.status['text'] = ''
        if len(results) == 0:
            self.status['text'] = 'No results found for ' + self.model.query
        else:
            self.current_page = self.model.last_requested_page
        self.unfreeze_editable()
        self.results_box.xview_moveto(self._FRACTION_LEFT_TEXT)

    def handle_search_error(self, event):
        self.status['text'] = 'Error in query ' + self.model.query
        self.unfreeze_editable()

    def corpus_selected(self, *args):
        new_selection = self.var.get()
        self.load_corpus(new_selection)

    def load_corpus(self, selection):
        if self.model.selected_corpus != selection:
            self.status['text'] = 'Loading ' + selection + '...'
            self.freeze_editable()
            self.model.load_corpus(selection)

    def search(self):
        self.current_page = 0
        self.clear_results_box()
        self.model.reset_results()
        query = self.query_box.get()
        if (len(query.strip()) == 0): return
        self.status['text'] = 'Searching for ' + query
        self.freeze_editable()
        self.model.search(
            query,
            self.current_page + 1,
        )

    def write_results(self, results):
        self.results_box['state'] = 'normal'
        row = 1
        for each in results:
            sent, pos1, pos2 = each[0].strip(), each[1], each[2]
            if len(sent) != 0:
                if (pos1 < self._char_before):
                    sent, pos1, pos2 = self.pad(sent, pos1, pos2)
                sentence = sent[pos1 - self._char_before:pos1 +
                                self._char_after]
                if not row == len(results):
                    sentence += '\n'
                self.results_box.insert(str(row) + '.0', sentence)
                word_markers, label_markers = self.words_and_labels(
                    sent, pos1, pos2)
                for marker in word_markers:
                    self.results_box.tag_add(self._HIGHLIGHT_WORD_TAG,
                                             str(row) + '.' + str(marker[0]),
                                             str(row) + '.' + str(marker[1]))
                for marker in label_markers:
                    self.results_box.tag_add(self._HIGHLIGHT_LABEL_TAG,
                                             str(row) + '.' + str(marker[0]),
                                             str(row) + '.' + str(marker[1]))
                row += 1
        self.results_box['state'] = 'disabled'

    def words_and_labels(self, sentence, pos1, pos2):
        search_exp = sentence[pos1:pos2]
        words, labels = [], []
        labeled_words = search_exp.split(' ')
        index = 0
        for each in labeled_words:
            if each == '':
                index += 1
            else:
                word, label = each.split('/')
                words.append((self._char_before + index,
                              self._char_before + index + len(word)))
                index += len(word) + 1
                labels.append((self._char_before + index,
                               self._char_before + index + len(label)))
                index += len(label)
            index += 1
        return words, labels

    def pad(self, sent, hstart, hend):
        if hstart >= self._char_before:
            return sent, hstart, hend
        d = self._char_before - hstart
        sent = ''.join([' '] * d) + sent
        return sent, hstart + d, hend + d

    def destroy(self, *e):
        if self.top is None: return
        self.top.after_cancel(self.after)
        self.top.destroy()
        self.top = None

    def clear_all(self):
        self.query_box.delete(0, END)
        self.model.reset_query()
        self.clear_results_box()

    def clear_results_box(self):
        self.results_box['state'] = 'normal'
        self.results_box.delete("1.0", END)
        self.results_box['state'] = 'disabled'

    def freeze_editable(self):
        self.query_box['state'] = 'disabled'
        self.search_button['state'] = 'disabled'
        self.prev['state'] = 'disabled'
        self.next['state'] = 'disabled'

    def unfreeze_editable(self):
        self.query_box['state'] = 'normal'
        self.search_button['state'] = 'normal'
        self.set_paging_button_states()

    def set_paging_button_states(self):
        if self.current_page == 0 or self.current_page == 1:
            self.prev['state'] = 'disabled'
        else:
            self.prev['state'] = 'normal'
        if self.model.has_more_pages(self.current_page):
            self.next['state'] = 'normal'
        else:
            self.next['state'] = 'disabled'

    def fire_event(self, event):
        #Firing an event so that rendering of widgets happen in the mainloop thread
        self.top.event_generate(event, when='tail')

    def mainloop(self, *args, **kwargs):
        if in_idle(): return
        self.top.mainloop(*args, **kwargs)
示例#54
0
class Gui(Tk):
    biome_listbox = None
    biome_listbox_lbl = None
    biome_filter_var = None
    biome_filter_box = None

    biome_select_btn = None

    study_listbox = None
    study_listbox_lbl = None
    study_select_btn = None
    study_filter_var = None
    study_filter_box = None

    study_id_disp = None
    study_id_var = None

    study_title_disp = None
    study_title_var = None

    study_desc_disp = None
    study_desc_var = None

    study_scientific_names = None
    study_sci_names_var = None

    biome_selection_btn = None
    biome_selection = None
    biome_selection_lbl = None
    biome_tag_btn = None

    tagging_confirmation_lbl = None
    tagging_confirmation_var = None

    suggested_biomes = []

    ena_view_btn = None

    def __init__(self, biome_classifier=None):
        # Create the menu
        super().__init__()
        args = parse_args()
        self.btc = BiomeTaggingTool(args.db)
        self.biome_classifier = biome_classifier

        self.list_frame = Frame()
        self.list_frame.grid(row=1, column=0, padx=10, pady=3)
        self.details_frame = Frame()
        self.details_frame.grid(row=3, column=0, padx=10, pady=3)
        header = Label(self, text='Tagging biomes on db: ' + args.db)
        header.grid(row=0, column=0, padx=10, pady=3)

        self.title = 'Biome tagging!'

        self.biomes_list = get_biomes()

        self.init_biome_list()
        self.init_study_list()

        self.init_study_display()
        self.init_biome_conf_display()
        self.init_confirmation_line()

    def init_biome_list(self):
        self.biome_listbox_lbl = Label(self.list_frame,
                                       text='List of biomes (click to select)')
        self.biome_listbox_lbl.grid(row=0, column=1, padx=10, pady=3)
        self.biome_listbox = Listbox(self.list_frame, width=75)
        self.biome_listbox.grid(row=1, column=1, padx=10, pady=3)

        self.biome_listbox.bind('<Double-Button>', self.select_biome)
        for b in self.biomes_list:
            self.biome_listbox.insert(END, b)
        self.biome_filter_var = StringVar()
        self.biome_filter_var.trace(
            "w", lambda name, index, mode: self.filter_biome_list())

        biome_filter_row = Frame(self.list_frame)
        biome_filter_row.grid(row=2, column=1, padx=10, pady=3)
        biome_filter_lbl = Label(biome_filter_row, text='Search biomes: ')
        biome_filter_lbl.grid(row=0, column=0, padx=10, pady=3)

        self.biome_match_case = IntVar()
        self.biome_filter_caps_checkbox = Checkbutton(
            biome_filter_row,
            text='Match case',
            variable=self.biome_match_case,
            command=self.filter_biome_list)
        self.biome_filter_caps_checkbox.grid(row=1, column=0, padx=10, pady=3)

        self.biome_filter_box = Entry(biome_filter_row,
                                      textvariable=self.biome_filter_var,
                                      width=50)
        self.biome_select_btn = Button(biome_filter_row,
                                       text='Select biome',
                                       command=self.select_biome)
        self.biome_filter_box.grid(row=0, column=1, padx=10, pady=3)
        self.biome_select_btn.grid(row=0, column=2, padx=10, pady=3)

        self.filter_biome_list()

    def filter_study_list(self):
        search_term = self.study_filter_var.get()
        self.study_listbox.delete(0, END)
        list_studies = []

        # Append non-suggested biomes which pass filter
        for s in self.btc.studies:
            accessions = (s.primary_accession + ' ' +
                          s.secondary_accession).lower()
            if search_term.lower() in accessions:
                list_studies.append(s.secondary_accession)

        # Insert into listbox and color items if needed
        for i, s in enumerate(list_studies):
            self.study_listbox.insert(END, s)

    def filter_biome_list(self):
        search_term = self.biome_filter_var.get()
        self.biome_listbox.delete(0, END)
        list_biomes = []

        index_colors = {}

        # Insert suggested biomes at top of list IF they match the filter text, and store indeces to colour them later
        for b in self.suggested_biomes:
            s = '{} ({} match)'.format(b[0], "{0:.2f}".format(b[1]))
            is_match = search_term.lower() in b[0].lower(
            ) if not self.biome_match_case.get() else search_term in b[0]
            if is_match:
                i = len(list_biomes)
                list_biomes.append(s)
                b_color = fmt_font_intensity(b[1])
                index_colors[i] = _from_rgb((255 - b_color, 0, b_color))

        # Append non-suggested biomes which pass filter
        for b in self.biomes_list:
            is_match = search_term.lower() in b.lower(
            ) if not self.biome_match_case.get() else search_term in b
            if is_match and b not in self.suggested_biomes:
                list_biomes.append(b)

        # Insert into listbox and color items if needed
        for i, b in enumerate(list_biomes):
            self.biome_listbox.insert(END, b)
            if i in index_colors:
                self.biome_listbox.itemconfig(i, {'fg': index_colors[i]})

    def init_study_list(self):
        self.study_listbox = Listbox(self.list_frame, width=75)
        self.update_study_list()
        self.study_listbox_lbl = Label(
            self.list_frame, text='List of studies that need tagging')
        self.study_listbox_lbl.grid(row=0, column=0, padx=10, pady=3)
        self.study_listbox.grid(row=1, column=0, padx=10, pady=3)

        study_filter_row = Frame(self.list_frame)
        study_filter_row.grid(row=2, column=0, padx=10, pady=3)
        study_filter_lbl = Label(study_filter_row,
                                 text='Search Study accession: ')
        study_filter_lbl.grid(row=0, column=0, padx=10, pady=3)

        self.study_filter_var = StringVar()
        self.study_filter_var.trace(
            "w", lambda name, index, mode: self.filter_study_list())

        self.study_filter_box = Entry(study_filter_row,
                                      textvariable=self.study_filter_var,
                                      width=50)
        self.study_filter_box.grid(row=0, column=1, padx=10, pady=3)

        self.study_select_btn = Button(study_filter_row,
                                       text='Select study',
                                       command=self.select_study)
        self.study_listbox.bind('<Double-Button>', self.select_study)
        self.study_select_btn.grid(row=0, column=3, padx=10, pady=3)

        self.ena_view_btn = Button(self.list_frame,
                                   text='View study in ENA',
                                   command=self.view_in_ena)
        self.ena_view_btn.grid(row=3, column=0, padx=10, pady=3)

    def view_in_ena(self):
        webbrowser.open_new("https://www.ebi.ac.uk/ena/data/view/" +
                            self.study_id_var.get().replace('Study id: ', ''))

    def init_study_display(self):
        self.study_id_var = StringVar(self)
        self.study_title_var = StringVar(self)
        self.study_desc_var = StringVar(self)
        self.study_sci_names_var = StringVar(self)

        self.study_id_disp = Label(self.details_frame,
                                   textvariable=self.study_id_var,
                                   wraplength=750)
        self.study_id_disp.grid(row=0, column=0, padx=10, pady=3)
        self.study_title_disp = Label(self.details_frame,
                                      textvariable=self.study_title_var,
                                      wraplength=750)
        self.study_title_disp.grid(row=1, column=0, padx=10, pady=3)

        self.study_desc_frame = Frame(self.details_frame)
        self.study_desc_frame.grid(row=2, column=0)

        self.study_desc_disp = tkscrolled.ScrolledText(self.study_desc_frame,
                                                       height=20,
                                                       width=140,
                                                       wrap='word')
        self.study_desc_disp.insert(0.0, '\n' + self.study_desc_var.get())
        self.study_desc_disp['font'] = ('consolas', '14')
        self.study_desc_disp.pack(expand=True, fill='both')

        self.study_scientific_names = Label(
            self.details_frame,
            textvariable=self.study_sci_names_var,
            wraplength=750)
        self.study_scientific_names.grid(row=3, column=0, padx=10, pady=3)

    def fetch_study(self, study_id):
        if study_id not in study_cache:
            study = self.btc.studies.filter(secondary_accession=study_id)[0]
            d = self.btc.fetch_info(study)
            study_cache[study_id] = d
        else:
            d = study_cache[study_id]
        print('Fetched ' + study_id)
        return d

    def select_study(self, *args, **kwargs):
        try:
            print('selecting')
            study_id = self.study_listbox.get(
                self.study_listbox.curselection())
            d = self.fetch_study(study_id)
            self.study_id_var.set('Study id: {}'.format(study_id))
            self.study_title_var.set('Title: {}'.format(d['title']))
            text = 'Abstract: {}'.format(d['abstract'])
            self.study_desc_disp.delete(1.0, END)
            self.study_desc_disp.insert(1.0, '\n' + text)
            self.study_desc_disp.see(0.0)

            # self.study_sci_names_var.set('Environment variable names: {}'.format(", ".join(d['scientific_names'])))
            self.reset_confirmation_line()
            self.suggested_biomes = self.biome_classifier.pred_input(
                (d['title'] or '') + ' ' + (d['abstract'] or ''))
            self.filter_biome_list()
        except TclError as e:
            logging.error(e)
            pass

    def reset_study_display(self):
        self.study_id_var.set('Study id:')
        self.study_title_var.set('Title:')
        self.study_desc_var.set('Description:')
        self.study_sci_names_var.set('Environment variable names:')

    def init_biome_conf_display(self):
        self.biome_selection = StringVar(value='Selected biome: ')
        self.biome_selection_lbl = Label(self.details_frame,
                                         textvariable=self.biome_selection)
        self.biome_selection_lbl.grid(row=0, column=1, padx=10, pady=3)
        self.biome_tag_btn = Button(self.details_frame,
                                    text='Tag biome',
                                    command=self.tag_biome_handler)
        self.biome_tag_btn.grid(row=1, column=1, padx=10, pady=3)

    def select_biome(self, *args, **kwargs):
        try:
            biome = self.biome_listbox.get(self.biome_listbox.curselection())
            self.biome_selection.set('Selected biome: {}'.format(biome))
            logging.info('Selected biome: ' + biome)
        except TclError:
            print('err')
            pass

    def tag_biome_handler(self, *args, **kwargs):
        study_id = self.study_id_var.get().replace('Study id: ', '')
        biome = self.biome_selection.get().replace('Selected biome: ', '')
        logging.info('Tagging {} with biome {}'.format(study_id, biome))
        lineage = re.sub('(\(\d\.\d+ match\))', '', biome)
        self.btc.tag_study(study_id, lineage)

        self.remove_study_from_list(study_id)
        self.reset_study_display()
        self.set_confirmation_line(study_id, biome)

        self.suggested_biomes = []
        self.filter_biome_list()

    def remove_study_from_list(self, study_id):
        logging.info('Removing study {} from list.'.format(study_id))
        self.btc.update_taggable_studies()
        self.update_study_list()

    def update_study_list(self):
        for i, s in enumerate(
                sorted([s.secondary_accession for s in self.btc.studies])):
            if self.study_listbox.get(i) != s:
                self.study_listbox.insert(i, s)
        self.study_listbox.delete(len(self.btc.studies), END)

    def init_confirmation_line(self):
        self.tagging_confirmation_var = StringVar(value='')
        self.tagging_confirmation_lbl = Label(
            self, textvariable=self.tagging_confirmation_var, fg="red")
        self.tagging_confirmation_lbl.grid(row=4, column=0, padx=10, pady=3)

    def set_confirmation_line(self, study_id, biome):
        s = 'Study {} was tagged with biome {}'.format(study_id, biome)
        self.tagging_confirmation_var.set(s)

    def reset_confirmation_line(self):
        self.tagging_confirmation_var.set('')
示例#55
0
    def __init__(self):  #for class initiation
        window = Tk()
        window.title("TipCalculator")
        window.configure(background="blue")
        window.geometry("375x250")
        window.resizable(width=False, height=False)

        self.meal_cost = StringVar()
        self.tip_percent = IntVar()
        self.tip = StringVar()
        self.total_cost = StringVar()

        tip_percents = Label(window,
                             text="Tip percentages",
                             bg="purple",
                             fg="white")
        tip_percents.grid(column=0, row=0, padx=15)

        bill_amount = Label(window, text="Bill amount", bg="black", fg="white")
        bill_amount.grid(column=1, row=0, padx=15)

        bill_amount_entry = Entry(window,
                                  textvariable=self.meal_cost,
                                  width=14)
        bill_amount_entry.grid(column=2, row=0)

        five_percent_tip = Radiobutton(window,
                                       text="0.5%",
                                       variable=self.tip_percent,
                                       value=5)
        five_percent_tip.grid(column=0, row=1)

        ten_percent_tip = Radiobutton(window,
                                      text="10%",
                                      variable=self.tip_percent,
                                      value=10)
        ten_percent_tip.grid(column=0, row=2)

        fifteen_percent_tip = Radiobutton(window,
                                          text="15%",
                                          variable=self.tip_percent,
                                          value=15)
        fifteen_percent_tip.grid(column=0, row=3)

        twenty_percent_tip = Radiobutton(window,
                                         text="20%",
                                         variable=self.tip_percent,
                                         value=20)
        twenty_percent_tip.grid(column=0, row=4)

        twentyfive_percent_tip = Radiobutton(window,
                                             text="25%",
                                             variable=self.tip_percent,
                                             value=25)
        twentyfive_percent_tip.grid(column=0, row=5)

        thirty_percent_tip = Radiobutton(window,
                                         text="30%",
                                         variable=self.tip_percent,
                                         value=30)
        thirty_percent_tip.grid(column=0, row=6)

        tip_amount_lb1 = Label(window,
                               text="Tip Amount",
                               bg="brown",
                               fg="White")
        tip_amount_lb1.grid(column=1, row=3, padx=15)

        tip_amount_entry = Entry(window, textvariable=self.tip, width=14)
        tip_amount_entry.grid(column=2, row=3)

        bill_total_lb1 = Label(window,
                               text="Bill Total",
                               bg="blue",
                               fg="white")
        bill_total_lb1.grid(column=1, row=5, padx=15)
        bill_total_entry = Entry(window,
                                 textvariable=self.total_cost,
                                 width=14)
        bill_total_entry.grid(column=2, row=5)

        calculate_btn = Button(window,
                               text="Calculate",
                               bg="green",
                               fg="white",
                               command=self.calculate)
        calculate_btn.grid(column=1, row=7, padx=15)

        clear_btn = Button(window,
                           text="clear",
                           bg="black",
                           fg="white",
                           command=self.clear)
        clear_btn.grid(column=2, row=7)
        window.mainloop()
示例#56
0
    text.delete('1.0', 'end')
    for i in all_values:
        if i.get() == 1:
            text.insert('end', f'ON {all_buttons[all_values.index(i)]}\n')


def off(event):
    text.delete('1.0', 'end')
    for i in all_values:
        if i.get() == 0:
            text.insert('end', f'OFF {all_buttons[all_values.index(i)]}\n')


if __name__ == '__main__':
    root = Tk()
    value1 = IntVar()
    value2 = IntVar()
    value3 = IntVar()
    all_values = [value1, value2, value3]
    check_button1 = Checkbutton(root,
                                text='1',
                                variable=value1,
                                offvalue=0,
                                onvalue=1)
    check_button2 = Checkbutton(root,
                                text='2',
                                variable=value2,
                                offvalue=0,
                                onvalue=1)
    check_button3 = Checkbutton(root,
                                text='3',
示例#57
0
    def update_filter(self, gui, send_pos=True):
        if self.client_tuple:
            self.client_tuple[0].kernel = self
        if len(gui.view_labels) > 0:
            [label.grid_forget() for label in gui.view_labels]
            [chekb.grid_forget() for chekb in gui.view_checks]
            gui.view_labels = []
            gui.view_checks = []
            gui.view_ch_val = []
        if gui.color.get() == "all" and gui.shape.get() == "all":
            filtered_items = list(
                self.mongo_db.find({}, {
                    "<img>": 1,
                    "_id": 0,
                    "ID": 1,
                    "X": 1,
                    "Y": 1
                }))
            current_filter = ("all", "all")
        elif gui.color.get() == "all":
            filtered_items = list(
                self.mongo_db.find({"#Shape": gui.shape.get()}, {
                    "<img>": 1,
                    "_id": 0,
                    "ID": 1,
                    "X": 1,
                    "Y": 1
                }))
            current_filter = ("all", gui.shape.get())
        elif gui.shape.get() == "all":
            filtered_items = list(
                self.mongo_db.find({"#Color": gui.color.get()}, {
                    "<img>": 1,
                    "_id": 0,
                    "ID": 1,
                    "X": 1,
                    "Y": 1
                }))
            current_filter = (gui.color.get(), "all")
        else:
            filtered_items = list(
                self.mongo_db.find(
                    {
                        "#Color": gui.color.get(),
                        "#Shape": gui.shape.get()
                    }, {
                        "<img>": 1,
                        "_id": 0,
                        "ID": 1,
                        "X": 1,
                        "Y": 1
                    }))
            current_filter = (gui.color.get(), gui.shape.get())
        self.check_filter_update(current_filter)

        gui.photos = []
        if len(filtered_items) > 0:
            image = PIL.Image.open(BytesIO(filtered_items[0]["<img>"]))
            items_per_row = int(gui.view_canvas.winfo_width() / image.size[0])

            for i, item in enumerate(filtered_items):
                photo = ImageTk.PhotoImage(
                    PIL.Image.open(BytesIO(item["<img>"])))
                val = IntVar()
                val.set(1)
                gui.view_checks.append(
                    Checkbutton(gui.view_frame,
                                image=photo,
                                variable=val,
                                command=self.send_pos))
                if item["ID"] in self.id_id.keys():
                    gui.view_labels.append(
                        Label(gui.view_frame,
                              text=self.id_id[item["ID"]],
                              background="white"))
                else:
                    gui.view_labels.append(
                        Label(gui.view_frame, text="", background="white"))
                gui.view_ch_val.append(val)
                gui.photos.append(photo)
            self.layout(None)
            self.filtered_items = filtered_items
            if send_pos:
                self.send_pos()

        self.log(
            "new filter", "Color: {} Shape: {}".format(gui.color.get(),
                                                       gui.shape.get()))
示例#58
0
def cashbook():
    global mycur
    global usertext1
    global window5
    global trv
    global search
    global tracc
    global trname
    global trbalance

    global trwithdrawl
    global trdeposit
    global trfinal
    global tremail
    global trtime

    window5 = tkinter.Tk()
    window5.geometry('1250x900+50+5')
    window5.configure(background='light blue')
    window5.title('SPR bank')
    window5.iconbitmap(r'favicon (2).ico')

    search = StringVar(window5)
    tracc = StringVar(window5)
    trname = StringVar(window5)
    trbalance = IntVar(window5)
    trwithdrawl = IntVar(window5)
    trdeposit = IntVar(window5)
    trfinal = IntVar(window5)
    tremail = StringVar(window5)
    trtime = StringVar(window5)

    wrapper1 = tkinter.LabelFrame(window5, text='cashbook', bg='light blue')
    wrapper2 = tkinter.LabelFrame(window5, text='update', bg='light blue')

    wrapper1.pack(fill='both', expand='yes', padx='20', pady='0')
    wrapper2.pack(fill='both', expand='yes', padx='20', pady='10')

    trv = Treeview(wrapper1,
                   columns=(1, 2, 3, 4, 5, 6),
                   show='headings',
                   height='15')
    trv.pack()
    trv.heading(1, text='firstname')
    trv.heading(2, text='lastname')
    trv.heading(3, text='accountno')
    trv.heading(4, text='email')
    trv.heading(5, text='lasttime update')
    trv.heading(6, text='Closing Balance')

    lbl1 = tkinter.Label(wrapper2,
                         text='Search :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl1.grid(row=1, column=0, padx='5', pady='3')
    ent1 = tkinter.Entry(wrapper2, bd=4, textvariable=search)
    ent1.grid(row=1, column=1, padx='5', pady='3')

    btnsr = tkinter.Button(wrapper2,
                           text="SEARCH",
                           activebackground='green',
                           command=search1)
    btnsr.grid(row=1, column=2)
    btncl = tkinter.Button(wrapper2,
                           text="CLEAR",
                           activebackground='green',
                           command=clear)

    trv.bind('<Double 1>', getrow)

    btncl.grid(row=1, column=4)
    lbl2 = tkinter.Label(wrapper2,
                         text='Accountno:',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl2.grid(row=4, column=0, padx='5', pady='3')
    ent2 = tkinter.Entry(wrapper2, bd=4, textvariable=tracc)
    ent2.grid(row=4, column=1, padx='20', pady='5')

    lbl3 = tkinter.Label(wrapper2,
                         text='Name :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl3.grid(row=5, column=0)
    ent3 = tkinter.Entry(wrapper2, bd=4, textvariable=trname)
    ent3.grid(row=5, column=1, padx='20', pady='5')

    lbl5 = tkinter.Label(wrapper2,
                         text='email :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl5.grid(row=6, column=0)
    ent5 = tkinter.Entry(wrapper2, bd=4, textvariable=tremail)
    ent5.grid(row=6, column=1, padx='20', pady='5')

    lbl5 = tkinter.Label(wrapper2,
                         text='lasttime update :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl5.grid(row=7, column=0)
    ent5 = tkinter.Entry(wrapper2, bd=4, textvariable=trtime)
    ent5.grid(row=7, column=1, padx='20', pady='5')

    lbl4 = tkinter.Label(wrapper2,
                         text='balance :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl4.grid(row=8, column=0)
    ent4 = tkinter.Entry(wrapper2, bd=4, textvariable=trbalance)
    ent4.grid(row=8, column=1, padx='20', pady='5')
    lbl5 = tkinter.Label(wrapper2,
                         text='Withdrawl :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl5.grid(row=6, column=4)
    ent5 = tkinter.Entry(wrapper2, bd=4, textvariable=trwithdrawl)
    ent5.grid(row=6, column=5, padx='20', pady='5')

    lbl5 = tkinter.Label(wrapper2,
                         text='Deposit :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl5.grid(row=7, column=4, padx='5', pady='3')
    ent5 = tkinter.Entry(wrapper2, bd=4, textvariable=trdeposit)
    ent5.grid(row=7, column=5, padx='5', pady='3')

    lbl6 = tkinter.Label(wrapper2,
                         text='final balance :',
                         font=('Gabriola'),
                         bg='light blue',
                         fg='black')
    lbl6.grid(row=8, column=4, padx='5', pady='3')
    ent6 = tkinter.Entry(wrapper2, bd=4, textvariable=trfinal)
    ent6.grid(row=8, column=5, padx='5', pady='3')

    btnup = tkinter.Button(wrapper2,
                           text="DELETE",
                           activebackground='red',
                           command=delete)
    btnup.grid(row=9, column=1)

    btnup = tkinter.Button(wrapper2,
                           text="UPDATE",
                           activebackground='green',
                           command=updatenew)
    btnup.place(x=570, y=150, height=25, width=150)

    btnex = tkinter.Button(wrapper2,
                           text="EXIT",
                           activebackground='red',
                           command=window2new2)
    btnex.place(x=750, y=150, height=25, width=150)

    query = 'SELECT fristname,lastname,accountno,email,accountcreated,closingbalance from account'
    mycur.execute(query)
    rows = mycur.fetchall()
    update(rows)
class App(Tk):
    def showMessage(self, messagetype, messageString):
        if messagetype == MSG_ERROR:
            messagebox.showerror("Error", messageString)
        elif messagetype == MSG_WARN:
            messagebox.showwarning("Warning", messageString)
        elif messagetype == MSG_INFO:
            messagebox.showinfo("Information", messageString)

    def sendMessage(self, messageType, messageText):
        self.api.sendMessage(messageType, messageText)

    def getGrid(self):

        if self.useManualPosition == False and self.gpsl == None:
            print('GPS Listener not running. Update settings and try again.')
            # js8callAPIsupport.js8CallUDPAPICalls.showMessage(MSG_ERROR, getStatus()))
            self.showMessage(
                'ERROR',
                'GPS Listener not running. Update settings and try again.')
            return
        if self.showoutput == 1:
            print('Getting Grid from GPS')

        if self.useManualPosition:
            gpsText = self.manualposition
        else:
            gpsText = self.gpsl.getMaidenhead()

        if self.showoutput == 1:
            print(gpsText)
        if gpsText == None:
            gpsText = "No Fix"

        ngr = None

        if self.gpsl != None:
            ngr = self.gpsl.get_ngr()

        if gpsText != None:
            if gpsText == 'None':
                gpsText = "No Fix"
                #print("Got Grid "+gpsText)
            if ngr != None:
                None
                #print("Got NGR "+ngr)

            latlon = ''

            if self.useManualPosition == False:
                if self.gpsl.getStatus().startswith('Error'):
                    self.gpsText = self.gpsl.getStatus()
                    lat = None
                    lon = None
                    latlon = self.gpsl.getStatus()
                else:
                    lat = self.gpsl.getCurrentLat()
                    lon = self.gpsl.getCurrentLon()

                if lat != None:
                    latf = f"{lat:.5f}"
                    lonf = f"{lon:.5f}"
                    latlon = str(latf) + ', ' + str(lonf)

            self.var1.set(gpsText)
            self.latlonvar.set(latlon)

            return gpsText


#            if gpsText!= "No Fix" and gpsText!='JJ00aa00':
#                self.setJS8CallGridButton.configure(state='normal')
#                self.sendJS8CallALLCALLButton.configure(state='normal')
#                self.latlonButton.configure(state='normal')
#self.ngrStr.set(ngr)
#            else:
#                self.setJS8CallGridButton.configure(state='disabled')
#                self.sendJS8CallALLCALLButton.configure(state='disabled')
#                self.latlonButton.configure(state='normal')
#                self.ngrStr.set('No Fix')
#                self.var1.set('No Fix')
#                self.latlonvar.set('No Fix')

#if gpsText=='JJ00aa00':
#self.ngrStr.set('No Fix')

    def show_frame(self, context):
        frame = self.frames[context]
        frame.tkraise()

    def nav_buttons(self, frame, controller):

        #        gps_page=Button(frame, text="GPS", command=lambda:controller.show_frame(GPSPage), bg="white", font=NAV_BUTTON_FONT, width=NAV_BUTTON_WIDTH)
        #        gps_page.grid(row=2, column=0)
        #        aprs_page=Button(frame, text="APRS Message", command=lambda:controller.show_frame(MessagePage), bg="white", font=NAV_BUTTON_FONT, width=NAV_BUTTON_WIDTH)
        #        aprs_page.grid(row=2, column=1)
        #        settings_page=Button(frame, text="Settings", command=lambda:controller.show_frame(SettingsPage), bg="white", font=NAV_BUTTON_FONT, width=NAV_BUTTON_WIDTH)
        #        settings_page.grid(row=2, column=2)

        rh = 0.1
        rw = 0.28
        rx = 0.01
        # ry=0.02

        gps_page = Button(frame,
                          text="GPS",
                          command=lambda: controller.show_frame(GPSPage),
                          bg="white")
        gps_page.grid(row=2, column=0, sticky=W + E + N + S, padx=5, pady=5)

        aprs_page = Button(frame,
                           text="APRS Message",
                           command=lambda: controller.show_frame(MessagePage),
                           bg="white")
        aprs_page.grid(row=2, column=1, sticky=W + E + N + S, padx=5, pady=5)
        settings_page = Button(
            frame,
            text="Settings",
            command=lambda: controller.show_frame(SettingsPage),
            bg="white")
        settings_page.grid(row=2,
                           column=2,
                           sticky=W + E + N + S,
                           padx=5,
                           pady=5)

    def sendGridToALLCALL(self, gridText):
        if self.gpsl != None:
            status = self.gpsl.getStatus()
        if self.useManualPosition == True:
            status = "Manual Grid"

        self.api.sendGridToALLCALL(gridText, status)

    def sendGridToJS8Call(self, gridText):
        if self.gpsl != None:
            status = self.gpsl.getStatus()
        if self.useManualPosition == True:
            status = "Manual Grid"

        self.api.sendGridToJS8Call(gridText, status)

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Main Window is closing, call any function you'd like here!")

    def __enter__(self):
        # make a database connection and return it
        print('Starting')

    def ask_quit(self):
        if self.gpsl != None:
            print('Shutting down GPS Listener')
            self.shutdownGPS()
            #self.gpsl.setReadGPS(False)
            #self.gpsl.join()

        print('Exiting. Thanks for using JS8CallUtils By M0IAX')
        self.destroy()

    def update_timer(self):
        if self.autoGridToJS8Call.get() == 0:
            self.initTimer()
            self.timerStr.set("Timer Not Active")

        if self.autoGridToJS8Call.get() == 1:

            if self.timer <= 0:
                self.initTimer()
            self.timer = self.timer - 1
            t = "Timer: " + str(self.timer)
            self.timerStr.set(t)

            if self.timer <= 0:
                #print('Got to Zero')
                gridstr = self.getGrid()
                #print('grd ', gridstr)
                combotext = self.autocombo.get()
                #print("combo text ", combotext)
                if gridstr != None and gridstr != '' and gridstr != "No Fix":
                    if combotext == "Auto update JS8Call Grid":
                        self.sendGridToJS8Call(gridstr)
                    if combotext == "Auto TX Grid to APRSIS":
                        self.sendGridToALLCALL(gridstr)
                    if combotext == "Auto TX Grid to APRSIS and Update JS8Call Grid":
                        self.sendGridToJS8Call(gridstr)
                        self.sendGridToALLCALL(gridstr)

                else:
                    print('No grid. enabld gps and wait for fix')
                self.initTimer()
        self.after(1000, self.update_timer)

    #def update_status_timer(self):
    #    self.mainWindow.after(10000, self.update_status_timer)

    def initTimer(self):
        self.timer = self.MAX_TIMER

    def autocomboChange(self, event):
        return ''

    def comboChange(self, event):
        mode = self.combo.get()
        print("mode is " + mode + "<<")
        if mode == "APRS":
            self.callLbl.config(text='Enter Callsign (including SSID)')
        elif mode == "Email":
            self.callLbl.config(text='Enter Email Address to send to')
        elif mode == "SMS":
            self.callLbl.config(text='Enter cell phone number')
        elif mode == "SOTA Spot":
            self.callLbl.config(text='Will be sent to APRS2SOTA')

    def cb(self):
        None
        #if self.autoGridToJS8Call.get()==0:
        #    self.autoGridToJS8Call.set(1)
        #else:
        #    self.autoGridToJS8Call.set(0)
        #    self.timerStr.set("Timer Not Active")
    def shutdownGPS(self):
        if self.gpsl != None:
            print('Shutting down GPS Listener')

            #self.gpsl.destroy()
            if isinstance(self.gpsl, networkGPSListener.netWorkGPS):
                self.gpsl.teminate()

            self.gpsl.setReadGPS(False)
            self.gpsl.join()
            self.gpsl = None

    def refreshSettings(self):

        self.useManualPosition = False
        self.settingValues = settings.Settings()

        self.showoutput = int(
            self.settingValues.getDebugSettingValue('showoutput'))

        self.timeinmins = int(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoatstart = int(
            self.settingValues.getAppSettingValue('autoonatstart'))
        self.autooption = int(
            self.settingValues.getAppSettingValue('autoselectedoption'))

        self.autocombo.current(self.autooption)  #set the selected item

        self.MAX_TIMER = self.timeinmins * 60

        self.serverPortVar = StringVar()
        self.serverVar = IntVar()

        self.serverPortVar.set(
            int(self.settingValues.getNetworkSettingValue('serverport')))
        self.serverVar.set(
            self.settingValues.getNetworkSettingValue('serverip'))

        self.gpsOption = self.settingValues.getGPSHardwareSettingValue(
            'option')

        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()

        self.gpsComPortVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpscomport'))
        self.gpsComPortSpeedVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpsportspeed'))
        self.maidPreceision.set(
            self.settingValues.getAppSettingValue('precision'))
        self.autoTimeVar.set(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoGridToJS8Call.set(
            self.settingValues.getAppSettingValue('autoonatstart'))

        self.autoGridCheck.configure(text="Enable Auto update every " +
                                     str(self.timeinmins) + " mins.")

        if self.gpsOption == 'None':
            self.autoGridCheck.configure(state='disabled')
            self.autoGridToJS8Call.set(0)
        else:
            self.autoGridCheck.configure(state='normal')

        if self.gpsl != None:
            self.gpsl.setPrecision(
                int(self.settingValues.getAppSettingValue('precision')))
            self.gpsl.setShowDebug(self.showoutput)

        if self.gpsOptionBeforeRefresh != self.gpsOption:
            if self.gpsl != None:
                print('Shutting down GPS Listener')

                #self.gpsl.destroy()
                if isinstance(self.gpsl, networkGPSListener.netWorkGPS):
                    self.gpsl.teminate()

                self.gpsl.setReadGPS(False)
                self.gpsl.join()
                self.gpsl = None

            if self.gpsOption != 'None':
                print('Determine GPS Listener')
                if self.gpsOption == 'GPSD':
                    print('Starting GPSD GPS Listener')
                    self.gpsl = gpsdGPSListener.GpsListener(
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                elif self.gpsOption == 'Network':
                    print('Starting Network GPS Listener')
                    self.gpsl = networkGPSListener.netWorkGPS(
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpscomport'),
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpsportspeed'),
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                elif self.gpsOption == 'Windows Location Services':
                    print('Using Windows Location Services')
                    self.gpsl = windowsLocation.locationservices(
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                elif self.gpsOption == 'Manual':
                    print('Manual Position, not suing GPS')

                    self.useManualPosition = True
                    self.manualposition = self.settingValues.getGPSHardwareSettingValue(
                        'gpscomport')
                else:
                    print('Running serial gps again')
                    self.gpsl = serialGPSlistener.GPSListener(
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpscomport'),
                        self.settingValues.getGPSHardwareSettingValue(
                            'gpsportspeed'),
                        self.settingValues.getAppSettingValue('precision'),
                        self.showoutput)
                if self.gpsl != None:
                    self.gpsl.start()
            else:
                print('Setting thread to None')
                self.gpsl = None
        self.gpsOptionBeforeRefresh = self.gpsOption

    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        self.seq = 1

        self.settingValues = settings.Settings()

        self.showoutput = int(
            self.settingValues.getDebugSettingValue('showoutput'))

        self.timeinmins = int(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoatstart = int(
            self.settingValues.getAppSettingValue('autoonatstart'))
        self.autooption = int(
            self.settingValues.getAppSettingValue('autoselectedoption'))

        #self.autocombo.set(self.autooption)

        self.MAX_TIMER = self.timeinmins * 60

        self.serverPortVar = StringVar()
        self.serverVar = IntVar()

        self.serverPortVar.set(
            int(self.settingValues.getNetworkSettingValue('serverport')))
        self.serverVar.set(
            self.settingValues.getNetworkSettingValue('serverip'))

        self.api = js8callAPIsupport.js8CallUDPAPICalls(
            self.settingValues.getNetworkSettingValue('serverip'),
            int(self.settingValues.getNetworkSettingValue('serverport')))

        self.gpsOption = self.settingValues.getGPSHardwareSettingValue(
            'option')

        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()

        self.gpsComPortSpeedVar = self.settingValues.getGPSHardwareSettingValue(
            'gpsportspeed')
        self.gpsComPortVar = self.settingValues.getGPSHardwareSettingValue(
            'gpscomport')

        self.gpsOptionBeforeRefresh = self.gpsOption

        self.useManualPosition = False

        self.gpsl = None

        if self.gpsOption != "None":
            print("GPS Option " + self.gpsOption)
            if self.gpsOption == 'GPSD':
                self.gpsl = gpsdGPSListener.GpsListener(
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)
            elif self.gpsOption == 'Network':
                self.gpsl = networkGPSListener.netWorkGPS(
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpscomport'),
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpsportspeed'),
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)
            elif self.gpsOption == 'Windows Location Services':
                print('Using Windows Location Services')
                self.gpsl = windowsLocation.locationservices(
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)

            elif self.gpsOption == 'Manual':
                self.useManualPosition = True
                self.manualposition = self.settingValues.getGPSHardwareSettingValue(
                    'gpscomport')
            else:
                self.gpsl = serialGPSlistener.GPSListener(
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpscomport'),
                    self.settingValues.getGPSHardwareSettingValue(
                        'gpsportspeed'),
                    self.settingValues.getAppSettingValue('precision'),
                    self.showoutput)

            if self.gpsl != None:
                self.gpsl.start()

        self.geometry(str(WIDTH) + "x" + str(HEIGHT))
        self.title("JS8Call Utilities by M0IAX")

        self.gpsComPortVar = StringVar()
        self.gpsComPortSpeedVar = StringVar()
        self.maidPreceision = StringVar()
        self.autoTimeVar = StringVar()
        self.autoGridToJS8Call = IntVar()

        self.var1 = StringVar()
        self.var2 = StringVar()
        self.latlonvar = StringVar()

        #set default values
        self.gpsComPortVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpscomport'))
        self.gpsComPortSpeedVar.set(
            self.settingValues.getGPSHardwareSettingValue('gpsportspeed'))
        self.maidPreceision.set(
            self.settingValues.getAppSettingValue('precision'))
        self.autoTimeVar.set(
            self.settingValues.getAppSettingValue('autotimeperiod'))
        self.autoGridToJS8Call.set(
            self.settingValues.getAppSettingValue('autoonatstart'))

        if self.useManualPosition:
            self.var1.set(self.manualposition)

        #Main window frame
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (GPSPage, MessagePage, SettingsPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky='nsew')

        self.show_frame(GPSPage)

        bottomFrame = Frame(self)
        bottomFrame.pack()

        self.autocombo = Combobox(bottomFrame, state='readonly', width=45)
        self.autocombo.state = 'disabled'
        self.autocombo.bind('<<ComboboxSelected>>', self.autocomboChange)
        self.autocombo['values'] = (
            "Auto update JS8Call Grid", "Auto TX Grid to APRSIS",
            "Auto TX Grid to APRSIS and Update JS8Call Grid")

        self.autocombo.current(self.autooption)  #set the selected item
        #self.autocombo.place(relx=0.05,rely=0.63, relwidth=0.9,relheight=0.1)
        self.autocombo.grid(row=0, column=0, sticky=W + E + N + S)

        self.autoGridToJS8Call = IntVar(value=self.autoatstart)
        self.autoGridCheck = Checkbutton(bottomFrame,
                                         text="Enable Auto update every " +
                                         str(self.timeinmins) + " mins.",
                                         variable=self.autoGridToJS8Call,
                                         command=self.cb)
        #self.autoGridCheck.place(relx=0.05,rely=0.71, relwidth=0.9,relheight=0.1)
        self.autoGridCheck.grid(row=1,
                                column=0,
                                sticky=W + E + N + S,
                                padx=5,
                                pady=5)

        if self.gpsOption == 'None':
            self.autoGridCheck.configure(state='disabled')
            self.autoGridToJS8Call.set(0)
        else:
            self.autoGridCheck.configure(state='normal')

        self.timer = 60  #Set timer to 60 for the first tx GPS should have a lock in that time
        self.timerStr = StringVar()

        self.timerStr.set("Timer Not Active")
        self.timerlabel = Label(bottomFrame, textvariable=self.timerStr)
        #self.timerlabel.place(relx=0.05,rely=0.81, relwidth=0.9,relheight=0.1)
        self.timerlabel.grid(row=2, column=0, sticky=W + E + N + S)

        buttonFrame = Frame(self)
        buttonFrame.pack()

        self.nav_buttons(buttonFrame, self)

        self.update_timer()
示例#60
0
    def fenetreChoixEnLigne(self):
        tailleX = 300
        tailleY = 200

        numero = str(self.root.geometry()).split('+')
        posX = int(numero[1])
        posY = int(numero[2])

        positionX = int(posX + (self.tailleEcranX / 2) - (tailleX / 2))
        positionY = int(posY + (self.tailleEcranY / 2) - (tailleY / 2))

        geo = str(tailleX) + "x" + str(tailleY) + "+" + str(
            positionX) + "+" + str(positionY)

        self.win = Toplevel(self.root)
        self.win.geometry(geo)
        self.win.title("Création")
        self.win.resizable(width=False, height=False)

        Label(self.win,
              text="Choisissez la taille du plateau:",
              width=41,
              height=2).grid(row=0, column=0, columnspan=2)
        varTaille = IntVar()
        varTaille.set(0)
        Radiobutton(self.win,
                    width=10,
                    height=3,
                    variable=varTaille,
                    text='10x10',
                    value=10,
                    indicatoron=0).grid(row=1, column=0, padx=0)
        Radiobutton(self.win,
                    width=10,
                    height=3,
                    variable=varTaille,
                    text='20x20',
                    value=20,
                    indicatoron=0).grid(row=1, column=1, padx=0)

        Label(self.win,
              text="Choisissez la durée d'un tour:").grid(row=2,
                                                          column=0,
                                                          columnspan=2)
        value = IntVar()
        value.set(10)
        entree = Entry(self.win, textvariable=value, width=30)
        entree.grid(row=3, column=0, columnspan=2, padx=7)

        Label(self.win, text="").grid(row=4, column=0, columnspan=2)

        canvasLigne = Canvas(self.win, width=300, height=10)
        canvasLigne.create_line(10, 7, 290, 7)
        canvasLigne.grid(row=5, column=0, columnspan=2)

        Button(self.win,
               text='VALIDER',
               command=lambda: self.nouveau2JoueursEnLigne(varTaille, value)
               ).grid(row=6, column=0)
        Button(self.win, text='ANNULER',
               command=self.win.destroy).grid(row=6, column=1)