Beispiel #1
0
class CheckBox:
    def __init__(self, root, text: str, x: int, y: int):
        self.varChecked = BooleanVar()
        self.text = text
        self.checkbox = Checkbutton(root,
                                    text=self.text,
                                    variable=self.varChecked,
                                    onvalue=True,
                                    offvalue=False)
        self.x = x
        self.y = y

        self.checkbox.pack()
        self.checkbox.place(x=self.x, y=self.y)

    @property
    def command(self):
        return self.command

    @command.setter
    def command(self, command):
        self.checkbox['command'] = command

    def isChecked(self):
        return True if self.varChecked.get() else False

    def check(self):
        self.checkbox.select()

    def uncheck(self):
        self.checkbox.deselect()
    def ask_for_object_classes(self):

        window = Toplevel(self.root)
        window.wm_title("Choose object classes to detect?")
        window.resizable(width=False, height=False)
#        instruct.geometry('{}x{}'.format(500, 100))
        window.geometry('{}x{}'.format(200, 320))
#        time.config(bg='lightgreen')
        window.attributes('-topmost', True)
        
        label1 = Label(window, text="Choose object classes to detect?")
        label1.pack(side="top", padx="10", pady="5")

        self.object_classes_to_detect = {key:IntVar(value=value) for key, value in self.object_classes_to_detect.items()}
        
        for key, value in self.object_classes_to_detect.items():
            c = Checkbutton(window, text = key, variable = value, onvalue = 1, offvalue = 0)
            c.select()
            c.pack(side="top", anchor=W, padx="10", pady="5")
        
        btn1 = Button(window, text="Save", command=lambda *args: self.set_classes(window))
        btn1.pack(side="top", fill="both", expand="yes", padx="10", pady="5")
        
        
        self.root.wait_window(window)
Beispiel #3
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        shift = StringVar()
        known = BooleanVar()   # true -> shift key known

        self.columnconfigure(0, weight=1, pad=5)
        self.columnconfigure(1, weight=1, pad=5)

        self.rowconfigure(0, pad=5)
        self.rowconfigure(1, pad=5)
        self.rowconfigure(2, weight=1, pad=5)
        self.rowconfigure(3, pad=5)
        self.rowconfigure(4, weight=1, pad=5)

        # Title
        bbutton = Button(self, text="<", command=lambda: controller.show_frame("MainPage"))
        bbutton.grid(row=0, column=0, padx=10, sticky=W)
        title = Label(self, text="Caesar Cipher")
        title.grid(row=0, columnspan=2, padx=10)

        # Shift Key
        sframe = Frame(self)
        sentry = Entry(sframe, textvariable=shift, width=55)
        sentry.pack(side=LEFT)
        sentry.insert(0, "Shift key")
        cb = Checkbutton(sframe, text="Unknown key", variable=known)
        cb.select()
        cb.pack(side=RIGHT, padx=10)
        sframe.grid(row=1, columnspan=2, padx=10, sticky=W+E)

        # Text input
        tinput = Text(self, wrap=WORD)
        tinput.grid(row=2, columnspan=2, padx=10, pady=10, sticky=N+E+S+W)
        scrolli = Scrollbar(self, command=tinput.yview)
        tinput.configure(yscrollcommand=scrolli.set)
        scrolli.grid(row=2, column=1, pady=10, sticky=N+S+E)
        tinput.insert(1.0, "Input")
        tinput.bind("<Control-Key-a>", select_all)  # select-all Windows/Linux
        tinput.bind("<Command-Key-a>", select_all)  # select-all Mac

        # Encode/Decode buttons
        ebutton = Button(self, text="Encode", width=15)
        ebutton.grid(row=3, column=0, padx=10, sticky=E)
        ebutton.configure(command=lambda: self.encode_prep(tinput.get(1.0, 'end-1c'), shift.get()))
        dbutton = Button(self, text="Decode", width=15)
        dbutton.grid(row=3, column=1, padx=10, sticky=W)
        dbutton.configure(command=lambda: self.decode_prep(tinput.get(1.0, 'end-1c'), shift.get(), not known.get()))

        # Output box
        self.output = Text(self, wrap=WORD)
        self.output.grid(row=4, columnspan=2, padx=10, pady=10, sticky=N+E+S+W)
        self.output.bind("<1>", lambda event: self.output.focus_set())
        scrollo = Scrollbar(self, command=self.output.yview)
        scrollo.grid(row=4, column=1, pady=10, sticky=N+S+E)
        self.output.configure(yscrollcommand=scrollo.set)
        self.output.insert(1.0, "Output")
        self.output.configure(state="disabled")
        self.output.bind("<Control-Key-a>", select_all)    # select-all Windows/Linux
        self.output.bind("<Command-Key-a>", select_all)    # select-all Mac
Beispiel #4
0
    def create_other_buttons(self):
        f = self.make_frame()[0]

        btn = Checkbutton(f, anchor="w",
                variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.select()
Beispiel #5
0
    def init_ui(self):
        self.var = BooleanVar()

        cb = Checkbutton(self,
                         text="Show title",
                         variable=self.var,
                         command=self.on_click)
        cb.select()
        cb.place(x=50, y=20)
    def populate(self):
        if self.frame_unpaid is not None:
            self.frame_unpaid.destroy()

        if self.frame_paid is not None:
            self.frame_paid.destroy()

        if self.frame_add is not None:
            self.frame_add.destroy()

        if self.frame_dialog is not None:
            self.frame_dialog.destroy()

        if self.addBillBox is not None:
            self.addBillBox.destroy()

        self.frame_unpaid = Frame(self, relief=RIDGE, borderwidth=2)
        self.frame_unpaid.pack(pady=0, padx=0, fill=X)
        self.frame_paid = Frame(self, relief=RIDGE, borderwidth=2)
        self.frame_paid.pack(pady=0, padx=0, fill=X)
        self.frame_dialog = Frame(self)
        self.frame_dialog.pack(pady=0, padx=0, fill=X)

        Label(self.frame_unpaid, text=unpaid_bills_label_text).pack(side=TOP, padx=5, pady=10)

        for bill_string in sorted(unpaid_dict):
            local_frame = Frame(self.frame_unpaid)
            local_frame.pack(pady=0, padx=0, fill=X)
            unpaid_dict[bill_string] = IntVar()
            Label(local_frame, text=bill_string).pack(side=LEFT, padx=5)
            c = Checkbutton(local_frame, text=checkbox_text, variable=unpaid_dict[bill_string], command=self.chk)
            c.pack(side=RIGHT)

        Label(self.frame_paid, text=paid_bills_label_text).pack(side=TOP, padx=5, pady=10)

        for data in sorted(paid_dict):
            bill_data = data.split('|')
            bill_string = bill_data[0]
            if len(bill_data) > 1:
                bill_date = bill_data[1].split('.')
                if len(bill_date) > 1:
                    bill_string += '(' + bill_date[1] + '.' + bill_date[0] + ')'
                else:
                    bill_string += '(xx.' + bill_date[0] + ')'

            local_frame = Frame(self.frame_paid)
            local_frame.pack(pady=0, padx=0, fill=X)
            paid_dict[data] = IntVar()
            Label(local_frame, text=bill_string).pack(side=LEFT, padx=5)
            c = Checkbutton(local_frame, text=checkbox_text, variable=paid_dict[data], command=self.unchk)
            c.pack(side=RIGHT)
            c.select()

        Button(self.frame_dialog, text='CONFIGURE', command=self.setup, width=9).pack(side=RIGHT, padx=5, pady=5)

        Button(self.frame_dialog, text='DISMISS', command=self.dismiss, width=9).pack(side=LEFT, padx=5, pady=5)
Beispiel #7
0
 def initUI(self):
     self.parent.title("Checkbutton")
     self.pack(fill=BOTH, expand=True)
     self.var = BooleanVar()
     cb = Checkbutton(self,text="Show Title",variable=self.var,command=self.onClick)
     bc=Button(self,text="Button")
     bc.pack()
     bc.place(x=60,y=60)
     cb.select()
     cb.place(x=40,y=40)
    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)
Beispiel #9
0
 def body(self, master):
     self.optOuts = []
     self.cbs = []
     for optText in self.output_text_options:
         v = IntVar()
         cb = Checkbutton(master, text=optText, variable = v)
         cb.select()
         cb.pack(anchor=tk.W)
         self.cbs.append(cb)
         self.optOuts.append(v) 
     return self.cbs[0]
    def initUI(self):
      
        self.master.title("Checkbutton")

        self.pack(fill=BOTH, expand=True)
        self.var = BooleanVar()
        
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=50)
Beispiel #11
0
    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 _makesetting(setting_window, conf):
    setting_label = Label(setting_window,
                          text=_('Setting'),
                          font=('courier', 20, 'bold'))
    setting_label.pack(side=TOP)

    style_container = Frame(setting_window)
    style_container.pack(side=TOP)
    style_label = Label(style_container,
                        text=_('Display wallpaper in style: '),
                        font=('courier', 15, 'bold'))
    style_label.pack(side=LEFT)
    style_combobox = Combobox(style_container)
    available_style = {
        '3': 'zoom',
        '2': 'scaled',
        '1': 'stretched',
        '0': 'centered',
        '4': 'wallpaper'
    }
    style_combobox['value'] = (_('centered'), _('stretched'), _('scaled'),
                               _('zoom'), _('wallpaper'))
    style_combobox.state(['readonly'])
    style_combobox.current(int(conf['style']))
    style_combobox.pack(side=LEFT)

    random_container = Frame(setting_window)
    random_container.pack(side=TOP)
    random_label = Label(random_container,
                         text=_('Choose wallpaper randomly? '),
                         font=('courier', 15, 'bold'))
    random_label.pack(side=LEFT)
    random_checkbutton = Checkbutton(random_container)
    random_checkbutton.pack(side=LEFT)
    if conf['random'] == "1":
        random_checkbutton.select()

    interval_container = Frame(setting_window)
    interval_container.pack(side=TOP)
    interval_label = Label(interval_container,
                           text=_('Change wallpaper every '),
                           font=('courier', 15, 'bold'))
    interval_label.pack(side=LEFT)
    interval_text = Text(interval_container, height=1, width=4)
    interval_text.insert(END, conf['interval'])
    interval_text.pack(side=LEFT)
    minute_label = Label(interval_container,
                         text=_(' minutes.'),
                         font=('courier', 15, 'bold'))
    minute_label.pack(side=LEFT)
    def create_option_buttons(self):
        "Fill frame with Checkbuttons bound to SearchEngine booleanvars."
        f = self.make_frame("Options")

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.revar,
                text="Regular expression")
        btn.pack(side="left", fill="both")
        if self.engine.isre():
            btn.select()

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.casevar,
                text="Match case")
        btn.pack(side="left", fill="both")
        if self.engine.iscase():
            btn.select()

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.wordvar,
                text="Whole word")
        btn.pack(side="left", fill="both")
        if self.engine.isword():
            btn.select()

        if self.needwrapbutton:
            btn = Checkbutton(f, anchor="w",
                    variable=self.engine.wrapvar,
                    text="Wrap around")
            btn.pack(side="left", fill="both")
            if self.engine.iswrap():
                btn.select()
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)
Beispiel #15
0
 def create_option_buttons(self):
     "Fill frame with Checkbuttons bound to SearchEngine booleanvars."
     frame = self.make_frame("Options")[0]
     engine = self.engine
     options = [(engine.revar, "Regular expression"),
                (engine.casevar, "Match case"),
                (engine.wordvar, "Whole word")]
     if self.needwrapbutton:
         options.append((engine.wrapvar, "Wrap around"))
     for var, label in options:
         btn = Checkbutton(frame, anchor="w", variable=var, text=label)
         btn.pack(side="left", fill="both")
         if var.get():
             btn.select()
     return frame, options  # for test
class ProgressListBoxItem(Frame, Observable):
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

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

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

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

    def _model_changed(self):
        self.update()

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

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

    def _user_check_changed(self):
        new_checked = self._checked_var.get()
        if new_checked is not self._model.get_check_status():
            self._model.manual_set_checked(new_checked)
        class CheckField:

            DISABLED = 'disabled'
            NORMAL = 'normal'

            def __init__(self, master=None, text=None, state=0, padding=0):

                self.var = IntVar()
                self.padding = padding
                self.master = master
                self.text = text
                command = lambda name=text: self.check_button_states(name)
                self.button = Checkbutton(master,
                                          command=command,
                                          text=text,
                                          variable=self.var,
                                          onvalue=1,
                                          offvalue=0)
                if state == 1:
                    self.button.select()

            def check_button_states(self, name):

                if self.master.settings_list[3].var.get() == 1:
                    self.master.settings_list[4].button['state'] = self.NORMAL
                    self.master.settings_list[5].button['state'] = self.NORMAL
                    self.master.settings_list[6].button['state'] = self.NORMAL

                    if name == 'solid_fill':
                        self.master.settings_list[5].button.deselect()
                        self.master.settings_list[6].button.deselect()
                    elif name == 'random_fill':
                        self.master.settings_list[4].button.deselect()
                        self.master.settings_list[6].button.deselect()
                    elif name == 'smart_fill':
                        self.master.settings_list[4].button.deselect()
                        self.master.settings_list[5].button.deselect()
                    else:
                        pass

                else:
                    self.master.settings_list[4].button[
                        'state'] = self.DISABLED
                    self.master.settings_list[5].button[
                        'state'] = self.DISABLED
                    self.master.settings_list[6].button[
                        'state'] = self.DISABLED
    def create_option_buttons(self):
        """Return (filled frame, options) for testing.

        Options is a list of SearchEngine booleanvar, label pairs.
        A gridded frame from make_frame is filled with a Checkbutton
        for each pair, bound to the var, with the corresponding label.
        """
        frame = self.make_frame("Options")[0]
        engine = self.engine
        options = [(engine.revar, "Regular expression"), (engine.casevar, "Match case"), (engine.wordvar, "Whole word")]
        if self.needwrapbutton:
            options.append((engine.wrapvar, "Wrap around"))
        for var, label in options:
            btn = Checkbutton(frame, anchor="w", variable=var, text=label)
            btn.pack(side="left", fill="both")
            if var.get():
                btn.select()
        return frame, options
def _makesetting(setting_window, conf):
    setting_label = Label(setting_window,
                          text=_('Setting'),
                          font=('courier', 20, 'bold'))
    setting_label.pack(side=TOP)

    style_container = Frame(setting_window)
    style_container.pack(side=TOP)
    style_label = Label(style_container,
                        text=_('Display wallpaper in style: '),
                        font=('courier', 15, 'bold'))
    style_label.pack(side=LEFT)
    style_combobox = Combobox(style_container)
    available_style = {'3': 'zoom', '2': 'scaled', '1': 'stretched', '0': 'centered', '4': 'wallpaper'}
    style_combobox['value'] = (_('centered'), _('stretched'), _('scaled'), _('zoom'), _('wallpaper'))
    style_combobox.state(['readonly'])
    style_combobox.current(int(conf['style']))
    style_combobox.pack(side=LEFT)

    random_container = Frame(setting_window)
    random_container.pack(side=TOP)
    random_label = Label(random_container,
                         text=_('Choose wallpaper randomly? '),
                         font=('courier', 15, 'bold'))
    random_label.pack(side=LEFT)
    random_checkbutton = Checkbutton(random_container)
    random_checkbutton.pack(side=LEFT)
    if conf['random'] == "1":
        random_checkbutton.select()

    interval_container = Frame(setting_window)
    interval_container.pack(side=TOP)
    interval_label = Label(interval_container,
                           text=_('Change wallpaper every '),
                           font=('courier', 15, 'bold'))
    interval_label.pack(side=LEFT)
    interval_text = Text(interval_container, height=1, width=4)
    interval_text.insert(END, conf['interval'])
    interval_text.pack(side=LEFT)
    minute_label = Label(interval_container,
                         text=_(' minutes.'),
                         font=('courier', 15, 'bold'))
    minute_label.pack(side=LEFT)
Beispiel #20
0
    def create_option_buttons(self):
        '''Return (filled frame, options) for testing.

        Options is a list of SearchEngine booleanvar, label pairs.
        A gridded frame from make_frame is filled with a Checkbutton
        for each pair, bound to the var, with the corresponding label.
        '''
        frame = self.make_frame("Options")[0]
        engine = self.engine
        options = [(engine.revar, "Regular expression"),
                   (engine.casevar, "Match case"),
                   (engine.wordvar, "Whole word")]
        if self.needwrapbutton:
            options.append((engine.wrapvar, "Wrap around"))
        for var, label in options:
            btn = Checkbutton(frame, anchor="w", variable=var, text=label)
            btn.pack(side="left", fill="both")
            if var.get():
                btn.select()
        return frame, options
Beispiel #21
0
    def setup_other(self, frame):
        Label(frame, text="Obstacles & Vehicles").grid(row=0, column=0)
        Label(frame, text="Obstacle: ").grid(row=1, column=0)
        obs_entry = Entry(frame, width=5)
        obs_entry.bind("<KeyRelease>",
                       lambda event: set_obs_chance(obs_entry.get()))
        obs_entry.insert(constants.END, str(ModelConstants.obstacle_chance))
        obs_entry.grid(row=1, column=1)

        Label(frame, text="Vehicle: ").grid(row=2, column=0)
        vehicle_entry = Entry(frame, width=5)
        vehicle_entry.bind("<KeyRelease>", lambda event: set_vehicle_chance(
            vehicle_entry.get()))
        vehicle_entry.insert(constants.END, str(ModelConstants.vehicle_chance))
        vehicle_entry.grid(row=2, column=1)

        Label(frame, text="Show Crumb Trails: ").grid(row=3, column=0)
        crumb_box = Checkbutton(frame, variable=ViewConstants.show_crumbs,
                                fg="black")
        crumb_box.select()
        crumb_box.grid(row=3, column=1)
Beispiel #22
0
    def __init_config(self):
        '''
        Menu中的配置信息
        :return:
        '''
        def confirm_button_click():
            focused_fields = edit_box1.get()
            is_filter = True if cb_isfilter_v.get() else False
            self.__profile.focused_fields = focused_fields
            self.__profile.is_filter = is_filter
            config.Config.store(self.__profile)
            config_window.destroy()

        config_window = Toplevel()
        config_window.title('系统配置')
        config_window.geometry('450x250')
        config_window.resizable(0, 0)

        Label(config_window, text="需要加载的列:").grid(column=0,
                                                  row=0,
                                                  padx=8,
                                                  pady=4)
        edit_box1 = tk.Entry(config_window)
        edit_box1.insert(0, self.__profile.focused_fields)
        edit_box1.grid(column=1, row=0, padx=8, pady=4)

        cb_isfilter_v = IntVar()
        cb_isfilter = Checkbutton(config_window,
                                  text="是否过滤看病、取药的数据",
                                  variable=cb_isfilter_v,
                                  onvalue=1,
                                  offvalue=0)
        cb_isfilter.select()
        cb_isfilter.grid(column=0, row=2, padx=8, pady=4)

        confirm_button = tk.Button(config_window,
                                   text="确定",
                                   command=confirm_button_click)
        confirm_button.grid(column=1, row=3, padx=8, pady=4)
Beispiel #23
0
class FensterRound(Frame):
    def __init__(self, master, controller):
        super().__init__(master)
        self.controller = controller

        self.int_round = StringVar(value=self.controller.int_round)
        self.int_round.trace_add('write', self.callback_int)
        if self.controller.bool_roundActive:
            self.bool_roundActive = BooleanVar(value=1)
        else:
            self.bool_roundActive = BooleanVar(value=0)

        self.grid()
        self.chkb = Checkbutton(master, text="Runden", var=self.bool_roundActive, command=self.callback_chkb)
        self.chkb.grid(row=0, column=0, padx=3, pady=3, sticky="w")
        Label(master, text="Anzahl Nachkommastellen").grid(row=1, column=0, padx=3, pady=3, sticky="w")
        self.entry_round = Entry(master,textvariable=self.int_round, validate="all", validatecommand=self.callback_int, width=5)
        self.entry_round.grid(row=1, column=1, padx=3, pady=3, sticky="e")
        self.init_chkb()
        self.callback_chkb()

    def callback_chkb(self):
        if self.bool_roundActive.get() == 1:
            self.entry_round.config(state="normal")
            self.controller.bool_roundActive = True
        else:
            self.entry_round.config(state="disabled")
            self.controller.bool_roundActive = False

    def callback_int(self, *args):
        if self.int_round.get() != "":
            self.controller.int_round = int(self.int_round.get())

    def init_chkb(self):
        if self.controller.bool_roundActive:
            self.chkb.select()
        else:
            self.chkb.deselect()
Beispiel #24
0
    def selector_popup(self):
        win = Toplevel(self.master)
        win.wm_title("Trash selector")

        j=0    
        i=0

        for item in self.trash_dir_list:
          
            pilImage = PILimage.open(f"trash\\{item}")
            phoImage = ImageTk.PhotoImage(pilImage)
    
            if item in self.trash_remove_list:
                
                #i had a problem using the expression  lambda: self.update_trash_list(item), the problem was that
                #lambda references the memory location of the variable item (i suppose). so we need to bind the item value to a parameter of the lambda.

                cb = Checkbutton(win, image = phoImage,   command=lambda x = item: self.update_trash_list(x))

                cb.select()
                cb.select()
             
            else:
                
                cb = Checkbutton(win, image = phoImage,  command=lambda x = item: self.update_trash_list(x))
        

            #we need to keep a reference of the image, otherwise python garbage collector will make the pictures transparent
            cb.image = phoImage

            cb.grid(row= j, column=i)

            i=i+1
            #with this, each time we pack "x" items, we add one to the row variable 
            if ( i%6 == 5):
                j=j+1
                i=0
class ControlAnnouncement:
    def __init__(self, parent):
        self.announcement = Announcement(
            sorted(list(users.keys()))[0],
            sorted(list(mail.keys()))[0])
        self.initializeGui(parent)

    def initializeGui(self, parent):
        self.parent = parent
        self.frame = Frame(self.parent)
        self.frame.grid(column=0, row=0)

        Label(self.frame, text="User").grid(row=0, sticky=W)
        Label(self.frame, text="Type").grid(row=1, sticky=W)

        userList = sorted(list(users.keys()))
        self.comboBoxUser = Combobox(self.frame,
                                     state="readonly",
                                     width=20,
                                     values=userList)
        self.comboBoxUser.set(userList[0])
        self.comboBoxUser.grid(row=0, column=1, sticky=W)
        self.comboBoxUser.bind('<<ComboboxSelected>>', self.updateUser)

        announcementTypes = sorted(list(mail.keys()))
        self.comboBoxType = Combobox(self.frame,
                                     state="readonly",
                                     width=35,
                                     values=announcementTypes)
        self.comboBoxType.set(announcementTypes[0])
        self.comboBoxType.grid(row=1, column=1, sticky=W)
        self.comboBoxType.bind('<<ComboboxSelected>>', self.updateType)

        self.scolledText = ScrolledText(self.frame,
                                        wrap=WORD,
                                        width=80,
                                        height=15)
        self.scolledText.grid(row=2, column=1, columnspan=2)
        self.scolledText.config(state=NORMAL)
        self.scolledText.insert(INSERT, self.announcement.message.as_string())
        self.scolledText.config(state=DISABLED)

        self.buttonSendTestMail = Button(self.frame,
                                         text='Send Test Mail',
                                         command=self.sendTestMail)
        self.buttonSendTestMail.grid(row=4, column=1)

        self.buttonSendMail = Button(self.frame,
                                     text='Send Mail',
                                     command=self.sendMail)
        self.buttonSendMail.grid(row=4, column=2)

        self.checkButtonAttachmentAvailable = Checkbutton(
            self.frame, text="Attachments available")
        self.checkButtonAttachmentAvailable.grid(row=3, sticky=W)

        self.checkAttachments()

    def checkAttachments(self):
        key = self.announcement.getAttachmentKey()
        print("Info: Attachment key is " + str(key))
        self.checkButtonAttachmentAvailable.config(state=NORMAL)
        if key is None:
            self.checkButtonAttachmentAvailable.deselect()
            self.buttonSendTestMail.config(state=NORMAL)
            self.buttonSendMail.config(state=NORMAL)
        else:
            if not self.announcement.attachmentsMissing():
                self.checkButtonAttachmentAvailable.select()
                self.buttonSendTestMail.config(state=NORMAL)
                self.buttonSendMail.config(state=NORMAL)
            else:
                self.checkButtonAttachmentAvailable.deselect()
                # self.buttonSendTestMail.config(state=DISABLED)
                self.buttonSendMail.config(state=DISABLED)
        self.checkButtonAttachmentAvailable.config(state=DISABLED)

    def updateUser(self, *args):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        self.announcement.setUser(self.comboBoxUser.get())
        self.scolledText.config(state=NORMAL)
        self.scolledText.delete(1.0, END)
        self.scolledText.insert(INSERT, self.announcement.message.as_string())
        self.scolledText.config(state=DISABLED)
        self.checkAttachments()

    def updateType(self, *args):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        self.announcement.setMailType(self.comboBoxType.get())
        self.scolledText.config(state=NORMAL)
        self.scolledText.delete(1.0, END)
        self.scolledText.insert(INSERT, self.announcement.message.as_string())
        self.scolledText.config(state=DISABLED)
        self.checkAttachments()

    def sendTestMail(self):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        self.announcement.sendTestMail()

    def sendMail(self):
        print(__class__.__name__ + "::" + sys._getframe().f_code.co_name)
        pwDialog = PasswordDialog(
            self.frame, title=self.announcement.getFullAddressList()[0])
        # print(pwDialog.result)
        if pwDialog.result:
            self.announcement.attach()
            self.announcement.sendMail(pwDialog.result)
            self.announcement.renderMessage()
Beispiel #26
0
class DemoClient(Frame):
    def __init__(self, tk, args):
        Frame.__init__(self, tk)
        locale.setlocale(locale.LC_ALL,
                         '')  # empty string for platform's default settings
        self.master = tk
        self.config = json.load(open('config.json', 'r'))
        self.config['COMBOBOX_INDEX'] = sorted(self.config['COMBOBOX_INDEX'],
                                               key=lambda x: x[0])
        self.game_type = int(
            args.gametype
        ) if args.gametype else self.config["DEFAULT_GAME_TYPE_ID"]
        tk.title(self.config["APP_TITLE"])
        tk.resizable(False, False)
        self.get_icon()
        atexit.register(self.cancel_game)

        # Init class data fields that we use for storing info that we need for using the API
        self.bot_id = None
        self.bot_password = None
        self.logged_in = False
        self.game_style_ids = []
        self.gameChips = 0
        self.gameDeals = 0
        self.gameStake = 0
        self.gamePrize = 0
        self.player_key = None
        self.play_again = BooleanVar()
        self.do_not_play_same_user = BooleanVar()
        self.close_after_game = False
        self.game_cancelled = False
        self.in_game = False

        self.topFrame = Frame(tk, padx=12, pady=12)
        self.middleFrame = Frame(tk, padx=12)
        self.middleFrameLeft = Frame(self.middleFrame)
        self.middleFrameRight = Frame(self.middleFrame)
        self.middleFrameRighter = Frame(self.middleFrame)

        self.topFrame.grid(row=0, sticky=W + E)

        self.middleFrame.grid(row=1, sticky=W)
        self.middleFrameLeft.grid(row=1, column=0)
        self.middleFrameRight.grid(row=1, column=1)
        self.middleFrameRighter.grid(row=1, column=2)

        # ===================================
        # Create form elements

        # Top Frame Elements
        self.botNameLabel = Label(self.topFrame, text="Bot Name:")
        self.bot_id_entry = Entry(self.topFrame)
        self.bot_id_entry.bind('<Return>', self.log_in_if_not)
        self.bot_id_entry.focus()
        self.passwordLabel = Label(self.topFrame, text="Password:"******"Login",
                                        command=self.log_in_out_clicked)

        self.balanceLabel = Label(self.topFrame, text="Bot Balance:")
        self.balance = Label(self.topFrame, text="0")
        self.close_button = Button(self.topFrame,
                                   text="Close",
                                   padx=2,
                                   command=tk.destroy)

        # Middle Frame Elements
        # Middle Frame LEFT Elements
        self.gameTypeCmb = ttk.Combobox(
            self.middleFrameLeft,
            state="disabled",
            values=tuple((game[0]) for game in self.config['COMBOBOX_INDEX']))
        if self.game_type != self.config['NULL_GAME_TYPE_ID']:
            index = [
                i for i in range(len(self.config['COMBOBOX_INDEX']))
                if self.config['COMBOBOX_INDEX'][i][1] == self.game_type
            ][0]
            self.gameTypeCmb.current(
                index)  # Default selection matches default game type id
        self.gameTypeCmb.bind("<<ComboboxSelected>>", self.game_type_selected)

        self.gameStyleLabel = Label(self.middleFrameLeft,
                                    font=(None, 18),
                                    pady=0,
                                    text="Game Style Selection")

        self.opponentLabel = Label(self.middleFrameLeft,
                                   text="Specify Opponent (optional):")
        self.specify_opponent_cmb = ttk.Combobox(
            self.middleFrameLeft, values=self.config['AVAILABLE_OPPONENTS'])

        self.do_not_play_same_user_check = Checkbutton(
            self.middleFrameLeft,
            text='Don\'t play another bot in same user account as me',
            var=self.do_not_play_same_user)

        self.game_styles_listbox = Listbox(self.middleFrameLeft,
                                           background='#FFFFFF',
                                           height=8)
        self.game_styles_listbox.bind('<Double-1>',
                                      self.find_game_double_clicked)
        self.game_styles_listbox.bind(
            '<Return>', self.find_game_double_clicked
        )  # Not a double click but we want it to do the same thing

        self.refresh_game_styles_button = Button(
            self.middleFrameLeft,
            text="Refresh Game Styles",
            command=self.refresh_game_styles_clicked)

        self.thinkingTimeLabel = Label(self.middleFrameLeft,
                                       text="Add \"Thinking Time\" (ms):")
        self.thinking_time_entry = Entry(self.middleFrameLeft)

        self.auto_play_next_game_check = Checkbutton(
            self.middleFrameLeft,
            text='Play another game when complete',
            var=self.play_again)

        self.cancel_stop_game_button = Button(
            self.middleFrameLeft,
            text=CANCEL_GAME_TEXT,
            command=self.cancel_stop_game_clicked)
        self.find_game_button = Button(self.middleFrameLeft,
                                       text="Find Game",
                                       command=self.find_game_clicked)

        self.resultText = Message(
            self.middleFrameLeft,
            width=300,
            text="This is where the informational messages will appear")
        self.spacerLabel = Label(self.middleFrameLeft, text=" ")

        # Middle Frame RIGHT Elements

        self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title")
        self.gameTitleText = Text(self.middleFrameRight,
                                  height=3,
                                  background='white',
                                  spacing1=3,
                                  pady=0)

        self.player = None  # Initialise as none before updating in create_visuals()
        self.opponent = None  # Initialise as none before updating in create_visuals()
        self.create_visuals()

        self.gameActionLabel = Label(self.middleFrameRight, text="")

        # ===================================
        # Set initial element states

        self.set_gamestyle_controls_states(DISABLED)
        self.cancel_stop_game_button.config(state=DISABLED)
        self.game_styles_listbox.config(background='white')
        self.thinking_time_entry.insert(0, 100)
        self.gameTitleText.config(state=DISABLED)
        self.set_balance(0)
        self.gameTitleText.tag_configure("center", justify='center')
        self.gameTitleText.tag_configure("bold", font='-weight bold')

        # ===================================
        # Form Layout

        # Top Frame Form Layout
        self.topFrame.grid_rowconfigure(0, weight=1)
        self.botNameLabel.grid(row=0, column=0, sticky=E)
        self.bot_id_entry.grid(row=0, column=1, sticky=W)
        self.passwordLabel.grid(row=0, column=2, sticky=E)
        self.bot_password_entry.grid(row=0, column=3, sticky=W)
        self.log_in_out_button.grid(row=0, column=4, sticky=E)
        self.topFrame.grid_columnconfigure(5, weight=1)
        self.balanceLabel.grid(row=0, column=5, sticky=E)
        self.balance.grid(row=0, column=6, sticky=W)
        self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0))

        # Middle Frame Form Layout
        self.middleFrame.grid_rowconfigure(0, weight=1)
        self.gameTypeCmb.grid(row=0, column=0, columnspan=1, sticky=W + E)
        self.gameStyleLabel.grid(row=1, column=0, columnspan=1, sticky=W + E)
        self.spacerLabel.grid(row=1, column=2, sticky=E)

        self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4)
        self.specify_opponent_cmb.grid(row=2, column=0, sticky=E, pady=4)

        self.do_not_play_same_user_check.grid(row=3,
                                              column=0,
                                              columnspan=1,
                                              sticky='we',
                                              pady=4)
        self.game_styles_listbox.grid(row=4,
                                      column=0,
                                      columnspan=1,
                                      sticky='we',
                                      pady=4)
        self.find_game_button.grid(row=5, column=0, pady=4, sticky=W)
        self.refresh_game_styles_button.grid(row=5,
                                             column=0,
                                             columnspan=1,
                                             sticky='',
                                             pady=4)
        self.cancel_stop_game_button.grid(row=5, column=0, sticky=E)

        self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4)
        self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4)

        self.auto_play_next_game_check.grid(row=7,
                                            column=0,
                                            columnspan=1,
                                            sticky=W,
                                            pady=4)
        self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4)
        self.middleFrame.grid_columnconfigure(9, weight=1)

        self.gameTitleLabel.grid(row=0, column=3)
        self.gameTitleText.grid(row=0, column=3, columnspan=2)
        self.gameActionLabel.grid(row=11, column=3, sticky='w')

        if args.botid is not None and args.password is not None:
            self.auto_play(args)

    def auto_play(self, args):
        self.bot_id_entry.insert(0, args.botid)
        self.bot_password_entry.insert(0, args.password)
        self.log_in_out_clicked()
        self.thinking_time_entry.insert(0, args.timeout)
        if args.playanothergame:
            self.auto_play_next_game_check.select()
        if args.dontplaysameuserbot:
            self.do_not_play_same_user_check.select()
        if args.closeaftergame:
            self.close_after_game = True
        if args.gamestyle is not None:
            i = 0
            for i in range(self.game_styles_listbox.size()):
                if args.gamestyle in str(self.game_styles_listbox.get(i)):
                    break
            self.game_styles_listbox.select_set(i, i)
            self.find_game_clicked()

    def log_in_out_clicked(self):
        """Click handler for the 'Login'/'Logout' button."""

        # This means we're logging out
        if self.logged_in:
            self.resultText.config(text='Logged Out')

            self.master.title(self.config["APP_TITLE"] + " (Not Logged In)")

            self.cancel_game()

            self.bot_id = None
            self.bot_password = None
            self.clear_game_title_text()
            self.gameActionLabel.config(text="")
            self.reset_game_styles_listbox()
            self.clear_all_boards()
            self.opponent.delete("all")

            self.log_in_out_button.config(text='Login')

            self.set_login_controls_states(ENABLED)
            self.set_gamestyle_controls_states(DISABLED)
            self.gameTypeCmb.config(state="disabled")

            self.logged_in = False
            self.bot_password_entry.delete(0, 'end')
            self.set_balance(0)

        # This means we're logging in
        else:
            self.bot_id = self.bot_id_entry.get()
            self.bot_password = self.bot_password_entry.get()

            res = self.get_list_of_game_styles()
            if res['Result'] == 'SUCCESS':
                self.resultText.config(text='Logged In')

                game_styles = res['GameStyles']
                self.master.title(self.bot_id + " - " +
                                  self.config["APP_TITLE"])

                self.set_login_controls_states(DISABLED)
                self.set_gamestyle_controls_states(ENABLED)
                self.gameTypeCmb.config(state="readonly")

                self.set_game_styles_listbox(game_styles)
                self.set_balance(res['Balance'])

                self.log_in_out_button.config(text='Logout')

                self.logged_in = True

            else:
                messagebox.showerror(
                    'Error',
                    'Invalid login attempt. Please check the username and password entered.'
                )

    def log_in_if_not(self, _):
        if not self.logged_in:
            self.log_in_out_clicked()

    def clear_all_boards(self):
        self.player.clear_board()
        self.opponent.clear_board()
        self.player.delete("all")
        self.opponent.delete("all")
        self.player.myBoard = None
        self.opponent.oppBoard = None

    def set_in_game(self, value):
        self.in_game = value

    def set_game_title_text(self, text, tag):
        self.gameTitleText.config(state=ENABLED)
        self.gameTitleText.insert("end", text, ("center", tag))
        self.gameTitleText.config(state=DISABLED)

    def clear_game_title_text(self):
        self.gameTitleText.config(state=ENABLED)
        self.gameTitleText.delete("1.0", "end")
        self.gameTitleText.config(state=DISABLED)

    def set_login_controls_states(self, state):
        self.bot_id_entry.config(state=state)
        self.bot_password_entry.config(state=state)

    def set_gamestyle_controls_states(self, state):
        self.specify_opponent_cmb.config(state=state)
        self.do_not_play_same_user_check.config(state=state)
        self.game_styles_listbox.config(state=state)
        self.find_game_button.config(state=state)
        self.refresh_game_styles_button.config(state=state)
        self.auto_play_next_game_check.config(state=state)
        self.thinking_time_entry.config(state=state)
        self.opponentLabel.config(state=state)
        self.thinkingTimeLabel.config(state=state)
        self.balanceLabel.config(state=state)
        self.balance.config(state=state)
        self.gameStyleLabel.config(state=state)
        self.game_styles_listbox.config(state=state)
        self.player.config(state=state)
        self.opponent.config(state=state)

    def set_balance(self, balance):
        """Set the balance field"""
        self.balance['text'] = int_with_commas(balance)

    def get_list_of_game_styles(self):
        """Get list of game styles from the server."""

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'GameTypeId': self.game_type
        }

        url = self.config["BASE_URL"] + self.config[
            "GET_LIST_OF_GAME_STYLES_EXTENSION"]

        return DemoClient.make_api_call(url, req)

    def set_game_styles_listbox(self, game_styles):
        """Set the content of the game styles listbox with a list of GameStyle dictionaries.
        Keyword Arguments:
        game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles().
        """
        self.reset_game_styles_listbox()
        for index, game_style in enumerate(game_styles):
            if self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["BATTLESHIPS_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['Ships'],
                        game_style['GameTypeSpecificInfo']['Board Size'],
                        game_style['GameTypeSpecificInfo']['Timeout ms'],
                        game_style['GameTypeSpecificInfo']['DealsTotal'],
                        game_style['GameTypeSpecificInfo']['PercentageLand'],
                        game_style['GameTypeSpecificInfo']['RandomLand']))
            elif self.game_type == self.config[
                    "NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["NOUGHTS_AND_CROSSES_GAME_STYLE_LISTBOX_TEXT"].
                    format(game_style['GameStyleId'], game_style['Stake'],
                           game_style['GameTypeSpecificInfo']['DealsTotal'],
                           game_style['GameTypeSpecificInfo']['Timeout ms']))
            elif self.game_type == self.config[
                    "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index, self.
                    config["TRAVELLING_SALESDRONE_GAME_STYLE_LISTBOX_TEXT"].
                    format(game_style['GameStyleId'], game_style['Stake'],
                           game_style['GameTypeSpecificInfo']['TotalCities'],
                           game_style['GameTypeSpecificInfo']['DealLength']))
            elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index, self.
                    config["PREDICTIVE_TEXT_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']
                        ['Number of Sentences'],
                        game_style['GameTypeSpecificInfo']
                        ['Switched Words Game'],
                        game_style['GameTypeSpecificInfo']['Timeout ms']))
            elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["TWIST_CUBE_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['cubeSize'],
                        game_style['GameTypeSpecificInfo']['GameLength']))
            elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["SLIDING_PUZZLE_GAME_STYLE_LISTBOX_TEXT"].
                    format(game_style['GameStyleId'], game_style['Stake'],
                           game_style['GameTypeSpecificInfo']['RowSize'],
                           game_style['GameTypeSpecificInfo']['ColumnSize'],
                           game_style['GameTypeSpecificInfo']['TimeLimit']))
            elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["BLURRY_WORD_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['NumImages'],
                        game_style['GameTypeSpecificInfo']['GameLength']))
            elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["MASTERMIND_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['NumPegs'],
                        game_style['GameTypeSpecificInfo']['NumColours'],
                        game_style['GameTypeSpecificInfo']
                        ['DuplicatesAllowed']))
            elif self.game_type == self.config[
                    "WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["WAREHOUSE_LOGISTICS_GAME_STYLE_LISTBOX_TEXT"].
                    format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']
                        ['WarehouseDimensions'][0],
                        game_style['GameTypeSpecificInfo']
                        ['WarehouseDimensions'][1]))
            elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["FOUR_IN_A_ROW_GAME_STYLE_LISTBOX_TEXT"].
                    format(game_style['GameStyleId'], game_style['Stake'],
                           game_style['GameTypeSpecificInfo']['Dimensions'][0],
                           game_style['GameTypeSpecificInfo']['Dimensions'][1],
                           game_style['GameTypeSpecificInfo']['Connections']))
            elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["WHO_IS_WHO_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['NumCharacters'],
                        game_style['GameTypeSpecificInfo']['ComparisonRound']))
            elif self.game_type == self.config[
                    "REVERSING_STONES_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["REVERSING_STONES_GAME_STYLE_LISTBOX_TEXT"].
                    format(game_style['GameStyleId'], game_style['Stake'],
                           game_style['GameTypeSpecificInfo']['Dimensions'][0],
                           game_style['GameTypeSpecificInfo']['Dimensions'][1],
                           game_style['GameTypeSpecificInfo']['Holes'],
                           game_style['GameTypeSpecificInfo']['Timeout ms']))
            elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["CHECKERS_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['Dimensions'][0],
                        game_style['GameTypeSpecificInfo']['Dimensions'][1],
                        game_style['GameTypeSpecificInfo']['Timeout ms']))
            elif self.game_type == self.config["GO_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index, self.config["GO_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['Dimensions'][0],
                        game_style['GameTypeSpecificInfo']['Dimensions'][1],
                        "CAPTURE" if
                        game_style['GameTypeSpecificInfo']['IsCaptureGo'] else
                        game_style['GameTypeSpecificInfo']['ScoringMethod'],
                        game_style['GameTypeSpecificInfo']['Timeout ms']))
            elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["LEXICO_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['Dimensions'][0],
                        game_style['GameTypeSpecificInfo']['Dimensions'][1],
                        game_style['GameTypeSpecificInfo']['TileMultipliers'],
                        game_style['GameTypeSpecificInfo']['Timeout ms']))
            elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]:
                self.game_styles_listbox.insert(
                    index,
                    self.config["DOMINOES_GAME_STYLE_LISTBOX_TEXT"].format(
                        game_style['GameStyleId'], game_style['Stake'],
                        game_style['GameTypeSpecificInfo']['SpotNo'],
                        game_style['GameTypeSpecificInfo']['Timeout ms']))
            else:
                raise ValueError('INVALID GAME TYPE PARAMETER')

            self.game_style_ids.append(game_style['GameStyleId'])
            # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION)

    def reset_game_styles_listbox(self):
        """Clear the content of the game styles listbox."""

        if self.game_styles_listbox.size() != 0:
            self.game_styles_listbox.delete(0, 'end')

            self.game_style_ids = []

    def refresh_game_styles_clicked(self):
        """Click handler for the 'Refresh Game Styles' button."""

        res = self.get_list_of_game_styles()
        game_styles = res['GameStyles']
        self.set_game_styles_listbox(game_styles)

    def find_game_clicked(self):
        """Click handler for the 'Find Game' button"""

        self.find_game_button.config(state=DISABLED)
        self.cancel_stop_game_button.config(state=ENABLED)
        self.game_styles_listbox.unbind('<Double-1>')
        self.game_styles_listbox.unbind('<Return>')
        self.game_styles_listbox.config(state=DISABLED)
        self.clear_all_boards()

        # Here we dispatch the work to a separate thread, to keep the GUI responsive.
        if not MAC:
            threading.Thread(target=self.game_loop, daemon=True).start()
        else:
            self.game_loop()  # Doesn't work on MACs

    def find_game_double_clicked(self, _):
        self.find_game_clicked()

    def game_type_selected(self, _):
        self.game_type = self.config["COMBOBOX_INDEX"][
            self.gameTypeCmb.current()][1]
        res = self.get_list_of_game_styles()
        if res['Result'] == 'SUCCESS':
            game_styles = res['GameStyles']
            self.set_game_styles_listbox(game_styles)
            self.get_icon()
            self.player.destroy()
            self.opponent.destroy()
            self.create_visuals()

    def get_icon(self):
        try:
            if WINDOWS:
                self.master.iconbitmap("assets/{0}/icon.ico".format(
                    self.game_type))
            else:
                self.master.iconbitmap("./assets/{0}/icon.xbm".format(
                    self.game_type))
        except Exception as e:
            print(e)

    def create_visuals(self):
        if self.game_type == self.config["NULL_GAME_TYPE_ID"]:
            self.player = null_visuals.NullVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = null_visuals.NullVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]:
            self.player = battleships_visuals.BattleshipsVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = battleships_visuals.BattleshipsVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]:
            self.player = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config[
                "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]:
            self.player = travelling_salesdrone_visuals.TravellingSalesdroneVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = travelling_salesdrone_visuals.TravellingSalesdroneVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]:
            self.player = predictive_text_visuals.PredictiveTextVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = predictive_text_visuals.PredictiveTextVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]:
            self.player = twist_cube_visuals.TwistCubeVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = twist_cube_visuals.TwistCubeVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]:
            self.player = sliding_puzzle_visuals.SlidingPuzzleVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = sliding_puzzle_visuals.SlidingPuzzleVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]:
            self.player = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]:
            self.player = mastermind_visuals.MastermindVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = mastermind_visuals.MastermindVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]:
            self.player = warehouse_logistics_visuals.WarehouseLogisticsVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = warehouse_logistics_visuals.WarehouseLogisticsVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]:
            self.player = four_in_a_row_visuals.FourInARowVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = four_in_a_row_visuals.FourInARowVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]:
            self.player = who_is_who_visuals.WhoIsWhoVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = who_is_who_visuals.WhoIsWhoVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["REVERSING_STONES_GAME_TYPE_ID"]:
            self.player = reversing_stones_visuals.ReversingStonesVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = reversing_stones_visuals.ReversingStonesVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]:
            self.player = checkers_visuals.CheckersVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = checkers_visuals.CheckersVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["GO_GAME_TYPE_ID"]:
            self.player = go_visuals.GoVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = go_visuals.GoVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]:
            self.player = lexico_visuals.LexicoVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = lexico_visuals.LexicoVisuals(
                self.middleFrameRight)  # Game Display Table
        elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]:
            self.player = dominoes_visuals.DominoesVisuals(
                self.middleFrameRight)  # Game Display Table
            self.opponent = dominoes_visuals.DominoesVisuals(
                self.middleFrameRight)  # Game Display Table
        else:
            raise ValueError('INVALID GAME TYPE PARAMETER')
        self.player.grid(row=1, column=3)
        self.opponent.grid(row=1, column=4)

    def game_loop(self):
        """Loop through finding and playing games."""

        while True:
            self.clear_all_boards()
            mover.persistentData = {}
            self.find_game()
            self.update_balance()
            if self.game_cancelled:
                break
            self.play_game()
            self.update_balance()
            if self.close_after_game:
                self.close_button.invoke()
            if self.game_cancelled:
                break
            if not self.play_again.get():
                break

        self.find_game_button.config(state=ENABLED)
        self.cancel_stop_game_button.config(state=DISABLED,
                                            text=CANCEL_GAME_TEXT)
        self.game_styles_listbox.bind('<Double-1>',
                                      self.find_game_double_clicked)
        self.game_styles_listbox.bind('<Return>',
                                      self.find_game_double_clicked)
        self.game_styles_listbox.config(state=ENABLED)
        self.game_cancelled = False

    def find_game(self):
        """Find a game."""

        offer_game_res = self.offer_game()

        if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD':
            self.cancel_stop_game_clicked()
            if 'ErrorMessage' in offer_game_res and offer_game_res[
                    'ErrorMessage'] == 'Check of OpponentId failed':
                self.resultText.config(text='Invalid Opponent ID')
            else:
                self.resultText.config(text='Invalid login or password')
        elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE':
            self.cancel_stop_game_clicked()
            self.resultText.config(text='Insufficient balance')
        elif offer_game_res['Result'] == 'BOT_IS_INACTIVE':
            self.cancel_stop_game_clicked()
            self.resultText.config(text='Bot is inactive')
        else:
            self.player_key = offer_game_res['PlayerKey']
            if offer_game_res['Result'] == 'WAITING_FOR_GAME':
                self.wait_for_game()

    def offer_game(self):
        """Offer a game."""

        self.cancel_game(
        )  # Cancel the last outstanding game offer that was made

        opponent_id = self.specify_opponent_cmb.get()
        if len(opponent_id) == 0:
            opponent_id = None
        try:
            game_style_id = self.game_style_ids[int(
                self.game_styles_listbox.curselection()[0])]
        except IndexError:
            self.game_styles_listbox.select_set(
                GAME_STYLE_LISTBOX_DEFAULT_SELECTION)
            game_style_id = self.game_style_ids[0]

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'MaximumWaitTime': 1000,
            'GameStyleId': game_style_id,
            'DontPlayAgainstSameUser': self.do_not_play_same_user.get(),
            'DontPlayAgainstSameBot': False,
            'OpponentId': opponent_id
        }
        url = self.config["BASE_URL"] + self.config["OFFER_GAME_EXTENSION"]

        return DemoClient.make_api_call(url, req)

    def wait_for_game(self):
        """Wait for game to start."""
        self.resultText.config(text='Waiting for game')
        while True:
            if self.game_cancelled:
                self.cancel_game()
                self.find_game_button.config(state=ENABLED)
                self.cancel_stop_game_button.config(state=DISABLED,
                                                    text=CANCEL_GAME_TEXT)
                self.game_styles_listbox.bind('<Double-1>',
                                              self.find_game_double_clicked)
                self.game_styles_listbox.bind('<Return>',
                                              self.find_game_double_clicked)
                self.game_styles_listbox.config(state=ENABLED)
                break
            poll_results = self.poll_for_game_state()

            if poll_results['Result'] == 'SUCCESS':
                break
            if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[
                    'Result'] == 'GAME_HAS_ENDED' or poll_results[
                        'Result'] == 'GAME_WAS_STOPPED':
                self.game_cancelled = True
            time.sleep(2)

    def play_game(self):
        """Play a game."""
        self.resultText.config(text='Playing game')
        self.in_game = True

        poll_results = self.poll_for_game_state()

        if poll_results["Result"] != "SUCCESS":
            return

        game_state = poll_results['GameState']

        title = format('Game ID: ' + str(game_state['GameId']))
        title += format(' / Style: ' + str(self.game_style_ids[int(
            self.game_styles_listbox.curselection()[0])]))
        title += "\n"
        versus = format(self.bot_id + ' vs ' + game_state['OpponentId'])

        self.clear_game_title_text()
        self.set_game_title_text(title, "")
        self.set_game_title_text(versus, "bold")

        self.middleFrame.update()

        while True:
            if self.game_cancelled:
                break

            if game_state['IsMover']:
                self.resultText.config(text='Playing Game - Your Turn')
                move = mover.calculate_move(self.game_type, game_state)
                move_results = self.make_move(move)

                if move_results['Result'] == 'INVALID_MOVE':
                    self.resultText.config(text="Invalid Move")
                elif move_results['Result'] != 'SUCCESS':
                    self.resultText.config(text='Game has ended: ' +
                                           move_results['Result'])
                    print(str(move_results))
                    print("Game ended")
                    break
                else:
                    game_state = move_results['GameState']
            else:
                self.resultText.config(text="Playing Game - Opponent's Turn")

                # ---- Code here will be called on your opponent's turn ----

                # ----------------------------------------------------------

                poll_results = self.poll_for_game_state()

                if poll_results['Result'] != 'SUCCESS':
                    self.resultText.config(text='Game has ended: ' +
                                           poll_results['Result'])
                    break
                game_state = poll_results['GameState']

            if game_state['GameStatus'] != 'RUNNING':
                break

            self.middleFrameRight.update()

            try:
                if int(self.thinking_time_entry.get()) > 0:
                    time.sleep((int(self.thinking_time_entry.get()) / 1000))
                else:
                    time.sleep(0.1)
            except ValueError:
                time.sleep(0.1)

        self.set_in_game(False)

    def make_move(self, move):
        """Make a move."""

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'PlayerKey': self.player_key,
            'Move': move
        }
        url = self.config["BASE_URL"] + self.config["MAKE_MOVE_EXTENSION"]

        result = DemoClient.make_api_call(url, req)

        if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[
                'Result']:
            print(result)
            try:
                self.player.draw_game_state(result['GameState'], True)
                self.opponent.draw_game_state(result['GameState'], False)
            except Exception as e:
                print("Gamestate error: " + str(e))

        return result

    def poll_for_game_state(self):
        """Poll the server for the latest GameState."""

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'MaximumWaitTime': 1000,
            'PlayerKey': self.player_key
        }
        url = self.config["BASE_URL"] + self.config[
            "POLL_FOR_GAME_STATE_EXTENSION"]

        result = DemoClient.make_api_call(url, req)
        if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[
                'Result']:
            self.player.draw_game_state(result['GameState'], True)
            self.opponent.draw_game_state(result['GameState'], False)

        return result

    def cancel_stop_game_clicked(self):
        self.game_cancelled = True
        self.cancel_game()
        self.find_game_button.config(state=ENABLED)
        self.cancel_stop_game_button.config(state=DISABLED,
                                            text=CANCEL_GAME_TEXT)
        self.game_styles_listbox.bind('<Double-1>',
                                      self.find_game_double_clicked)
        self.game_styles_listbox.bind('<Return>',
                                      self.find_game_double_clicked)
        self.game_styles_listbox.config(state=ENABLED)

    def cancel_game(self):
        print("Cancelling last game offer")
        if self.player_key is None:
            return
        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'PlayerKey': self.player_key
        }

        url = self.config["BASE_URL"] + self.config[
            "CANCEL_GAME_OFFER_EXTENSION"]
        DemoClient.make_api_call(url, req)
        try:
            self.resultText.config(text='Cancelled game')
        except Exception as e:
            print(str(e) + " -- Demo client has been closed")

    def update_balance(self):
        res = self.get_list_of_game_styles()
        self.set_balance(res['Balance'])

    @staticmethod
    def make_api_call(url, req):
        """Make an API call."""
        while True:
            try:
                res = requests.post(url,
                                    json=req,
                                    headers=API_CALL_HEADERS,
                                    timeout=60.0)
                try:
                    jres = res.json()
                    if 'Result' in jres:
                        return jres
                    time.sleep(0.1)
                except ValueError:
                    time.sleep(0.1)
            except requests.ConnectionError:
                time.sleep(0.1)
            except requests.Timeout:
                time.sleep(0.1)
            except requests.HTTPError:
                time.sleep(0.1)
            except BaseException as e:  # Bad code but needed for testing purposes
                print(e)
                time.sleep(0.1)
Beispiel #27
0
else:
    opcije="0|||".split("|")
#else:
#    os.makedirs("C:\\EOP")
#    opcije="0||".split("|")
    



t.title('EOP')
t.config(bg='green',width = 300,height = 600)

c1=Checkbutton(t,text="Remember me",variable=remember,bg='lightblue',activebackground="blue")
c1.place(x=105,y=450)
if opcije[0]=="1":
    c1.select()

l1=Label(t,text="REGISTER TO EOP",font=("Verdana",18),bg='pink')
l1.place(x=40,y=1)

l2=Label(t,text="USERNAME:"******"E-MAIL:",bg='pink')
l3.place(x=5,y=100)
l4=Label(t,text="PASSWORD:"******"*",textvariable=StringVar(t, value=''))
Beispiel #28
0
class GUI:
    def PrintException(self):
        exc_type, exc_obj, tb = sys.exc_info()
        f = tb.tb_frame
        lineno = tb.tb_lineno
        filename = f.f_code.co_filename
        linecache.checkcache(filename)
        line = linecache.getline(filename, lineno, f.f_globals)
        print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(
            filename, lineno, line.strip(), exc_obj))

    def __init__(self, master, EM, sim_results):
        try:
            # Initialize plotting figures variables etc
            self.fig = plt.figure(1)
            self.fig2 = plt.figure(2)
            self.ax = self.fig.gca(projection='3d')
            # self.ax = plt.axes(projection='3d') #self.fig.add_subplot(111, projection='3d')

        except BaseException as e:
            self.PrintException()

#Initialize EnvironmentManipulator
        self.EM = EM
        self.EM.setValue(1.0)
        # SImulation results
        self.sim_results = sim_results
        #Import Optimizer Alogorithm Class
        self.opt = Optimizer()
        #GUI INIT
        self.master = master
        master.title("Lotus Test Platform")

        #INITIAL STATE OF TRAJECTORY WIDGETS
        self.label_initial = Label(master, text="Initial State of Trajectory")
        self.label_initial.grid(row=0, column=0, columnspan=2)

        self.label_initial_position = Label(master, text="Position")
        self.label_initial_position.grid(row=1, column=0, columnspan=2)
        self.label_initial_position.justify = "center"

        self.label_x = Label(master, text="X:")
        self.label_x.grid(row=2, column=0)

        self.label_y = Label(master, text="Y:")
        self.label_y.grid(row=3, column=0)

        self.entry_initial_x = Entry(
            master)  #, validate = 'key', validatecommand = vcmd)
        self.entry_initial_x.grid(row=2, column=1)
        self.entry_initial_x.insert(0, "-2000")

        self.entry_initial_y = Entry(master)
        self.entry_initial_y.grid(row=3, column=1)
        self.entry_initial_y.insert(0, "-1000")

        self.label_initial_velocity = Label(master, text="Velocity")
        self.label_initial_velocity.grid(row=4, column=0, columnspan=2)
        self.label_initial_velocity.justify = "center"

        self.label_vmag = Label(master, text="V_Magnitude:")
        self.label_vmag.grid(row=5, column=0)

        # self.label_vy = Label(master, text="Y:")
        # self.label_vy.grid(row=6, column=0)

        self.entry_initial_vmag = Entry(
            master)  #, validate = 'key', validatecommand = vcmd)
        self.entry_initial_vmag.grid(row=5, column=1)
        self.entry_initial_vmag.insert(0, "0")

        # self.entry_initial_vy = Entry(master)
        # self.entry_initial_vy.grid(row=6, column=1)
        # self.entry_initial_vy.insert(0, "500")

        self.label_initial_yaw = Label(master, text="Yaw")
        self.label_initial_yaw.grid(row=7, column=0)

        self.entry_initial_yaw = Entry(master)
        self.entry_initial_yaw.grid(row=7, column=1)
        self.entry_initial_yaw.insert(0, str(np.pi / 2))

        self.label_initial_omega = Label(master, text="Omega(yaw rate)")
        self.label_initial_omega.grid(row=8, column=0)

        self.entry_initial_omega = Entry(master)
        self.entry_initial_omega.grid(row=8, column=1)
        self.entry_initial_omega.insert(0, "0")

        # FINAL STATE OF TRAJECTORY WUIDGETS
        self.label_final = Label(master, text="Final State of Trajectory")
        self.label_final.grid(row=0, column=2, columnspan=2)

        self.label_final_position = Label(master, text="Position")
        self.label_final_position.grid(row=1, column=2, columnspan=2)
        self.label_final_position.justify = "center"

        self.label_final_x = Label(master, text="X:")
        self.label_final_x.grid(row=2, column=2)

        self.label_final_y = Label(master, text="Y:")
        self.label_final_y.grid(row=3, column=2)

        self.entry_final_x = Entry(
            master)  #, validate = 'key', validatecommand = vcmd)
        self.entry_final_x.grid(row=2, column=3)
        self.entry_final_x.insert(0, "0")

        self.entry_final_y = Entry(master)
        self.entry_final_y.grid(row=3, column=3)
        self.entry_final_y.insert(0, "0")

        self.label_final_velocity = Label(master, text="Velocity")
        self.label_final_velocity.grid(row=4, column=2, columnspan=2)
        self.label_final_velocity.justify = "center"

        self.label_final_vx = Label(master, text="X:")
        self.label_final_vx.grid(row=5, column=2)

        self.label_final_vy = Label(master, text="Y:")
        self.label_final_vy.grid(row=6, column=2)

        self.entry_final_vx = Entry(
            master)  #, validate = 'key', validatecommand = vcmd)
        self.entry_final_vx.grid(row=5, column=3)
        self.entry_final_vx.insert(0, "0")

        self.entry_final_vy = Entry(master)
        self.entry_final_vy.grid(row=6, column=3)
        self.entry_final_vy.insert(0, "0")

        self.label_final_yaw = Label(master, text="Yaw")
        self.label_final_yaw.grid(row=7, column=2)

        self.entry_final_yaw = Entry(master)
        self.entry_final_yaw.grid(row=7, column=3)
        self.entry_final_yaw.insert(0, "0")

        #GENERATE TRAJECTORY BUTTONS
        self.label_trajectory_generation = Label(master,
                                                 text="Trajectory Generation")
        self.label_trajectory_generation.grid(row=9, column=0, columnspan=2)
        self.label_trajectory_generation.justify = "center"

        self.button_generate_trajectory_minimum_time = Button(
            master, text="Min Time", command=lambda: self.getTrajectory())
        self.button_generate_trajectory_minimum_time.grid(row=10, column=0)

        # Save sim data checkbox
        self.cb_save_simulation = Checkbutton(master, text="Save Sim Data")
        self.cb_save_simulation.grid(row=9, column=10)
        self.cb_save_simulation.select(
        )  # Make checkbutton checked when gui starts

        #RUN TRAJECTORY BUTTON
        #RUN treatment button
        self.button_run = Button(master,
                                 text="RUN TRAJECTORY",
                                 command=lambda: self.runTrajectory())
        self.button_run.grid(row=10, column=10)

        #PLOT TRAJECTORY BUTTON
        self.button_plot = Button(master,
                                  text="PLOT TRAJECTORY DATA",
                                  command=lambda: self.plotTrajectory())
        self.button_plot.grid(row=10, column=11)
        #PLOT SIMULATION RESULTS BUTTON
        self.button_plot_sim_results = Button(
            master,
            text="PLOT SIM RESULTS",
            command=lambda: self.plotSimulationResults())
        self.button_plot_sim_results.grid(row=9, column=11)
        #REAL TIME OF TRAJECTORY
        self.label_t0_name = Label(master, text="t0")
        self.label_t0_name.grid(row=9, column=3, columnspan=2)

        self.label_t0 = Label(master, text="0.0")
        self.label_t0.grid(row=10, column=3)

        self.label_tnow_name = Label(master, text=":::::t_now:::::")
        self.label_tnow_name.grid(row=9, column=5, columnspan=4)

        self.label_tnow = Label(master, text="0.0")
        self.label_tnow.grid(row=10, column=5, columnspan=4)
        self.label_tnow.justify = "center"

        #DISPLAY OPTIMATL TRAJECTORY DATA
        self.label_trajectory_data = Label(
            master,
            text=
            "---------------------------------------------------------------------Trajectory Data---------------------------------------------------------------------"
        )
        self.label_trajectory_data.grid(row=11, column=0, columnspan=15)
        self.label_trajectory_data.justfy = "center"

        self.text_trajectory_data = Text(master)
        self.text_trajectory_data.grid(row=12,
                                       column=0,
                                       columnspan=15,
                                       sticky='nsew',
                                       ipady=100)

        #Scroll bar for trajectory data
        # scrollb = Scrollbar(self.text_trajectory_data, command=self.text_trajectory_data.yview, orient='vertical')
        # scrollb.grid(row=11, column=11, sticky='nsew')
        # self.text_trajectory_data['yscrollcommand']=scrollb.set

        # WAYPOINT PLACEMENT IMAGE AND MOVEABLE SHAPES
        self.canvas_waypoint = tk.Canvas(master,
                                         width=580,
                                         height=700,
                                         background='gray')
        self.canvas_waypoint.grid(row=1,
                                  column=15,
                                  columnspan=5,
                                  rowspan=15,
                                  sticky='nwe')
        self.field = PhotoImage(
            file=
            'D:\Documents\RLBot\RLBotPythonExample-master\Lotus\RL_Field.png')
        self.canvas_waypoint.create_image(0, 0, image=self.field, anchor=NW)
        # WAYPOINT CIRCLES
        self.waypoint_size = 25
        self.waypoint_position_x = [
            150, 300, 300, 150
        ]  # Position of the waypoint shapes in canvas
        self.waypoint_position_y = [150, 150, 300, 300]
        self.waypoint_shape = []
        self.waypoint_text = []

        #Create the 4 way points in their default positions
        for i in range(len(self.waypoint_position_x)):
            x = self.canvas_waypoint.create_oval(
                self.waypoint_position_x[i],
                self.waypoint_position_y[i],
                self.waypoint_position_x[i] + self.waypoint_size,
                self.waypoint_position_y[i] + self.waypoint_size,
                outline='black',
                fill='green')
            self.waypoint_shape.append(x)
            y = self.canvas_waypoint.create_text(
                self.waypoint_position_x[i] + 4,
                self.waypoint_position_y[i] + 4,
                anchor=NW,
                font=("Purisa", 10, 'bold'),
                text="W" + str(i + 1),
                fill='white')
            self.waypoint_text.append(y)
        print(self.waypoint_shape)

        #Bind left mousebutton click to update position of way point
        self.canvas_waypoint.bind("<ButtonRelease-1>", self.move_waypoint)

        #Bind mouse entering canvas to give it keyboard focus
        self.canvas_waypoint.bind(
            "<Enter>", lambda event: self.canvas_waypoint.focus_set())

        #Bind keyboard buttons 1234 to change the "state" of the editing feature. Number you press changes which waypoint you will change
        self.canvas_waypoint.bind("0", self.set_editing_state)
        self.canvas_waypoint.bind("1", self.set_editing_state)
        self.canvas_waypoint.bind("2", self.set_editing_state)
        self.canvas_waypoint.bind("3", self.set_editing_state)
        self.canvas_waypoint.bind("4", self.set_editing_state)
        self.current_waypoint = 0  # Current waypoint that events will affect

    def move_waypoint(self, event):
        try:

            bbox = np.array(
                self.canvas_waypoint.coords(self.waypoint_shape[
                    self.current_waypoint]))  #Get bounding box of shape
            print(bbox)
            init = self.get_center_of_shape(
                bbox)  #Get center positoin vector of shape from bounding box
            new = np.array([event.x, event.y])  # Get mouse position
            final = new - init  # Find deltas
            self.canvas_waypoint.move(
                self.waypoint_shape[self.current_waypoint], final[0],
                final[1])  #Move shape by delta
            self.canvas_waypoint.move(
                self.waypoint_text[self.current_waypoint], final[0],
                final[1])  #Move shape by delta
        except BaseException as e:
            self.PrintException()

    def set_editing_state(self, event):
        self.current_waypoint = int(event.char) - 1
        print(self.current_waypoint)

    def get_center_of_shape(self, bbox):  #bbox is bounding box (x1,y1,x2,y2)
        position = np.array(
            [int((bbox[0] + bbox[2]) / 2),
             int((bbox[1] + bbox[3]) / 2)])
        return position

    def compartmentalizeData(self):
        try:
            s_ti = [
                float(self.entry_initial_x.get()),
                float(self.entry_initial_y.get())
            ]
            s_tf = [
                float(self.entry_final_x.get()),
                float(self.entry_final_y.get())
            ]
            v_ti = float(self.entry_initial_vmag.get())
            v_tf = [
                float(self.entry_final_vx.get()),
                float(self.entry_final_vy.get())
            ]
            r_ti = float(self.entry_initial_yaw.get())
            omega_ti = [float(self.entry_initial_omega.get())]

            return s_ti, s_tf, v_ti, v_tf, r_ti, omega_ti

        except Exception as e:
            print(e)

    def getTrajectory(self):
        try:
            s_ti, s_tf, v_ti, v_tf, r_ti, omega_ti = self.compartmentalizeData(
            )

            self.opt.__init__(
            )  #Reset initial conditions and all variables to allow a clean simulation
            acceleration, yaw, t_star = self.opt.optimize2D(
                s_ti, s_tf, v_ti, v_tf, r_ti,
                omega_ti)  #Run the driving optimization algorithm

            print("t_star", t_star, "acceleration", acceleration.value, "yaw",
                  yaw.value)
            string = "\n--------------------------------------------------" + \
                str("\nt_star: ") + str(t_star)+"\nacceleration: "+ str(acceleration.value)+ "\nyaw: "+ str(yaw.value) + "\nturning: " + str(self.opt.u_turning_d.value)
            self.text_trajectory_data.insert('1.end', string)

            return t_star, acceleration, self.opt.u_turning_d.value

        except Exception as e:
            print(e)
            print('An entry is invalid')

    def plotSimulationResults(self):
        try:
            if 'self.ax' not in locals(
            ):  # create self.ax becuase it throws an error when in the __init__() function, b/c of threads?
                # self.ax = self.fig.add_subplot(111, projection='3d')
                self.ax = self.fig.gca(projection='3d')

            ts = self.sim_results.ts
            ts_a = np.array(
                self.sim_results.t_now[2:-1]) - self.sim_results.t_now[2]

            # Switch to right figure
            plt.figure(1)
            self.ax.clear()
            # Plot reference trajectory vs time
            Axes3D.plot(self.ax,
                        self.sim_results.sx,
                        self.sim_results.sy,
                        ts,
                        c='r',
                        marker='o')
            plt.ylabel('Position/Velocity y')
            plt.xlabel('Position/Velocity x')
            self.ax.set_zlabel('time')

            # Plot actual trajectory vs time
            Axes3D.plot(self.ax,
                        self.sim_results.sx_a[2:-1],
                        self.sim_results.sy_a[2:-1],
                        ts_a,
                        c='b',
                        marker='.')

            plt.figure(2)
            plt.clf()
            plt.subplot(3, 1, 1)
            plt.plot(ts, self.sim_results.vx, 'r-')
            # plt.ylabel('acceleration')

            plt.subplot(3, 1, 1)
            plt.plot(ts_a, self.sim_results.vx_a[2:-1], 'b-')
            plt.ylabel('vx error')

            # Get v_mag and v_mag_a
            v_mag = np.sqrt(
                np.multiply(self.sim_results.vx, self.sim_results.vx) +
                np.multiply(self.sim_results.vy, self.sim_results.vy))
            v_mag_a = np.sqrt(
                np.multiply(self.sim_results.vx_a, self.sim_results.vx_a) +
                np.multiply(self.sim_results.vy_a, self.sim_results.vy_a))

            plt.subplot(3, 1, 3)
            plt.plot(ts, v_mag, 'b-')
            plt.ylabel('vmag')
            plt.subplot(3, 1, 3)
            plt.plot(ts_a, v_mag_a[2:-1], 'g-')
            plt.ylabel('vmag')

            plt.ion()
            plt.show()
            plt.pause(0.001)
        except BaseException as e:
            self.PrintException()

    def plotTrajectory(self):
        try:
            print("printing trajectory?")
            ts = self.opt.d.time * self.opt.tf.value[0]

            # Switch to right figure
            self.fig

            # plt.subplot(2, 1, 1)
            Axes3D.plot(self.ax,
                        self.opt.sx.value,
                        self.opt.sy.value,
                        ts,
                        c='r',
                        marker='o')
            plt.ylabel('Position/Velocity y')
            plt.xlabel('Position/Velocity x')
            self.ax.set_zlabel('time')

            # fig = plt.figure(3)
            # self.ax = fig.add_subplot(111, projection='3d')
            # plt.subplot(2, 1, 1)
            Axes3D.plot(self.ax,
                        self.opt.vx.value,
                        self.opt.vy.value,
                        ts,
                        c='b',
                        marker='.')

            self.fig2
            plt.clf()
            plt.subplot(3, 1, 1)
            plt.plot(ts, self.opt.a, 'r-')
            plt.ylabel('acceleration')

            plt.subplot(3, 1, 2)
            plt.plot(ts, np.multiply(self.opt.yaw, 180 / math.pi), 'r-')
            plt.ylabel('turning input')

            plt.subplot(3, 1, 3)
            plt.plot(ts, self.opt.v_mag, 'b-')
            plt.ylabel('vmag')

            plt.ion()
            plt.show()
            plt.pause(0.001)

        except Exception as e:
            self.PrintException()

    def runTrajectory(self):
        #Set EnvironmentManipulator initial car and ball states
        b = self.createBallStateFromGUI(
        )  # BallStateEnumeration().ballStateHigh
        c = self.createCarStateFromGUI()
        self.EM.setInitialStates(c, b)
        self.EM.startTrajectory()

    def getTrajectoryData(self):
        # Trajectory Data Types
        ts = self.opt.d.time * self.opt.tf.value[0]  # Get the time vector
        print("ts: ", ts)
        print(type(ts))
        sx = self.opt.sx
        sy = self.opt.sy
        vx = self.opt.vx
        vy = self.opt.vy
        yaw = self.opt.yaw
        omega = self.opt.omega
        curvature = self.opt.curvature

        return ts, sx, sy, vx, vy, yaw, omega, curvature

    def getInputData(self):
        return self.opt.a, self.opt.u_turning_d

    def createCarStateFromGUI(self):
        x = float(self.entry_initial_x.get())
        y = float(self.entry_initial_y.get())
        vmag = float(self.entry_initial_vmag.get())
        r = float(self.entry_initial_yaw.get())
        omega = float(self.entry_initial_omega.get())

        # get x y velocities
        vx = np.cos(r) * vmag
        vy = np.sin(r) * vmag

        carState = CarState(boost_amount=100,
                            physics=Physics(location=Vector3(x, y, 17.01),
                                            velocity=Vector3(vx, vy, 0),
                                            rotation=Rotator(pitch=0,
                                                             yaw=r,
                                                             roll=0),
                                            angular_velocity=Vector3(
                                                0, 0, omega)))

        return carState

    def createBallStateFromGUI(self):
        x = float(self.entry_final_x.get())
        y = float(self.entry_final_y.get())
        ballState = BallState(
            Physics(location=Vector3(x, y, 1000), velocity=Vector3(0, 0, 0)))

        return ballState
Beispiel #29
0
    def make_changable(self, name, row_id, kind='text', preVals=None):

        relation = StringVar()
        pattern = StringVar()
        change = StringVar()
        changeTo = StringVar()

        relMenu = OptionMenu(self.diagFrame, relation,
                             *StringComparison.options)
        relMenu.grid(row=row_id, column=1, sticky=W)

        patEntry = Entry(self.diagFrame, textvariable=pattern)
        patEntry.grid(row=row_id, column=2, sticky=W)

        if self.entry and hasattr(self.entry, name):
            inString = getattr(self.entry, name)
        else:
            inString = ''
        chMenu = OptionMenu(self.diagFrame,
                            change,
                            *StringModification.options,
                            command=self.possibleDialog(changeTo, inString))
        chMenu.grid(row=row_id, column=3, sticky=W)

        if name == 'account':
            chVal = CustomMenubutton(self.diagFrame,
                                     self.ledger,
                                     self.entry,
                                     textvariable=changeTo,
                                     indicatoron=True)
        else:
            chVal = Entry(self.diagFrame, textvariable=changeTo)
        chVal.grid(row=row_id, column=4, sticky=W)

        settableItems = [relMenu, patEntry, chMenu, chVal]
        checkVar = IntVar()
        command = self.getCheckcommand(checkVar, settableItems)
        label = Checkbutton(self.diagFrame,
                            text=name.title(),
                            variable=checkVar,
                            onvalue=True,
                            offvalue=False,
                            command=command)
        label.grid(row=row_id, column=0, sticky=E + W)

        if not preVals:
            label.deselect()
        else:
            if not preVals['pattern']:
                label.deselect()
            else:
                label.select()
        command()

        if preVals:
            if 'relation' in preVals:
                relation.set(preVals['relation'])
            if 'pattern' in preVals:
                pattern.set(preVals['pattern'])
            if 'change' in preVals:
                change.set(preVals['change'])
            if 'changeTo' in preVals:
                changeTo.set(preVals['changeTo'])

        return checkVar, relation, pattern, change, changeTo
Beispiel #30
0
cl5.grid(row=5, column=0, padx=0, pady=(10, 5), sticky=E)

c1.grid(row=1, column=1, padx=(0, 5), pady=(0, 5), sticky=W)
c2.grid(row=2, column=1, padx=(0, 5), pady=(0, 5), sticky=W)
c3.grid(row=3, column=1, padx=0, pady=(0, 5), sticky=W)
c4.grid(row=4, column=1, padx=0, pady=(0, 5), sticky=W)
c5.grid(row=5, column=1, padx=(0, 5), pady=(10, 5), sticky=W)

l2.grid(row=6, column=0, padx=(10, 0), pady=(10, 10), sticky=E)
e1.grid(row=6, column=1, padx=(0, 5), pady=(10, 10), sticky=W)
but.grid(row=7, column=0, columnspan=3, pady=(0, 10))
top.wm_title("Passwort-Generator")

e1.bind("<Return>", fkt)
# e2.bind("<Return>",fkt)
c5.select()
c5fkt()
t1.set('12')
e1.focus()
e1.selection_range(0, END)
e1.icursor(END)

ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
w = 310
h = 270
x = (ws / 2) - (w / 2)
y = (hs / 2) - (h / 2)


# set the dimensions of the screen
Beispiel #31
0
    def init_gui(self):
        """init helper"""
        # setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        # Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(
            msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white"
        )
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        # History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(
            history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white"
        )
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind("<Double-Button-1>", self.select_recent_file)
        self.set_history_window()

        # status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        # labels
        self.lblRatingLabel = Label(rating_frame, text="Rating:")
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text="Recently Used:").pack(side=LEFT)
        Label(top_frame, text="Module or package").pack(side=LEFT)

        # file textbox
        self.txtModule = Entry(top_frame, background="white")
        self.txtModule.bind("<Return>", self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        # results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(
            res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier"
        )
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        # buttons
        Button(top_frame, text="Open", command=self.file_open).pack(side=LEFT)
        Button(top_frame, text="Open Package", command=(lambda: self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text="Run", command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text="Quit", command=self.quit).pack(side=BOTTOM)

        # radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(
            check_frame,
            text="Information",
            fg=COLORS["(I)"],
            variable=self.information_box,
            command=self.refresh_msg_window,
        )
        c = Checkbutton(
            check_frame,
            text="Convention",
            fg=COLORS["(C)"],
            variable=self.convention_box,
            command=self.refresh_msg_window,
        )
        r = Checkbutton(
            check_frame, text="Refactor", fg=COLORS["(R)"], variable=self.refactor_box, command=self.refresh_msg_window
        )
        w = Checkbutton(
            check_frame, text="Warning", fg=COLORS["(W)"], variable=self.warning_box, command=self.refresh_msg_window
        )
        e = Checkbutton(
            check_frame, text="Error", fg=COLORS["(E)"], variable=self.error_box, command=self.refresh_msg_window
        )
        f = Checkbutton(
            check_frame, text="Fatal", fg=COLORS["(F)"], variable=self.fatal_box, command=self.refresh_msg_window
        )
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        # check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(
            radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window
        )
        rawMet = Radiobutton(
            radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window
        )
        dup = Radiobutton(
            radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window
        )
        ext = Radiobutton(
            radio_frame,
            text="External dependencies",
            variable=self.box,
            value="External dependencies",
            command=self.refresh_results_window,
        )
        stat = Radiobutton(
            radio_frame,
            text="Statistics by type",
            variable=self.box,
            value="Statistics by type",
            command=self.refresh_results_window,
        )
        msgCat = Radiobutton(
            radio_frame,
            text="Messages by category",
            variable=self.box,
            value="Messages by category",
            command=self.refresh_results_window,
        )
        msg = Radiobutton(
            radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window
        )
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=E)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, columnspan=2, sticky=W)

        # dictionary for check boxes and associated error term
        self.msg_type_dict = {
            "I": lambda: self.information_box.get() == 1,
            "C": lambda: self.convention_box.get() == 1,
            "R": lambda: self.refactor_box.get() == 1,
            "E": lambda: self.error_box.get() == 1,
            "W": lambda: self.warning_box.get() == 1,
            "F": lambda: self.fatal_box.get() == 1,
        }
        self.txtModule.focus_set()
class GraphicalUserInterface(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.__initUI()

    def __initUI(self):
        self.parent.title("Fuel Manager")

        # parameters that the user can modify
        self.__exchvar = BooleanVar()
        self.__exchrate = True
        self.__datevar = BooleanVar()
        self.__datetime = True
        self.__empty_tank_var = BooleanVar()
        self.__empty_tank = False
        self.__airport_file = "input files/airport.csv"
        self.__aircraft_file = "input files/aircraft.csv"
        self.__currency_file = "input files/countrycurrency.csv"
        self.__exchange_rate_file = "input files/currencyrates.csv"
        self.__itinerary_file = "input files/testroutes.csv"
        self.__output_file = "bestroutes/bestroutes.csv"
        self.__home_airport = ["DUB"]
        self.__other_airports = ["LHR", "CDG", "JFK", "AAL", "AMS", "ORK"]
        self.__hubs = ["MHP"]
        self.__stopover_cost = 0
        self.__constraints = "JFK AAL / JFK CDG"
        self.__aircraft_code = "747"

        # main frame
        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=True)
        self.pack(fill=BOTH, expand=True)

        # manage single itinerary frame
        self.manual_frame = LabelFrame(self, text="Manage a single itinerary", font=("Helvetica", 14), width=300)
        self.manual_frame.place(x=50, y=50)

        # Empty row to put some space between the other rows and to control the width of this frame because
        # I don't know what I'm doing
        self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=0, sticky="W")

        # Text field where user can enter home airport
        self.home_airport_label = Label(self.manual_frame, width=22, text="Home airport:", anchor='w')
        self.home_airport_label.grid(row=1, sticky="W")
        self.home_airport_entry = Entry(self.manual_frame, width=50)
        self.home_airport_entry.grid(row=2, sticky="E")
        self.home_airport_entry.insert(0, self.__home_airport)

        self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=3, sticky="W")

        # Text field where user can enter other airports
        self.other_airports_label = Label(self.manual_frame, width=22, text="Other airports:", anchor='w')
        self.other_airports_label.grid(row=4, sticky="W")
        self.other_airports_entry = Entry(self.manual_frame, width=50)
        self.other_airports_entry.grid(row=5, sticky="E")
        self.other_airports_entry.insert(0, self.__other_airports)

        self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=6, sticky="W")

        # Text field where user can enter aircraft code
        self.aircraft_label = Label(self.manual_frame, width=22, text="Aircraft code:", anchor='w')
        self.aircraft_label.grid(row=7, sticky="W")
        self.aircraft_entry = Entry(self.manual_frame, width=50)
        self.aircraft_entry.grid(row=8, sticky="E")
        self.aircraft_entry.insert(0, self.__aircraft_code)

        self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=9, sticky="W")

        # Text field where user can enter constraints
        self.constraints_label = Label(self.manual_frame, width=22, text="Constraints:", anchor='w')
        self.constraints_label.grid(row=13, sticky="W")
        self.constraints_entry = Entry(self.manual_frame, width=50)
        self.constraints_entry.grid(row=14, sticky="E")
        self.constraints_entry.insert(0, self.__constraints)
        self.constraints_explanation_label = \
            Label(self.manual_frame, width=50,
                  text="Each constraint should consist of three-letter airport codes"
                       "\nseparated by spaces. To enter more than one constraint,"
                       "\nuse ' / ' to separate them", anchor='w', justify='left')
        self.constraints_explanation_label.grid(row=15, sticky="W")

        self.empty_label = Label(self.manual_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=16, sticky="W")

        # run button
        self.run_button = Button(self.manual_frame, text='Manage itinerary', command=self.__manage_single_itinerary,
                                 bg="#CCE1E8")
        self.run_button.grid(row=16, sticky="E")

        # manage list of itineraries frame
        self.itinerary_list_frame = LabelFrame(self, text="Manage a list of itineraries",
                                               font=("Helvetica", 14), width=300)
        self.itinerary_list_frame.place(x=50, y=375)

        # Empty row to put some space between the other rows and to control the width of this frame
        self.empty_label = Label(self.itinerary_list_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=12, sticky="W")

        # Text field where user can enter itinerary filepath
        self.itinerary_label = Label(self.itinerary_list_frame, width=22, text="Itinerary list: ", anchor='w')
        self.itinerary_label.grid(row=13, sticky="W")
        self.itinerary_entry = Entry(self.itinerary_list_frame, width=50)
        self.itinerary_entry.grid(row=13, sticky="E")
        self.itinerary_entry.insert(0, self.__itinerary_file)
        self.itinerary_button = Button(self.itinerary_list_frame, text='Browse...',
                                       command=self.__get_itinerary_filename)
        self.itinerary_button.grid(row=14, sticky="E")

        self.empty_label = Label(self.itinerary_list_frame, text=" ", width=60, height=2, font=("Helvetica", 1))
        self.empty_label.grid(row=15, sticky="W")

        # run button
        self.run_button = Button(self.itinerary_list_frame, text='Manage list of itineraries',
                                 command=self.__manage_list, bg="#CCE1E8")
        self.run_button.grid(row=16, sticky="E")

        # Fuel management settings frame
        self.general_frame = LabelFrame(self, text="Fuel management settings", font=("Helvetica", 14), width=300)
        self.general_frame.place(x=500, y=50)

        # Empty row to put some space between the other rows and to control the width of this frame
        self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=0, sticky="W")

        # Text field where user can enter hubs
        self.hubs_label = Label(self.general_frame, width=22, text="Hubs:", anchor='w')
        self.hubs_label.grid(row=1, sticky="W")
        self.hubs_entry = Entry(self.general_frame, width=50)
        self.hubs_entry.grid(row=2, sticky="E")
        self.hubs_entry.insert(0, self.__hubs)

        self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=3, sticky="W")

        # Text field where user can enter cost of extra stopovers
        self.stopover_cost_label = Label(self.general_frame, width=40, text="Cost of each extra stopover (euros):",
                                         anchor='w')
        self.stopover_cost_label.grid(row=4, sticky="W")
        self.stopover_cost_entry = Entry(self.general_frame, width=50)
        self.stopover_cost_entry.grid(row=5, sticky="E")
        self.stopover_cost_entry.insert(0, self.__stopover_cost)

        self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=6, sticky="W")

        # bring home extra fuel checkbox
        self.empty_tank_cb = Checkbutton(self.general_frame,
                                         text="Always return to home airport with an empty tank",
                                         variable=self.__empty_tank_var, command=self.__empty_tank_toggle)
        self.empty_tank_cb.grid(row=7, sticky="W")

        self.empty_label = Label(self.general_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=8, sticky="W")

        # manage inputs frame
        self.input_frame = LabelFrame(self, text="Inputs", font=("Helvetica", 14), width=300)
        self.input_frame.place(x=500, y=250)

        self.empty_label = Label(self.input_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=0, sticky="W")

        # Text field where user can enter airport filepath
        self.airport_label = Label(self.input_frame, width=22, text="Airport list: ", anchor='w')
        self.airport_label.grid(row=1, sticky="W")
        self.airport_entry = Entry(self.input_frame, width=50)
        self.airport_entry.grid(row=1, sticky="E")
        self.airport_entry.insert(0, self.__airport_file)
        self.airport_button = Button(self.input_frame, text='Browse...', command=self.__get_airport_filename)
        self.airport_button.grid(row=2, sticky="E")

        self.empty_label = Label(self.input_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=3, sticky="W")

        # Text field where user can enter aircraft filepath
        self.aircraft_file_label = Label(self.input_frame, width=22, text="Aircraft list: ", anchor='w')
        self.aircraft_file_label.grid(row=4, sticky="W")
        self.aircraft_file_entry = Entry(self.input_frame, width=50)
        self.aircraft_file_entry.grid(row=4, sticky="E")
        self.aircraft_file_entry.insert(0, self.__aircraft_file)
        self.aircraft_file_button = Button(self.input_frame, text='Browse...', command=self.__get_aircraft_filename)
        self.aircraft_file_button.grid(row=5, sticky="E")

        self.empty_label = Label(self.input_frame, text=" ", width=425, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=6, sticky="W")

        # Text field where user can enter country-currency filepath
        self.currency_label = Label(self.input_frame, width=22, text="Currency list: ", anchor='w')
        self.currency_label.grid(row=7, sticky="W")
        self.currency_entry = Entry(self.input_frame, width=50)
        self.currency_entry.grid(row=7, sticky="E")
        self.currency_entry.insert(0, self.__currency_file)
        self.currency_button = Button(self.input_frame, text='Browse...', command=self.__get_currency_filename)
        self.currency_button.grid(row=8, sticky="E")

        self.empty_label = Label(self.input_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=9, sticky="W")

        # Text field where user can enter exchange rate filepath
        self.exchange_rate_label = Label(self.input_frame, width=22, text="Exchange rate list: ", anchor='w')
        self.exchange_rate_label.grid(row=10, sticky="W")
        self.exchange_rate_entry = Entry(self.input_frame, width=50)
        self.exchange_rate_entry.grid(row=10, sticky="E")
        self.exchange_rate_entry.insert(0, self.__exchange_rate_file)
        self.exchange_rate_button = Button(self.input_frame, text='Browse...', command=self.__get_exchange_rate_filename)
        self.exchange_rate_button.grid(row=11, sticky="E")

        # real-time exchange rates checkbox
        self.forex = Checkbutton(self.input_frame, text="Use real-time exchange rates", variable=self.__exchvar,
                                 command=self.__forex_toggle)
        self.forex.select()
        self.forex.grid(row=12, sticky="W")

        # manage output frame
        self.output_frame = LabelFrame(self, text="Output", font=("Helvetica", 14), width=300)
        self.output_frame.place(x=500, y=550)

        self.empty_label = Label(self.output_frame, text=" ", width=60, height=1, font=("Helvetica", 1))
        self.empty_label.grid(row=0, sticky="W")

        # Text field where user can enter output filepath
        self.output_label = Label(self.output_frame, width=22, text="Output file: ", anchor='w')
        self.output_label.grid(row=1, sticky="W")
        self.output_entry = Entry(self.output_frame, width=50)
        self.output_entry.grid(row=1, sticky="E")
        self.output_entry.insert(0, self.__output_file)
        self.output_button = Button(self.output_frame, text='Browse...', command=self.__get_output_filename)
        self.output_button.grid(row=2, sticky="E")

        # append date to output filename checkbox
        self.datetime_cb = Checkbutton(self.output_frame,
                                       text="Append date and time to filename (e.g., bestroutes 20151218 160000.csv)",
                                       variable=self.__datevar, command=self.__datetime_toggle)
        self.datetime_cb.grid(row=3, sticky="W")
        self.datetime_cb.select()

    # GUI methods

    def __forex_toggle(self):
        if self.__exchvar.get() == True:
            self.__exchrate = True
        else:
            self.__exchrate = False

    def __datetime_toggle(self):
        if self.__datevar.get() == True:
            self.__datetime = True
        else:
            self.__datetime = False

    def __empty_tank_toggle(self):
        if self.__empty_tank_var.get() == True:
            self.__empty_tank = True
        else:
            self.__empty_tank = False

    def __get_airport_filename(self):
        self.__airport_file = filedialog.askopenfilename(
            filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*")))
        self.airport_entry.delete(0, END)
        self.airport_entry.insert(0, self.__airport_file)

    def __get_aircraft_filename(self):
        self.__aircraft_file = filedialog.askopenfilename(
            filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*")))
        self.aircraft_file_entry.delete(0, END)
        self.aircraft_file_entry.insert(0, self.__aircraft_file)

    def __get_currency_filename(self):
        self.__currency_file = filedialog.askopenfilename(
            filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*")))
        self.currency_entry.delete(0, END)
        self.currency_entry.insert(0, self.__currency_file)

    def __get_exchange_rate_filename(self):
        self.__exchange_rate_file = filedialog.askopenfilename(
            filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*")))
        self.exchange_rate_entry.delete(0, END)
        self.exchange_rate_entry.insert(0, self.__exchange_rate_file)

    def __get_itinerary_filename(self):
        self.__itinerary_file = filedialog.askopenfilename(
            filetypes=(("Comma-separated values files", "*.csv"), ("All files", "*.*")))
        self.itinerary_entry.delete(0, END)
        self.itinerary_entry.insert(0, self.__itinerary_file)

    def __get_output_filename(self):
        self.__output_file = filedialog.asksaveasfilename(defaultextension=".csv", filetypes=(
            ("Comma-separated values file", "*.csv"), ("All Files", "*.*")))
        self.output_entry.delete(0, END)
        self.output_entry.insert(0, self.__output_file)

    def __manage_list(self):
        # validate user inputs
        hubs, stopover_cost = validate_inputs_for_list_of_itineraries(self.hubs_entry.get().upper().split(),
                                                                      self.stopover_cost_entry.get())
        print("Managing list of itineraries...")
        manage_list_of_routes(self.__exchrate,
                      self.__datetime,
                      self.__empty_tank,
                      hubs,
                      stopover_cost,
                      self.itinerary_entry.get(),
                      self.airport_entry.get(),
                      self.aircraft_file_entry.get(),
                      self.currency_entry.get(),
                      self.exchange_rate_entry.get(),
                      self.output_entry.get())

    def __manage_single_itinerary(self):
        # validate user inputs
        try:
            hubs, stopover_cost, constraints_list, home_airport, other_airports, aircraft_code = \
                validate_inputs_for_single_itinerary(self.hubs_entry.get().upper().split(),
                                self.stopover_cost_entry.get(),
                                self.constraints_entry.get().upper().split(),
                                self.home_airport_entry.get().upper(),
                                self.other_airports_entry.get().upper().split(),
                                self.aircraft_entry.get().upper())
        except TypeError:
            return

        print("Managing single itinerary...")
        manage_single_route(home_airport,
                            other_airports,
                            aircraft_code,
                            self.__exchrate,
                            self.__datetime,
                            self.__empty_tank,
                            hubs,
                            stopover_cost,
                            constraints_list,
                            self.airport_entry.get(),
                            self.aircraft_file_entry.get(),
                            self.currency_entry.get(),
                            self.exchange_rate_entry.get(),
                            self.output_entry.get())
Beispiel #33
0
class UserInterface(UIfunctions):
    def __init__(self, filehandler, databasehandler, path=None):
        self.title = "OpenKeynote (BETA)"
        self._filehandler = filehandler
        self._databasehandler = databasehandler
        self.path = path
        self.itemlist = []
        self.root = Tk()
        self.previeweditem = ""
        self.editeditem = ""
        self.case_selected = IntVar()
        self.parentname = ""
        self.autosave = IntVar()
        self._html_path = None

        self._default_title = self.title
        self.main_window()
        self.tree_view()
        self.frame_vertical_bar()
        self.bindings_and_menu()
        self.frame_setup()

        self.update_status()
        self.root.mainloop()

    def main_window(self, *args):
        self.mainframe = Frame(self.root)
        self.mainframe.grid(column=0, row=0, sticky=E+W+N+S)
        self.bottomframe = Frame(self.root)
        self.bottomframe.grid(column=0, row=1, sticky=E+W)
        self.statusbar = Label(
            self.bottomframe, text=self._filehandler.statustext, anchor=W)
        self.statusbar.pack(fill=BOTH, padx=0, pady=0)
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        self.root.rowconfigure(1, pad=10)
        self.pw = PanedWindow(self.mainframe, orient=HORIZONTAL)
        self.pw.pack(fill=BOTH, expand=1)
        self.pane_left = Frame(self.root)
        self.pw.add(self.pane_left)
        self.pane_right = Frame(self.root)
        self.pw.add(self.pane_right)

        self.frame_left = Frame(self.pane_left)
        self.frame_left.pack(fill=BOTH, expand=1, padx=3, pady=3)
        self.frame_center = Frame(self.pane_right)
        self.frame_center.grid(row=0, column=0, sticky=W+N, rowspan=4)
        self.frame_right = Frame(self.pane_right)
        self.frame_right.grid(row=0, column=1, sticky=W+E+N+S, padx=3, pady=3)
        self.pane_right.columnconfigure(1, weight=1)
        self.pane_right.rowconfigure(0, weight=1)
        self.sf1 = Text(self.frame_left, height=1, width=25, borderwidth=1,
                        relief="solid", highlightthickness=0)
        self.sf1.insert(1.0, "TODO: Searchbar")
        self.sf1.grid(row=0, column=0, sticky=W+E+N+S, pady=5)
        self.sf1.config(state=DISABLED)
        self.cs = Button(self.frame_left, text="X", width=1)
        self.cs.grid(row=0, column=1)
        self.frame_left.columnconfigure(0, weight=1)

    def tree_view(self, *args):
        """
        Tree view
        """
        self.l1 = ttk.Treeview(self.frame_left, columns=["stuff"], show="tree")
        self.yscroll = Scrollbar(self.frame_left, orient=VERTICAL)
        self.yscroll.config(width=10)
        self.l1['yscrollcommand'] = self.yscroll.set
        self.yscroll['command'] = self.l1.yview
        self.l1.grid(row=1, column=0, columnspan=3,  padx=30,
                     pady=10, sticky=N+S+E+W)
        self.yscroll.grid(row=1, column=0, columnspan=3, sticky=N+S+E)
        self.l1.bind("<ButtonRelease-1>", self.change_selection)

        self.frame_left.rowconfigure(1, weight=1)

    def frame_vertical_bar(self, *args):
        self.vbs = []
        middlebuttons = ("New Item", "New Subitem", "Delete",
                         "Rename", "Change Parent","- Descriptions (BETA) -")
        middlefunctions = (
            lambda: self.add_item(parent=self.parentname),
            lambda: self.add_item(parent=self.previeweditem),
            lambda: self.delete_item_dialog(),
            self.rename_item_dialog,
            self.change_parent_dialog,
            lambda: self.description_window(database_rows=self._databasehandler.view())
            #lambda: self.save_keynote_to_database(title="title",keynote="KN10", entreprise="min entreprise", category="")
            #self.save_all_keynotes_to_database
            )

        for a, button_text in enumerate(middlebuttons):
            self.vbs.append(ttk.Button(self.frame_center, text=button_text))
            self.vbs[a].pack(fill=BOTH)
            self.vbs[a].config(command=middlefunctions[a], width=10)
        for x in [2, 3, 4]:
            self.vbs[x].config(state=DISABLED)
        self.tx1 = Label(self.frame_right, text="Preview", anchor=W)
        self.tx1.grid(row=0, column=0, columnspan=3, sticky=W+E)
        self.tx2 = Label(self.frame_right, text="Editing", anchor=W)
        self.tx2.grid(row=2, column=0, sticky=W+E)

        self.e1 = scrolledtext.ScrolledText(self.frame_right,
                                            fg="#555", font=("Courier", 13),
                                            padx=10, pady=10,
                                            highlightthickness=0,
                                            borderwidth=1, relief="solid")
        self.e1.grid(row=1, column=0, columnspan=3, sticky=N+S+E+W)
        # was Text before

        self.e2 = scrolledtext.ScrolledText(self.frame_right,
                                            font=("Courier", 13), borderwidth=1,
                                            relief="solid", padx=10, pady=10,
                                            highlightthickness=0)
        self.e2.grid(row=3, column=0, columnspan=3, sticky=E+W+S+N)
        # AUTOSAVE
        self.autosaveFrame = LabelFrame(self.frame_center, text=' Autosave ')
        self.autosaveFrame.pack(fill=BOTH)
        self.autosave.trace(
            'w', lambda *args: print(f"Autosave: {self.autosave.get()}"))
        self.autosaveCheck = Checkbutton(
            self.autosaveFrame, text="Enabled", variable=self.autosave, anchor=W)
        self.autosaveCheck.select()
        self.autosaveCheck.pack(fill=BOTH)
        self.labelsFrame = LabelFrame(self.frame_center, text=' Change Case ')
        self.labelsFrame.pack(fill=BOTH)

        # CASE BUTTONS
        self.case_radiobuttons = []
        self.case_selected.set(99)
        rbtns = ['No change', 'UPPERCASE', 'lowercase', 'First Letter']
        for a, button_text in enumerate(rbtns):
            self.case_radiobuttons.append(
                Radiobutton(self.labelsFrame, text=button_text,
                            variable=self.case_selected,
                            value=a, command=self.change_case, width=10, anchor=W))
            self.case_radiobuttons[a].grid(sticky="W", row=a)

    def change_case(self, *args):
        pass

    def bindings_and_menu(self, *args):
        """
        Main key bindings
        """
        if os.name == "nt":
            self.CTRL = "Control"
            self.MBTN = "3"
        else:
            self.CTRL = "Command"
            self.MBTN = "2"

        def bindings_key(event):
            if event.state == 8 or event.state == 12:
                return
            else:
                return("break")

        self.sf1.bind("<Tab>", lambda a: self.focus_on(target=self.l1))
        self.sf1.bind("<Shift-Tab>", lambda a: self.focus_on(target=self.vb2))
        self.e1.bind("<Key>", bindings_key)
        self.e1.bind("<Tab>", lambda a: self.focus_on(target=self.e2))
        self.e1.bind(
            "<Shift-Tab>", lambda a: self.focus_on(target=self.vbs[-1]))

        self.e2.bind("<Tab>", lambda a: self.focus_on(target=self.vb1))
        self.e2.bind("<Shift-Tab>", lambda a: self.focus_on(target=self.e1))

        self.vb1 = ttk.Button(self.frame_right, text="Edit")
        self.vb1.grid(row=2, column=1)
        self.vb1.config(command=self.edit_item)
        self.vb2 = ttk.Button(self.frame_right, text="Save")
        self.vb2.grid(row=2, column=2)
        self.vb2.config(command=self.saveitem)

        self.frame_right.rowconfigure(1, weight=1)
        self.frame_right.rowconfigure(3, weight=1)
        self.frame_right.columnconfigure(0, weight=1)

        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)
        file = Menu(self.menu, tearoff=0)  # TODO is it a win thing?
        file.add_command(label='New File*', command=self.close_file)
        file.add_command(
            label='Open File...', accelerator=f"{self.CTRL}-o",
            command=self.open_file_dialog)
        file.add_command(label='Save File',
                         accelerator=f"{self.CTRL}-s", command=self.save_file)
        file.add_command(label='Save File As...',
                         command=self.save_file_dialog)
        file.add_command(label='Close file', command=self.close_file)
        file.add_command(
            label='Exit', accelerator=f"{self.CTRL}-q", command=self.client_exit)
        self.menu.add_cascade(label='File', menu=file)

        self.clickmenu = Menu(self.root, tearoff=0)
        self.clickmenu.add_command(label="Cut")
        self.clickmenu.add_command(label="Copy")
        self.clickmenu.add_command(label="Paste")
        self.root.bind_class(
            "Text", f"<Button-{self.MBTN}><ButtonRelease-{self.MBTN}>",
            lambda event=None: self.right_click_menu())

        menu_edit = Menu(self.menu, tearoff=0)
        menu_edit.add_command(label='Select All', accelerator=f"{self.CTRL}-a",
                              command=self.select_all)
        self.root.bind(f"<{self.CTRL}-a>", self.select_all)
        self.e1.bind(f"<{self.CTRL}-a>", self.select_all)

        self.e1.bind(f"<{self.CTRL}-c>", self.e1.event_generate("<<Copy>>"))
        self.e2.bind(f"<{self.CTRL}-a>", self.select_all)
        menu_edit.add_command(label='Cut', accelerator=f"{self.CTRL}-x",
                              command=lambda: self.root.event_generate("<<Cut>>"))
        menu_edit.add_command(label='Copy', accelerator=f"{self.CTRL}-c",
                              command=lambda: self.copy_text())
        menu_edit.add_command(label='Paste', accelerator=f"{self.CTRL}-v",
                              command=lambda: self.root.event_generate("<<Paste>>"))
        self.menu.add_cascade(label='Edit', menu=menu_edit)

        menu_help = Menu(self.menu, tearoff=0)
        menu_help.add_command(label='About', command=self.about)
        self.menu.add_cascade(label='Help', menu=menu_help)

        for i in "Up,Down,Right,Return,Left".split(","):
            self.root.bind("<"+i+">", self.change_selection)

        self.e1.bind("<F2>", self.rename_item_dialog)
        self.e1.bind(f"<{self.CTRL}-s>", None)
        self.e1.bind(f"<{self.CTRL}-o>", None)
        self.root.bind("<F2>", self.rename_item_dialog)
        self.root.bind(f"<{self.CTRL}-s>", self.save_file)
        self.root.bind(f"<{self.CTRL}-o>", self.open_file_dialog)

    def copy_text(self, event=None):
        w = self.root.focus_get()
        w.event_generate("<<Copy>>")

    def update_title(self, title=""):
        self.root.title(title)

    def frame_setup(self, *args):
        """
        Misc UI functions
        """

        # sharp fonts in high res (https://stackoverflow.com/questions/41315873/
        # attempting-to-resolve-blurred-tkinter-text-scaling-on-windows-10-high-dpi-disp)
        if os.name == "nt":
            # TODO
            # self.root.protocol("WM_DELETE_WINDOW", self.client_exit)
            from ctypes import windll, pointer, wintypes
            try:
                windll.shcore.SetProcessDpiAwareness(1)
            except Exception:
                pass  # this will fail on Windows Server and maybe early Windows
            # TODO: Put link to ico file on windows.
            try:
                iconpath = Path("icon.ico")
                self.root.iconbitmap(Path())
            except:
                print("error with icon")
            else:  # mac?
                self.root.createcommand('exit', self.client_exit)

        self.root.title(self.title)
        if self.path:
            self.open_file(path=self.path)

        """ TODO: ICON /Windows

        self.root.iconbitmap("/Users/msn/Dropbox/py/Git/OpenKeynote/images/ico.icns")

        img = Image(
            "photo", file="/Users/msn/Dropbox/py/Git/OpenKeynote/images/large.gif")
        self.root.iconphoto(True, img) # you may also want to try this.
        self.root.call('wm','iconphoto', self.root._w, img)
        """
        self.width = min(int(self.root.winfo_screenwidth()-500), 1500)
        self.height = int(self.root.winfo_screenheight()-500)
        self.root.winfo_width()
        self.root.winfo_height()
        self.x = (self.root.winfo_screenwidth() // 2) - (self.width // 2)
        # self.x = 0
        self.y = (self.root.winfo_screenheight() // 2) - (self.height // 2)
        # self.y = 50
        self.root.geometry(f"{self.width}x{self.height}+{self.x}+{self.y}")
        self.root.update()
        self.root.after(0, self.fixUI)

    def right_click_menu(self, event=None):
        x, y = self.root.winfo_pointerxy()
        w = self.root.winfo_containing(x, y)
        # https://stackoverflow.com/a/8476726/11514850
        # w = self.root
        self.clickmenu.entryconfigure("Cut",
                                      command=lambda: w.event_generate("<<Cut>>"))
        self.clickmenu.entryconfigure("Copy",
                                      command=lambda: w.event_generate("<<Copy>>"))
        self.clickmenu.entryconfigure("Paste",
                                      command=lambda: w.event_generate("<<Paste>>"))
        self.clickmenu.tk.call("tk_popup", self.clickmenu,
                               w.winfo_pointerx(), w.winfo_pointery())

    def update_status(self, event=None):
        """
        Set statusbar in bottom of the window
        """
        self.statusbar.config(text=self._filehandler.refresh_status())
        self.root.after(100, self.update_status)

    def client_exit(self, *args):
        answer = messagebox.askyesnocancel('quit?', 'Save file first?')
        if answer == True:
            self.save_file()
            sys.exit()
        if answer == None:
            return
        if answer == False:
            exit()
Beispiel #34
0
class MainApp:
    def __init__(self):
        self.root = Tk()
        self.root.title("KCLP Solution - Submitted by Team Vanished Gradient (Deep Raval, Jaymin Suhagiya)")
        self.root.tk.call('wm', 'iconphoto', self.root._w, PhotoImage(file='../Images/icon.png'))
        #self.root.geometry('360x100')
        self.root.resizable(0,0)
        self.switch_details = []
        
        self.details_lf = LabelFrame(self.root, text = " 1. Enter Rack & Switch Details: ")
        self.details_lf.grid(row = 0, columnspan = 10, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        
        self.hyperparam_lf = LabelFrame(self.root, text = "2. Hyperparameteres:")
        self.hyperparam_lf.grid(row = 1, column = 0, columnspan = 5, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        
        self.solve_lf= LabelFrame(self.root, text = "3. Execute and Stats:")
        self.solve_lf.grid(row = 1, column = 5, columnspan = 5, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        
        Label(self.details_lf, text = "Rack length :").grid(row = 0, column = 0, sticky = 'E', padx = 5, pady = 2)
        self.rack_length = Entry(self.details_lf, width = 15)
        self.rack_length.grid(row = 0, column = 1, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Rack breadth :").grid(row = 0, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.rack_breadth = Entry(self.details_lf, width = 15)
        self.rack_breadth.grid(row = 0, column = 3, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Rack height :").grid(row = 0, column = 4, sticky = 'E', padx = 5, pady = 2)
        self.rack_height = Entry(self.details_lf, width = 15)
        self.rack_height.grid(row = 0, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Switch 1 (l, b, h, value, instances):").grid(row = 1, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s1_l = Entry(self.details_lf, width = 15)
        self.s1_l.grid(row = 1, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s1_b = Entry(self.details_lf, width = 15)
        self.s1_b.grid(row = 1, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s1_h = Entry(self.details_lf, width = 15)
        self.s1_h.grid(row = 1, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s1_v = Entry(self.details_lf, width = 15)
        self.s1_v.grid(row = 1, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s1_i = Entry(self.details_lf, width = 15)
        self.s1_i.grid(row = 1, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Switch 2 (l, b, h, value, instances):").grid(row = 2, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s2_l = Entry(self.details_lf, width = 15)
        self.s2_l.grid(row = 2, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s2_b = Entry(self.details_lf, width = 15)
        self.s2_b.grid(row = 2, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s2_h = Entry(self.details_lf, width = 15)
        self.s2_h.grid(row = 2, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s2_v = Entry(self.details_lf, width = 15)
        self.s2_v.grid(row = 2, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s2_i = Entry(self.details_lf, width = 15)
        self.s2_i.grid(row = 2, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        Label(self.details_lf, text = "Switch 3 (l, b, h, value, instances):").grid(row = 3, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s3_l = Entry(self.details_lf, width = 15)
        self.s3_l.grid(row = 3, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s3_b = Entry(self.details_lf, width = 15)
        self.s3_b.grid(row = 3, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s3_h = Entry(self.details_lf, width = 15)
        self.s3_h.grid(row = 3, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s3_v = Entry(self.details_lf, width = 15)
        self.s3_v.grid(row = 3, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s3_i = Entry(self.details_lf, width = 15)
        self.s3_i.grid(row = 3, column = 5, sticky = 'E', padx = 5, pady = 2)

        Label(self.details_lf, text = "Switch 4 (l, b, h, value, instances):").grid(row = 4, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s4_l = Entry(self.details_lf, width = 15)
        self.s4_l.grid(row = 4, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s4_b = Entry(self.details_lf, width = 15)
        self.s4_b.grid(row = 4, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s4_h = Entry(self.details_lf, width = 15)
        self.s4_h.grid(row = 4, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s4_v = Entry(self.details_lf, width = 15)
        self.s4_v.grid(row = 4, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s4_i = Entry(self.details_lf, width = 15)
        self.s4_i.grid(row = 4, column = 5, sticky = 'E', padx = 5, pady = 2)

        Label(self.details_lf, text = "Switch 5 (l, b, h, value, instances):").grid(row = 5, column = 0, sticky = 'E', padx = 5, pady = 2) 
        self.s5_l = Entry(self.details_lf, width = 15)
        self.s5_l.grid(row = 5, column = 1, sticky = 'E', padx = 5, pady = 2)
        self.s5_b = Entry(self.details_lf, width = 15)
        self.s5_b.grid(row = 5, column = 2, sticky = 'E', padx = 5, pady = 2)
        self.s5_h = Entry(self.details_lf, width = 15)
        self.s5_h.grid(row = 5, column = 3, sticky = 'E', padx = 5, pady = 2)
        self.s5_v = Entry(self.details_lf, width = 15)
        self.s5_v.grid(row = 5, column = 4, sticky = 'E', padx = 5, pady = 2)        
        self.s5_i = Entry(self.details_lf, width = 15)
        self.s5_i.grid(row = 5, column = 5, sticky = 'E', padx = 5, pady = 2)
        
        self.strat_option_var = StringVar(self.root)
        choices = { 'Strategy 2','Strategy 3','Strategy 1'}
        self.strat_option_var.set('Strategy 3') 
        self.strat_option = OptionMenu(self.hyperparam_lf, self.strat_option_var, *choices)
        Label(self.hyperparam_lf, text="Choose a Strategy: ").grid(row = 0, column = 0)
        self.strat_option.grid(row = 0, column = 1)
        
        self.orientation_allowed_var = IntVar()
        self.orientation_allowed = Checkbutton(self.hyperparam_lf,variable = self.orientation_allowed_var, text="Orientation allowed", onvalue = 1, offvalue = 0)
        self.orientation_allowed.grid(row = 0, column=2, pady = 2, sticky = 'WE')
        self.orientation_allowed.select()
                
        self.pairing_allowed_var = IntVar()
        self.pairing_allowed = Checkbutton(self.hyperparam_lf,variable = self.pairing_allowed_var, text="Pairing allowed", onvalue = 1, offvalue = 0)
        self.pairing_allowed.grid(row = 0, column=3, pady = 2, sticky = 'WE')
        self.pairing_allowed.select()

        Label(self.hyperparam_lf, text = "Strategy 1: width,depth: Value||Volume").grid(row = 1, column = 0, columnspan = 3, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        Label(self.hyperparam_lf, text = "Strategy 2: width,depth: Value/Volume").grid(row = 2, column = 0, columnspan = 3, sticky='W', padx=5, pady=5, ipadx=5, ipady=5)
        Label(self.hyperparam_lf, text = "Strategy 3: width:Value||Volume, depth:Value/Volume (Most Preferred)").grid(row = 3, column = 0, columnspan = 3, sticky='W', padx=5, pady=0, ipadx=5, ipady=4)
        
        self.exec_time_lbl = Label(self.solve_lf, text = "Execution Completed in: - Seconds")
        self.exec_time_lbl.grid(row = 0, column = 0, columnspan = 5 , pady = 2, sticky = 'W')
        
        self.rs_lbl = Label(self.solve_lf, text = "Remaining Switches:- ")
        self.rs_lbl.grid(row = 1, column = 0, columnspan = 5, sticky='W', padx=5, pady=5)
        
        self.val_gain_lbl = Label(self.solve_lf, text = "Total Value gained: - ")
        self.val_gain_lbl.grid(row = 2, column = 0, columnspan = 5, sticky='W', padx=5, pady=5)
        
        self.vol_pack_lbl = Label(self.solve_lf, text = "% of total volume packed: - %")
        self.vol_pack_lbl.grid(row = 3, column = 0, columnspan = 5, sticky='W', padx=5, pady=5)
        
        self.reset_btn = Button(self.solve_lf, text = "Reset", bg = "lightblue", command = self.reset)
        self.reset_btn.grid(row = 4, column = 2, sticky='W', padx=5, pady=0, ipadx=5, ipady=0)        
        self.solve_btn = Button(self.solve_lf, text = "Solve", bg = "lightblue", command = self.solve)
        self.solve_btn.grid(row = 4, column = 3, sticky='W', padx=5, pady=0, ipadx=5, ipady=0)
        self.vis_btn = Button(self.solve_lf, text = "Visualize", bg = "lightblue", command = self.visualize)
        self.vis_btn.grid(row = 4, column = 4, sticky='W', padx=5, pady=0, ipadx=5, ipady=0)

        
    def run(self):
        self.root.mainloop()
        
    def reset(self):
        self.rack_length.delete(0, END)
        self.rack_height.delete(0, END)
        self.rack_breadth.delete(0, END)
        
        self.s1_b.delete(0, END)
        self.s1_h.delete(0, END)
        self.s1_i.delete(0, END)
        self.s1_l.delete(0, END)
        self.s1_v.delete(0, END)
        
        self.s2_b.delete(0, END)
        self.s2_h.delete(0, END)
        self.s2_i.delete(0, END)
        self.s2_l.delete(0, END)
        self.s2_v.delete(0, END)
        
        self.s3_b.delete(0, END)
        self.s3_h.delete(0, END)
        self.s3_i.delete(0, END)
        self.s3_l.delete(0, END)
        self.s3_v.delete(0, END)
        
        self.s4_b.delete(0, END)
        self.s4_h.delete(0, END)
        self.s4_i.delete(0, END)
        self.s4_l.delete(0, END)
        self.s4_v.delete(0, END)
        
        self.s5_b.delete(0, END)
        self.s5_h.delete(0, END)
        self.s5_i.delete(0, END)
        self.s5_l.delete(0, END)
        self.s5_v.delete(0, END)
        
        self.exec_time_lbl["text"] = "Execution Completed in: - Seconds"
        self.rs_lbl["text"] = "Remaining Switches:- "
        self.val_gain_lbl["text"] = "Total Value gained: - "
        self.vol_pack_lbl["text"] = "% of total volume packed: - %"
        
    def solve(self):
        try:
            self.switch_details.clear()
            self.switch_details.append((int(self.rack_length.get()), int(self.rack_breadth.get()), int(self.rack_height.get())))
            self.switch_details.append((int(self.s1_l.get()), int(self.s1_b.get()), int(self.s1_h.get()), int(self.s1_v.get()), int(self.s1_i.get())))
            self.switch_details.append((int(self.s2_l.get()), int(self.s2_b.get()), int(self.s2_h.get()), int(self.s2_v.get()), int(self.s2_i.get())))
            self.switch_details.append((int(self.s3_l.get()), int(self.s3_b.get()), int(self.s3_h.get()), int(self.s3_v.get()), int(self.s3_i.get())))
            self.switch_details.append((int(self.s4_l.get()), int(self.s4_b.get()), int(self.s4_h.get()), int(self.s4_v.get()), int(self.s4_i.get())))
            self.switch_details.append((int(self.s5_l.get()), int(self.s5_b.get()), int(self.s5_h.get()), int(self.s5_v.get()), int(self.s5_i.get())))
        except ValueError:
            messagebox.showerror("An Error Occured", "Please fill all input fields with number !")
            return
        with open("input.txt",'w') as f:
            for i in self.switch_details:
                for j in i:
                    f.write(' '+str(j))
        import subprocess
        o = bool(self.orientation_allowed_var.get())
        p = bool(self.pairing_allowed_var.get())
        s = self.strat_option_var.get()
        if o:
            if p:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_Orientation_and_Pairing_Allowed_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_Orientation_and_Pairing_Allowed_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_Orientation_and_Pairing_Allowed_S3.exe")
            else:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_Orientation_Allowed_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_Orientation_Allowed_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_Orientation_Allowed_S3.exe")                
        else:
            if p:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_Pairing_Allowed_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_Pairing_Allowed_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_Pairing_Allowed_S3.exe")
            else:
                if s == "Strategy 1":
                    subprocess.check_call("Solution_S1.exe")
                elif s == "Strategy 2":
                    subprocess.check_call("Solution_S2.exe")
                elif s == "Strategy 3":                    
                    subprocess.check_call("Solution_S3.exe")                
                
        with open("forgui.txt") as f:
            data = f.readlines()
        self.exec_time_lbl["text"] = data[0]
        self.rs_lbl["text"] = data[1]
        self.val_gain_lbl["text"] = data[2]
        self.vol_pack_lbl["text"] = data[3]
        self.visualize()
    
    def visualize(self):
        if self.exec_time_lbl["text"] == "Execution Completed in: - Seconds":
            messagebox.showerror("An error occured !", "Solve problem before visulaizing it !")
            return 
        import matplotlib.pyplot as plt

        #5 different colors for 5 different switches (RGBA)
        colors = [(1, 0.1, 0.1, 1), (0.1, 1, 0.1, 1), (0.1, 181/255., 204/255., 1), (1, 0.5, 0.1, 1), (0.23, 0.23, 0.23, 1)]

        #Opening "output.txt" which have info about switches position and their orientation
        with open("output.txt",'r') as f:
            data = f.readlines()

        
        rz, ry, rx = [int(x) for x in data[0].split()]
        data.pop(0)
        fig = plt.figure()
        ax = fig.gca(projection='3d')
        #Making Boundary to fill smooth orientations
        ax.bar3d(0, 0, 0, max(ry,rz,rx), max(ry,rz,rx), max(ry,rz,rx), color = (0, 0, 0, 0), shade = False)
        #Making legend
        type_0 = plt.Rectangle((0, 0), 1, 1, fc = colors[0])
        type_1 = plt.Rectangle((0, 0), 1, 1, fc = colors[1])
        type_2 = plt.Rectangle((0, 0), 1, 1, fc = colors[2])
        type_3 = plt.Rectangle((0, 0), 1, 1, fc = colors[3])
        type_4 = plt.Rectangle((0, 0), 1, 1, fc = colors[4])
        ax.legend([type_0, type_1, type_2, type_3, type_4],['Type 0', 'Type 1', 'Type 2', 'Type 3', 'Type 4'])
        #Creating transparant rack  
        ax.bar3d(0, 0, 0, rx, ry, rz, color = (0, 0, 0, 0.1), shade = False)
        for line in data:
            #Creating switch with appropiate colors
            t, dz, dy, dx, x, y, z = [int(x) for x in line.split()]
            ax.bar3d(x, y, z, dx, dy, dz, color = colors[t], edgecolor = (0, 0, 0, 1), shade = False) 
            
        ax.set_title('Visualization of placed switches')
        plt.show()
Beispiel #35
0
    def initUI(self):
        self.style = Style()
        self.style.theme_use("default")
        self.master.title("LineChart")

        self.pack(fill=BOTH, expand=True)

        self.SSU = BooleanVar()
        self.SSU.set(1)
        self.COX1 = BooleanVar()
        self.COX1.set(1)
        self.EF1A = BooleanVar()
        self.EF1A.set(1)
        self.EF1A_variants = BooleanVar()
        self.EF1A_variants.set(1)
        self.filelabel = StringVar(self, "File not chosen")
        self.filename = ""
        self.var = IntVar()
        self.var.set(1)
        self.clades = IntVar()
        self.clades.set(0)

        # self.columnconfigure(2, weight=1)
        # self.rowconfigure(2, weight=1)

        cbSSU = Checkbutton(self,
                            text="SSU",
                            variable=self.SSU,
                            state=DISABLED,
                            onvalue=1,
                            offvalue=0)
        cbSSU.select()
        cbSSU.grid(sticky=W, padx=5, pady=5)
        cbCOX1 = Checkbutton(self,
                             text="COX1",
                             variable=self.COX1,
                             onvalue=1,
                             offvalue=0)
        cbCOX1.select()
        cbCOX1.grid(sticky=W, row=1, padx=5, pady=5)
        cbEF1A = Checkbutton(self,
                             text="EF1A",
                             variable=self.EF1A,
                             onvalue=1,
                             offvalue=0)
        cbEF1A.select()
        cbEF1A.grid(sticky=W, row=2, padx=5, pady=5)
        cbEcomb = Checkbutton(self,
                              text="EF1A combinations",
                              variable=self.EF1A_variants,
                              onvalue=1,
                              offvalue=0)
        cbEcomb.select()
        cbEcomb.grid(sticky=W, row=3, padx=5, pady=5)

        openButton = Button(self, text="Choose file", command=self.onOpen)
        openButton.grid(sticky=W, row=0, column=1, padx=5, pady=5)

        labFile = Label(self, textvariable=self.filelabel)
        labFile.grid(sticky=W, row=0, column=2, columnspan=2, padx=5, pady=5)

        closeButton = Button(self, text="Exit", command=self.quit)
        closeButton.grid(sticky=E, row=4, column=3, padx=5, pady=5)

        okButton = Button(self, text="OK", command=self.onOK)
        okButton.grid(sticky=W, row=4, column=0, padx=5, pady=5)
class FailsafesManager:
    def __init__(self, controller: utils.ControllerType):
        self.controller = controller
        self.tk_format = utils.TkFormat(self.controller.config_info)

        # check before taking spectra whether conditions have been met regarding when the last white reference was, etc
        self.wrfailsafe = IntVar()
        self.wrfailsafe.set(1)
        self.optfailsafe = IntVar()
        self.optfailsafe.set(1)
        self.angles_failsafe = IntVar()
        self.angles_failsafe.set(1)
        self.labelfailsafe = IntVar()
        self.labelfailsafe.set(1)
        self.wr_angles_failsafe = IntVar()
        self.wr_angles_failsafe.set(1)
        self.anglechangefailsafe = IntVar()
        self.anglechangefailsafe.set(1)

        self.settings_top = None

        self.wrfailsafe_check = None
        self.wr_timeout_entry = None
        self.optfailsafe_check = None
        self.opt_timeout_entry = None
        self.angles_failsafe_check = None
        self.label_failsafe_check = None
        self.wr_angles_failsafe_check = None
        self.anglechangefailsafe_check = None

    def on_closing(self):
        self.settings_top.withdraw()

    def show(self) -> None:
        self.settings_top = Toplevel(self.controller.master)
        self.settings_top.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.settings_top.wm_title("Failsafe Settings")
        settings_frame = Frame(self.settings_top,
                               bg=self.tk_format.bg,
                               pady=2 * self.tk_format.pady,
                               padx=15)
        settings_frame.pack()

        failsafe_title_frame = Frame(settings_frame, bg=self.tk_format.bg)
        failsafe_title_frame.pack(pady=(10, 0), fill=X, expand=True)
        failsafe_label0 = Label(
            failsafe_title_frame,
            fg=self.tk_format.textcolor,
            text=
            "Failsafes:                                                                      ",
            bg=self.tk_format.bg,
        )
        failsafe_label0.pack(side=LEFT)

        failsafe_frame = Frame(settings_frame,
                               bg=self.tk_format.bg,
                               pady=self.tk_format.pady)
        failsafe_frame.pack(fill=BOTH, expand=True, padx=(10, 10))

        wr_failsafe_check_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        wr_failsafe_check_frame.pack(pady=self.tk_format.pady,
                                     padx=(20, 5),
                                     fill=X,
                                     expand=True)
        self.wrfailsafe_check = Checkbutton(
            wr_failsafe_check_frame,
            fg=self.tk_format.textcolor,
            text="Prompt if no white reference has been taken.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.wrfailsafe,
            selectcolor=self.tk_format.check_bg,
        )
        self.wrfailsafe_check.pack(side=LEFT)
        if self.wrfailsafe.get():
            self.wrfailsafe_check.select()

        wr_timeout_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        wr_timeout_frame.pack(pady=self.tk_format.pady,
                              padx=(20, 5),
                              fill=X,
                              expand=True)
        wr_timeout_label = Label(wr_timeout_frame,
                                 fg=self.tk_format.textcolor,
                                 text="Timeout (minutes):",
                                 bg=self.tk_format.bg)
        wr_timeout_label.pack(side=LEFT, padx=(20, 0))
        self.wr_timeout_entry = Entry(
            wr_timeout_frame,
            bd=self.tk_format.bd,
            width=10,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        self.wr_timeout_entry.pack(side=LEFT, padx=(0, 20))
        self.wr_timeout_entry.insert(0, "8")

        optfailsafe_check_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        optfailsafe_check_frame.pack(pady=self.tk_format.pady,
                                     padx=(20, 5),
                                     fill=X,
                                     expand=True)
        self.optfailsafe_check = Checkbutton(
            optfailsafe_check_frame,
            fg=self.tk_format.textcolor,
            text="Prompt if the instrument has not been optimized.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            selectcolor=self.tk_format.check_bg,
            variable=self.optfailsafe,
        )
        self.optfailsafe_check.pack(side=LEFT)
        if self.optfailsafe.get():
            self.optfailsafe_check.select()

        opt_timeout_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        opt_timeout_frame.pack(pady=self.tk_format.pady,
                               fill=X,
                               expand=True,
                               padx=(20, 5))
        opt_timeout_label = Label(opt_timeout_frame,
                                  fg=self.tk_format.textcolor,
                                  text="Timeout (minutes):",
                                  bg=self.tk_format.bg)
        opt_timeout_label.pack(side=LEFT, padx=(20, 0))
        self.opt_timeout_entry = Entry(
            opt_timeout_frame,
            bd=self.tk_format.bd,
            width=10,
            bg=self.tk_format.entry_background,
            selectbackground=self.tk_format.selectbackground,
            selectforeground=self.tk_format.selectforeground,
        )
        self.opt_timeout_entry.pack(side=LEFT, padx=(0, 20))
        self.opt_timeout_entry.insert(0, "60")
        filler_label = Label(opt_timeout_frame,
                             bg=self.tk_format.bg,
                             fg=self.tk_format.textcolor,
                             text="              ")
        filler_label.pack(side=LEFT)

        angles_failsafe_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        angles_failsafe_frame.pack(pady=self.tk_format.pady,
                                   padx=(20, 5),
                                   fill=X,
                                   expand=True)
        self.angles_failsafe_check = Checkbutton(
            angles_failsafe_frame,
            fg=self.tk_format.textcolor,
            text="Check validity of emission and incidence angles.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            selectcolor=self.tk_format.check_bg,
            variable=self.angles_failsafe,
        )
        if self.angles_failsafe.get():
            self.angles_failsafe_check.select()

        label_failsafe_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        label_failsafe_frame.pack(pady=self.tk_format.pady,
                                  padx=(20, 5),
                                  fill=X,
                                  expand=True)
        self.label_failsafe_check = Checkbutton(
            label_failsafe_frame,
            fg=self.tk_format.textcolor,
            text="Require a label for each spectrum.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            selectcolor=self.tk_format.check_bg,
            variable=self.labelfailsafe,
        )
        self.label_failsafe_check.pack(pady=(6, 5), side=LEFT, padx=(0, 20))
        if self.labelfailsafe.get():
            self.label_failsafe_check.select()

        wr_angles_failsafe_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        wr_angles_failsafe_frame.pack(pady=self.tk_format.pady,
                                      padx=(20, 5),
                                      fill=X,
                                      expand=True)
        self.wr_angles_failsafe_check = Checkbutton(
            wr_angles_failsafe_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=
            "Require a new white reference at each viewing geometry             ",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.wr_angles_failsafe,
        )
        self.wr_angles_failsafe_check.pack(pady=(6, 5), side=LEFT)
        if self.wr_angles_failsafe.get():
            self.wr_angles_failsafe_check.select()

        wrap_frame = Frame(failsafe_frame, bg=self.tk_format.bg)
        wrap_frame.pack(pady=self.tk_format.pady,
                        padx=(20, 5),
                        fill=X,
                        expand=True)
        self.anglechangefailsafe_check = Checkbutton(
            wrap_frame,
            selectcolor=self.tk_format.check_bg,
            fg=self.tk_format.textcolor,
            text=
            "Remind me to check the goniometer if the viewing geometry changes.",
            bg=self.tk_format.bg,
            pady=self.tk_format.pady,
            highlightthickness=0,
            variable=self.anglechangefailsafe,
        )

        failsafes_ok_button = Button(failsafe_frame,
                                     text="Ok",
                                     command=self.settings_top.destroy)
        failsafes_ok_button.config(
            fg=self.tk_format.buttontextcolor,
            highlightbackground=self.tk_format.highlightbackgroundcolor,
            bg=self.tk_format.buttonbackgroundcolor,
            width=15,
        )
        failsafes_ok_button.pack(pady=self.tk_format.pady)
        self.settings_top.resizable(False, False)

    # If the user has failsafes activated, check that requirements are met. Always require a valid number of spectra.
    # Different requirements are checked depending on what the function func is that will be called next (opt, wr, take
    # spectrum, acquire)
    def check_optional_input(self,
                             func,
                             args: Optional[List] = None,
                             warnings: str = "") -> bool:
        if args is None:
            args = []
        label = warnings
        now = int(time.time())
        incidence = self.controller.incidence_entries[0].get()
        emission = self.controller.emission_entries[0].get()
        azimuth = self.controller.azimuth_entries[0].get()

        if self.controller.manual_automatic.get() == 0:
            # pylint: disable = comparison-with-callable
            warnings = self.controller.check_viewing_geom_for_manual_operation(
            )
            label += warnings

            if self.optfailsafe.get() and func != self.controller.opt:
                try:
                    opt_limit = int(
                        float(self.controller.opt_timeout_entry.get())) * 60
                except (ValueError, AttributeError):
                    opt_limit = sys.maxsize
                if self.controller.opt_time is None:
                    label += "The instrument has not been optimized.\n\n"
                elif now - self.controller.opt_time > opt_limit:
                    minutes = str(int((now - self.controller.opt_time) / 60))
                    seconds = str((now - self.controller.opt_time) % 60)
                    if int(minutes) > 0:
                        label += (
                            "The instrument has not been optimized for " +
                            minutes + " minutes " + seconds + " seconds.\n\n")
                    else:
                        label += "The instrument has not been optimized for " + seconds + " seconds.\n\n"
                if self.controller.opt_time is not None:
                    if self.controller.angles_change_time is None:
                        pass
                    elif self.controller.opt_time < self.controller.angles_change_time:
                        valid_i = utils.validate_int_input(
                            incidence, self.controller.min_science_i,
                            self.controller.max_science_i)
                        valid_e = utils.validate_int_input(
                            emission, self.controller.min_science_e,
                            self.controller.max_science_e)
                        valid_az = utils.validate_int_input(
                            azimuth, self.controller.min_science_az,
                            self.controller.max_science_az)
                        if valid_i and valid_e and valid_az:
                            label += "The instrument has not been optimized at this geometry.\n\n"

            if self.wrfailsafe.get(
            ) and func != self.controller.wr and func != self.controller.opt:
                try:
                    wr_limit = int(float(self.wr_timeout_entry.get())) * 60
                except (ValueError, AttributeError):
                    wr_limit = sys.maxsize
                if self.controller.wr_time is None:
                    label += "No white reference has been taken.\n\n"
                elif self.controller.opt_time is not None and self.controller.opt_time > self.controller.wr_time:
                    label += "No white reference has been taken since the instrument was optimized.\n\n"
                elif int(self.controller.instrument_config_entry.get()) != int(
                        self.controller.spec_config_count):
                    label += "No white reference has been taken while averaging this number of spectra.\n\n"
                elif self.controller.spec_config_count is None:
                    label += "No white reference has been taken while averaging this number of spectra.\n\n"
                elif now - self.controller.wr_time > wr_limit:
                    minutes = str(int((now - self.controller.wr_time) / 60))
                    seconds = str((now - self.controller.wr_time) % 60)
                    if int(minutes) > 0:
                        label += (" No white reference has been taken for " +
                                  minutes + " minutes " + seconds +
                                  " seconds.\n\n")
                    else:
                        label += " No white reference has been taken for " + seconds + " seconds.\n\n"
            if self.wr_angles_failsafe.get() and func != self.controller.wr:

                if self.controller.angles_change_time is not None and self.controller.wr_time is not None and func != self.controller.opt:
                    if self.controller.angles_change_time > self.controller.wr_time + 1:
                        valid_i = utils.validate_int_input(
                            incidence, self.controller.min_science_i,
                            self.controller.max_science_i)
                        valid_e = utils.validate_int_input(
                            emission, self.controller.min_science_e,
                            self.controller.max_science_e)
                        valid_az = utils.validate_int_input(
                            azimuth, self.controller.min_science_az,
                            self.controller.max_science_az)
                        if valid_i and valid_e and valid_az:
                            label += " No white reference has been taken at this viewing geometry.\n\n"

        if self.labelfailsafe.get(
        ) and func != self.controller.opt and func != self.controller.wr:
            if self.controller.sample_label_entries[
                    self.controller.current_sample_gui_index].get() == "":
                label += "This sample has no label.\n\n"
        for entry in self.controller.sample_label_entries:
            sample_label = entry.get()
            newlabel = self.controller.validate_sample_name(sample_label)
            if newlabel != sample_label:
                entry.delete(0, "end")
                if newlabel == "":
                    newlabel = "sample"

                entry.insert(0, newlabel)
                label += (
                    "'" + sample_label +
                    "' is an invalid sample label.\nSample will be labeled as '"
                    + newlabel + "' instead.\n\n")
                self.controller.log(
                    "Warning: '" + sample_label +
                    "' is an invalid sample label. Removing reserved characters and expressions."
                )

        if label != "":  # if we came up with errors
            title = "Warning!"

            buttons = {
                "yes": {
                    # if the user says they want to continue anyway, run take spectrum again but this time with
                    # override=True
                    func: args
                },
                "no": {},
            }
            label = "Warning!\n\n" + label
            label += "\nDo you want to continue?"
            Dialog(self.controller, title, label, buttons)
            return False
        # if there were no errors
        return True
Beispiel #37
0
varAgent = IntVar()

checkboxesFrame = LabelFrame(window,
                             text="Odabir polja:",
                             height=120,
                             width=600,
                             borderwidth=2,
                             relief="groove")
checkboxesFrame.place(x=205, y=0)

clientIPCheckbox = Checkbutton(checkboxesFrame,
                               text="IP klijenta",
                               variable=varClientIP,
                               command=SearchAndFilter)
clientIPCheckbox.grid(row=0, column=0)
clientIPCheckbox.select()

clientIDCheckbox = Checkbutton(checkboxesFrame,
                               text="ID korisnika",
                               variable=varClientID,
                               command=SearchAndFilter)
clientIDCheckbox.grid(row=1, column=0)
clientIDCheckbox.select()

usernameCheckbox = Checkbutton(checkboxesFrame,
                               text="Korisničko ime",
                               variable=varUsername,
                               command=SearchAndFilter)
usernameCheckbox.grid(row=2, column=0)
usernameCheckbox.select()
Beispiel #38
0
class Win2:
    def run(self):
        # Variable
        self.usbChoiceList = []
        self.startUpChoice = False
        # Main window
        self.win = Tk()
        self.win.title("Easy USB Backup")
        self.win.geometry('700x500')
        self.win.iconbitmap(path + 'material/a.ico')
        self.win.resizable(0, 0)
        self.win.option_add('*tearOff', False)

        #==================================================================================================
        # Menu functions
        def Control():
            # Variable
            self.config1 = 0
            self.config2 = 0
            # Control window
            self.conWin = Tk()
            self.conWin.title("控制中心")
            self.conWin.iconbitmap(path + 'material/a.ico')
            self.conWin.geometry("710x80")
            self.conWin.resizable(0, 0)
            # Label
            self.conl1 = Label(self.conWin,
                               text="检测时间间隔(s)",
                               font=('fangsong', 13))
            self.conl2 = Label(self.conWin,
                               text="备份文件夹命名方式",
                               font=('fangsong', 13))
            self.conl3 = Label(self.conWin,
                               text="检测到U盘插入时是否提示",
                               font=('fangsong', 13))
            # Entry
            self.cone1 = Entry(self.conWin, width=64)

            # Radiobutton functions
            def conr1f():
                if self.config1 != 0:
                    self.conrL1 = [
                        self.conr1, self.conr2, self.conr3, self.conr4
                    ]
                    self.conrL1[self.config1].deselect()
                    self.config1 = 0
                else:
                    self.conrL1[self.config1].select()

            def conr2f():
                if self.config1 != 1:
                    self.conrL1 = [
                        self.conr1, self.conr2, self.conr3, self.conr4
                    ]
                    self.conrL1[self.config1].deselect()
                    self.config1 = 1
                else:
                    self.conrL1[self.config1].select()

            def conr3f():
                if self.config1 != 2:
                    self.conrL1 = [
                        self.conr1, self.conr2, self.conr3, self.conr4
                    ]
                    self.conrL1[self.config1].deselect()
                    self.config1 = 2
                else:
                    self.conrL1[self.config1].select()

            def conr4f():
                if self.config1 != 3:
                    self.conrL1 = [
                        self.conr1, self.conr2, self.conr3, self.conr4
                    ]
                    self.conrL1[self.config1].deselect()
                    self.config1 = 3
                else:
                    self.conrL1[self.config1].select()

            def conr7f():
                if self.config2 != 0:
                    self.conrL2 = [self.conr7, self.conr8]
                    self.conrL2[self.config2].deselect()
                    self.config2 = 0
                else:
                    self.conrL2[self.config2].select()

            def conr8f():
                if self.config2 != 1:
                    self.conrL2 = [self.conr7, self.conr8]
                    self.conrL2[self.config2].deselect()
                    self.config2 = 1
                else:
                    self.conrL2[self.config2].select()

            # Checkbutton
            self.conr1 = Checkbutton(self.conWin, text="时间", command=conr1f)
            self.conr2 = Checkbutton(self.conWin, text="U盘名称", command=conr2f)
            self.conr3 = Checkbutton(self.conWin,
                                     text="时间+U盘名称",
                                     command=conr3f)
            self.conr4 = Checkbutton(self.conWin,
                                     text="U盘名称+时间",
                                     command=conr4f)
            self.conr7 = Checkbutton(self.conWin, text="是", command=conr7f)
            self.conr8 = Checkbutton(self.conWin, text="否", command=conr8f)

            # Button fuctions
            def apply():
                Log("Apply button is clicked")
                try:
                    self.time = int(self.cone1.get())
                    self.jsconfig = {
                        'time': self.time,
                        'config1': self.config1,
                        'config2': self.config2
                    }
                    with open(path + 'info/config.json',
                              encoding='utf-8') as fileConf:
                        fileConff = fileConf.readlines()
                    if fileConff == []:
                        with open(path + 'info/config.json',
                                  mode='w',
                                  encoding='utf-8') as f:
                            dump(self.jsconfig,
                                 f,
                                 indent=4,
                                 separators=(',', ':'))
                        if (messagebox.showinfo("控制中心", "应用成功")) == "ok":
                            self.conWin.destroy()
                    elif fileConff != []:
                        with open(path + 'info/config.json',
                                  encoding='utf-8') as f:
                            self.ff = load(f)
                        self.ff["time"] = self.time
                        self.ff['config1'] = self.config1
                        self.ff['config2'] = self.config2
                        with open(path + 'info/config.json',
                                  mode='w',
                                  encoding='utf-8') as f:
                            dump(self.ff, f, indent=4, separators=(",", ":"))
                        if (messagebox.showinfo("控制中心", "应用成功")) == "ok":
                            self.conWin.destroy()
                except:
                    messagebox.showerror("控制中心", "您输入的数据错误,或您打开了多个控制中心窗口.")

            def advice():
                Log("Advice button is clicked")
                self.cone1.delete(0, END)
                self.cone1.insert('insert', '2')
                self.conrL1 = [self.conr1, self.conr2, self.conr3, self.conr4]
                self.conrL1[self.config1].deselect()
                self.conr3.select()
                self.config1 = 2
                self.conrL2 = [self.conr7, self.conr8]
                self.conrL2[self.config2].deselect()
                self.conr8.select()
                self.config2 = 1

            # Button
            self.conb1 = Button(self.conWin,
                                text="应用",
                                relief=GROOVE,
                                width=7,
                                command=apply)
            self.conb2 = Button(self.conWin,
                                text="推荐设置",
                                relief=GROOVE,
                                width=7,
                                command=advice)
            # Display
            self.conl1.place(x=0, y=0)
            self.cone1.place(x=250, y=2)
            self.conl2.place(x=0, y=25)
            self.conr1.place(x=170, y=25)
            self.conr2.place(x=220, y=25)
            self.conr3.place(x=290, y=25)
            self.conr4.place(x=393, y=25)
            self.conl3.place(x=0, y=50)
            self.conr7.place(x=210, y=50)
            self.conr8.place(x=245, y=50)
            self.conb1.place(x=580, y=48)
            self.conb2.place(x=640, y=48)
            self.conWin.mainloop()
#==================================================================================================

        def About():
            # About window
            self.aboutwin = Toplevel()
            self.aboutwin.title("关于")
            self.aboutwin.geometry("300x200")
            self.aboutwin.resizable(0, 0)
            self.aboutwin.iconbitmap(path + 'material/a.ico')
            # Label
            self.aboutl1 = Label(self.aboutwin,
                                 text="Easy USB Backup",
                                 font=('Arial', 16))
            self.aboutl2 = Label(self.aboutwin,
                                 text="作者:Skyler Sun",
                                 font=('fangsong', 14))
            self.aboutl3 = Label(self.aboutwin,
                                 text="GUI设计:徐笳棋",
                                 font=('fangsong', 14))
            self.aboutl4 = Label(self.aboutwin,
                                 text="版本号:0-4",
                                 font=('fangsong', 14))
            # Display
            self.aboutl1.pack(side='top')
            self.aboutl2.place(x=15, y=30)
            self.aboutl3.place(x=15, y=55)
            self.aboutl4.place(x=15, y=80)
            self.aboutwin.mainloop()

#==================================================================================================
# Menu

        self.winMenubar = Menu(self.win)
        self.winmenu = Menu(self.winMenubar)
        self.winmenu.add_command(label="控制中心", command=Control)
        self.winmenu.add_command(label="关于", command=About)
        self.winMenubar.add_cascade(label="设置", menu=self.winmenu)
        self.win['menu'] = self.winMenubar
        # Background
        self.backgroundImg = PhotoImage(file=path + 'material/g.gif')
        self.canvas = Canvas(width=700,
                             height=480,
                             highlightthickness=0,
                             borderwidth=0)
        self.canvas.create_image(0, 0, image=self.backgroundImg, anchor='nw')
        # Label
        self.canvas.create_text(135,
                                25,
                                text="选择U盘(可移动DISK)",
                                font=('Arial', 17),
                                fill='red')
        self.canvas.create_text(70,
                                365,
                                text="备份位置",
                                font=('Arial Black', 17),
                                fill='red')
        self.canvas.create_text(590,
                                440,
                                text="By: Skyler Sun",
                                font=('Arial Black', 17),
                                fill='white')
        self.location = Label(self.win,
                              width=34,
                              height=1,
                              font=('fangsong', 17),
                              anchor='w')
        # Frame
        self.usbFrame = Frame(self.win)
        # Text
        self.usbText = Text(self.usbFrame, height=23, width=67)

        # Checkbutton fuctioins
        def usbAct(content):
            if content in self.usbChoiceList:
                self.usbChoiceList.remove(content)
                Log(content + " disk is removed")
            elif content not in self.usbChoiceList:
                Log(content + " disk is added")
                self.usbChoiceList.append(content)
            self.usbChoiceList.sort()
            with open(path + 'info/config.json', encoding='utf-8') as f:
                ff = f.readlines()
            if ff != []:
                with open(path + 'info/config.json', encoding='utf-8') as F:
                    i = load(F)
                i['usbChoiceList'] = str(self.usbChoiceList)
                with open(path + 'info/config.json',
                          mode='w',
                          encoding='utf-8') as F:
                    dump(i, F, indent=4, separators=(',', ':'))
                Log("USB Choice List: " + str(self.usbChoiceList))
            elif ff == []:
                self.dict = {"usbChoiceList": str(self.usbChoiceList)}
                with open(path + 'info/config.json',
                          mode='w',
                          encoding='utf-8') as F:
                    dump(self.dict, F, indent=4, separators=(",", ":"))

        def usbDf():
            usbAct('D')

        def usbEf():
            usbAct('E')

        def usbFf():
            usbAct('F')

        def usbGf():
            usbAct('G')

        def usbHf():
            usbAct('H')

        def usbIf():
            usbAct('I')

        def usbJf():
            usbAct('J')

        def usbKf():
            usbAct('K')

        def usbLf():
            usbAct('L')

        def usbMf():
            usbAct('M')

        def usbNf():
            usbAct('N')

        def usbOf():
            usbAct('O')

        def usbPf():
            usbAct('P')

        def usbQf():
            usbAct('Q')

        def usbRf():
            usbAct('R')

        def usbSf():
            usbAct('S')

        def usbTf():
            usbAct('T')

        def usbUf():
            usbAct('U')

        def usbVf():
            usbAct('V')

        def usbWf():
            usbAct('W')

        def usbXf():
            usbAct('X')

        def usbYf():
            usbAct('Y')

        def usbZf():
            usbAct('Z')

        # Checkbutton
        self.usbD = Checkbutton(self.usbText,
                                text="D盘",
                                bg='white',
                                command=usbDf)
        self.usbE = Checkbutton(self.usbText,
                                text="E盘",
                                bg='white',
                                command=usbEf)
        self.usbF = Checkbutton(self.usbText,
                                text="F盘",
                                bg='white',
                                command=usbFf)
        self.usbG = Checkbutton(self.usbText,
                                text="G盘",
                                bg='white',
                                command=usbGf)
        self.usbH = Checkbutton(self.usbText,
                                text="H盘",
                                bg='white',
                                command=usbHf)
        self.usbI = Checkbutton(self.usbText,
                                text="I盘",
                                bg='white',
                                command=usbIf)
        self.usbJ = Checkbutton(self.usbText,
                                text="J盘",
                                bg='white',
                                command=usbJf)
        self.usbK = Checkbutton(self.usbText,
                                text="K盘",
                                bg='white',
                                command=usbKf)
        self.usbL = Checkbutton(self.usbText,
                                text="L盘",
                                bg='white',
                                command=usbLf)
        self.usbM = Checkbutton(self.usbText,
                                text="M盘",
                                bg='white',
                                command=usbMf)
        self.usbN = Checkbutton(self.usbText,
                                text="N盘",
                                bg='white',
                                command=usbNf)
        self.usbO = Checkbutton(self.usbText,
                                text="O盘",
                                bg='white',
                                command=usbOf)
        self.usbP = Checkbutton(self.usbText,
                                text="P盘",
                                bg='white',
                                command=usbPf)
        self.usbQ = Checkbutton(self.usbText,
                                text="Q盘",
                                bg='white',
                                command=usbQf)
        self.usbR = Checkbutton(self.usbText,
                                text="R盘",
                                bg='white',
                                command=usbRf)
        self.usbS = Checkbutton(self.usbText,
                                text="S盘",
                                bg='white',
                                command=usbSf)
        self.usbT = Checkbutton(self.usbText,
                                text="T盘",
                                bg='white',
                                command=usbTf)
        self.usbU = Checkbutton(self.usbText,
                                text="U盘",
                                bg='white',
                                command=usbUf)
        self.usbV = Checkbutton(self.usbText,
                                text="V盘",
                                bg='white',
                                command=usbVf)
        self.usbW = Checkbutton(self.usbText,
                                text="W盘",
                                bg='white',
                                command=usbWf)
        self.usbX = Checkbutton(self.usbText,
                                text="X盘",
                                bg='white',
                                command=usbXf)
        self.usbY = Checkbutton(self.usbText,
                                text="Y盘",
                                bg='white',
                                command=usbYf)
        self.usbZ = Checkbutton(self.usbText,
                                text="Z盘",
                                bg='white',
                                command=usbZf)
        self.usbText.window_create('insert', window=self.usbD)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbE)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbF)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbG)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbH)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbI)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbJ)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbK)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbL)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbM)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbN)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbO)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbP)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbQ)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbR)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbS)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbT)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbU)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbV)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbW)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbX)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbY)
        self.usbText.insert('insert', '\n')
        self.usbText.window_create('insert', window=self.usbZ)
        # ScrollBar
        self.usbScrollBar = Scrollbar(self.usbFrame,
                                      width=20,
                                      orient='vertical')

        # Button fuction
        def throughf():
            self.copyTo = filedialog.askdirectory()
            with open(path + 'info/config.json', encoding='utf-8') as f:
                if f.readlines() == []:
                    with open(path + 'info/config.json',
                              mode='w',
                              encoding='utf-8') as F:
                        self.dict = {"copyTo": self.copyTo}
                        dump(self.dict, F, indent=4, separators=(",", ":"))
                else:
                    with open(path + 'info/config.json',
                              encoding='utf-8') as F:
                        self.dict = load(F)
                    self.dict["copyTo"] = self.copyTo
                    with open(path + 'info/config.json',
                              mode='w',
                              encoding='utf-8') as F:
                        dump(self.dict, F, indent=4, separators=(",", ":"))
            self.copyToPath.set(self.copyTo)

        def startUpButtonf():
            if self.startUpChoice == False:
                Popen(
                    'copy ' + winPath +
                    'startup\\startup.exe "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp"',
                    shell=True)
                with open('C:/Easy USB Backup Info.pyc', mode='w') as i:
                    i.write(winPath + "main.exe")
                Log("开机自启已选择")
                self.startUpText.set("开机自启")
                self.startUpChoice = True
            elif self.startUpChoice == True:
                Popen(
                    'del ' +
                    '"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\startup.exe"',
                    shell=True)
                Log("开机不自启已选择")
                self.startUpText.set("开机不自启")
                self.startUpChoice = False

        def Helpf():
            Log("Help window starts")
            # Help window
            self.helP = Toplevel()
            self.helP.geometry('500x318')
            self.helP.title('Easy USB Backup')
            self.helP.iconbitmap(path + 'material/a.ico')
            self.helP.resizable(0, 0)
            # Extensions
            self.helPBar = Scrollbar(self.helP, orient='vertical', width=20)
            self.helPText = Text(self.helP,
                                 width=68,
                                 yscrollcommand=self.helPBar.set)
            with open(path + 'material/h.pyc', encoding='utf-8') as file:
                helPContent = file.readlines()
            for i in helPContent:
                self.helPText.insert('insert', i)
            self.helPText.config(state='disabled')
            self.helPBar.config(command=self.helPText.yview)
            # Display
            self.helPText.place(x=0, y=0)
            self.helPBar.pack(side='right', fill='y')
            self.helP.mainloop()

        def Hidef():
            self.win.withdraw()
            messagebox.showinfo("Easy USB Backup", "窗口已隐藏,按下alt来还原窗口")

            def onPress(key):
                try:
                    i = []
                    i.append(str(key.char))
                    del i
                except AttributeError:
                    if str(key) == 'Key.alt_l':
                        self.win.deiconify()
                        listener.stop()

            def onRelease(key):
                pass

            listener = pynput.keyboard.Listener(on_press=onPress,
                                                on_release=onRelease)
            listener.start()

        def LogLook():
            Popen('"' + winPath + 'Easy USB Backup.log"', shell=True)

        def Killf():
            Popen('taskkill /f /im main.exe', shell=True)

        def BackupLook():
            try:
                i1 = -1
                i = list(self.copyTo)
                for I in i:
                    i1 += 1
                    if I == "/":
                        i[i1] = "\\"
                i = ''.join(i)
                del i1
                Popen('explorer ' + i, shell=True)
                del i
            except:
                messagebox.showerror("Easy USB Backup", "请先选择备份目录")

        def Startf():
            if messagebox.showinfo("Easy USB Backup",
                                   "   程序已开始, 请勿多次点击开始备份按钮") == 'ok':

                def BackupRun():
                    with open(path + 'info/config.json',
                              encoding='utf-8') as f:
                        q = f.readlines()
                    if q == []:
                        Log("Json file is empty")
                        messagebox.showerror("Easy USB Backup", "   设置错误   ")
                    else:
                        Log("Json file has items")
                        with open(path + 'info/config.json',
                                  encoding='utf-8') as f:
                            i = load(f)
                        order = 1
                        try:
                            time = i['time']
                            config1 = i['config1']
                            config2 = i['config2']
                            copyTo = i['copyTo']
                            usbChoiceList = list(i['usbChoiceList'])
                            order = 0
                        except:
                            Log("Json file is not currect")
                            messagebox.showerror("Easy USB Backup",
                                                 "   设置错误   ")
                        if list(copyTo)[-1] != '/':
                            copyTo += '/'
                        if order == 0:
                            usbChoiceList.remove('[')
                            usbChoiceList.remove(']')

                            # change list
                            def ChangeUSBList(content):
                                while True:
                                    try:
                                        usbChoiceList.remove(content)
                                    except ValueError:
                                        break

                            ChangeUSBList("'")
                            ChangeUSBList(',')
                            ChangeUSBList(' ')
                            # check usbchoicelist
                            uusbChoiceList = usbChoiceList[:]
                            localDisks = []
                            order = -1
                            ordeR = 0
                            for i in disk_partitions():
                                if "removable" not in i.opts:
                                    localDisks.append(i.mountpoint)
                            for i in usbChoiceList:
                                order += 1
                                uusbChoiceList[order] += ':\\'
                                usbChoiceList[order] += ':/'
                                if uusbChoiceList[order] in localDisks:
                                    a = Tk()
                                    a.withdraw()
                                    Log("USB choice is wrong")
                                    messagebox.showerror(
                                        "Easy USB Backup", "您选择的U盘有误, 请重新选择")
                                    a.destroy()
                                    ordeR = 1
                                    break
                            # Start to detect
                            if ordeR == 0:
                                # Variable
                                order1 = 1
                                copyedDevices = []
                                usbDevices = []
                                position1 = ''
                                position2 = ''

                                # thread function
                                def cpThf():
                                    if config2 == 0:
                                        if messagebox.showinfo(
                                                'Easy USB Backup',
                                                '检测到有U盘插入') == 'ok':
                                            copyedDevices.append(position1)
                                            copytree(position1, position2)
                                    elif config2 == 1:
                                        copyedDevices.append(position1)
                                        copytree(position1, position2)

                                while True:
                                    Log('Start to detect USB')
                                    devices = disk_partitions()
                                    for device in devices:
                                        if "removable" in device.opts:
                                            mountpoint = list(
                                                device.mountpoint)[0] + ':/'
                                            usbDevices.append(mountpoint)
                                            order1 = 0
                                    if copyedDevices != []:
                                        for i in copyedDevices:
                                            if i not in usbDevices:
                                                copyedDevices.remove(i)
                                    if order1 == 0:
                                        Log('Found USB')
                                        # copy starts
                                        for device in usbDevices:
                                            if (device in usbChoiceList) and (
                                                    device
                                                    not in copyedDevices):
                                                position1 = device
                                                ddevice = list(device)
                                                ddevice.pop()
                                                ddevice = ''.join(ddevice)
                                                wwinPath = list(winPath)
                                                wwinPath[0] = wwinPath[
                                                    0].upper()
                                                wwinPath = ''.join(wwinPath)
                                                Popen('vol ' + ddevice +
                                                      ' > ' + wwinPath +
                                                      'info\\name.pyc',
                                                      shell=True)
                                                sleep(3)
                                                # with open(path + 'info/name.pyc', encoding='unicode_escape') as f:
                                                with open(path +
                                                          'info/name.pyc',
                                                          encoding='gbk') as f:
                                                    usbname = list(
                                                        f.readlines()[0])
                                                usbName = []
                                                allow = -4
                                                for i in usbname:
                                                    if allow == 0:
                                                        if i != '\n':
                                                            usbName.append(i)
                                                    elif allow != 0:
                                                        if i == ' ':
                                                            allow += 1
                                                usbName = ''.join(usbName)
                                                if config1 == 0:
                                                    now = strftime(
                                                        '%Y-%m-%d  %H-%M-%S')
                                                    position2 = copyTo + now
                                                elif config1 == 1:
                                                    position2 = copyTo + usbName
                                                elif config1 == 2:
                                                    now = strftime(
                                                        '%Y-%m-%d  %H-%M-%S')
                                                    position2 = copyTo + now + ', ' + usbName
                                                elif config1 == 3:
                                                    now = strftime(
                                                        '%Y-%m-%d  %H-%M-%S')
                                                    position2 = copyTo + usbName + ', ' + now
                                                cpTh = Thread(target=cpThf,
                                                              daemon=True)
                                                cpTh.start()
                                    usbDevices.clear()
                                    Log('End detect')
                                    sleep(time)

                BackupTh = Thread(target=BackupRun, daemon=True)
                BackupTh.start()

        # Button
        self.through = Button(self.win,
                              text="浏览",
                              command=throughf,
                              relief=GROOVE,
                              width=8)
        self.startUpButton = Button(self.win,
                                    font=('fangsong', 15),
                                    relief=GROOVE,
                                    command=startUpButtonf,
                                    width=10)
        self.helpButton = Button(self.win,
                                 text="使用必读",
                                 relief=GROOVE,
                                 width=10,
                                 font=('fangsong', 15),
                                 command=Helpf)
        self.hideButton = Button(self.win,
                                 text="隐藏",
                                 relief=GROOVE,
                                 width=10,
                                 font=('fangsong', 15),
                                 command=Hidef)
        self.logButton = Button(self.win,
                                text="日志文件",
                                relief=GROOVE,
                                width=10,
                                font=('fangsong', 15),
                                command=LogLook)
        self.killButton = Button(self.win,
                                 text="结束任务",
                                 relief=GROOVE,
                                 width=10,
                                 font=('fangsong', 15),
                                 command=Killf)
        self.BackupButton = Button(self.win,
                                   text="备份目录",
                                   relief=GROOVE,
                                   width=10,
                                   font=('fangsong', 15),
                                   command=BackupLook)
        self.startButton = Button(self.win,
                                  text="开始备份",
                                  relief=GROOVE,
                                  width=10,
                                  font=('fangsong', 15),
                                  command=Startf)
        # Config
        self.usbText.config(state='disabled', cursor='arrow')
        self.usbText.configure(yscrollcommand=self.usbScrollBar.set)
        self.usbScrollBar.config(command=self.usbText.yview)
        # Display
        # StartUpButton
        self.startUpButton.place(x=540, y=50)
        self.startUpText = StringVar()
        self.startUpText.set("开机不自启")
        self.startUpButton.config(textvariable=self.startUpText)
        # Location
        self.location.place(x=19, y=380)
        self.copyToPath = StringVar()
        self.location.config(textvariable=self.copyToPath)
        # Others
        self.through.place(x=443, y=380)
        self.usbText.pack(side='left')
        self.usbScrollBar.pack(side='right', fill='y')
        self.canvas.place(x=0, y=0)
        self.usbFrame.place(x=19, y=45)
        self.helpButton.place(x=540, y=100)
        self.hideButton.place(x=540, y=150)
        self.logButton.place(x=540, y=200)
        self.killButton.place(x=540, y=250)
        self.BackupButton.place(x=540, y=300)
        self.startButton.place(x=540, y=350)
        # Loop
        self.win.mainloop()
        Log("=========Program ends=========")
Beispiel #39
0
class BattleshipsDemoClient(Frame):
    def __init__(self, tk, args):
        Frame.__init__(self, tk)
        # empty string for platform's default settings
        locale.setlocale(locale.LC_ALL, '')
        self.master = tk
        tk.title(APP_TITLE)
        tk.resizable(False, False)
        try:
            if WINDOWS:
                tk.iconbitmap("200x200/icon.ico")
            else:
                tk.iconbitmap("@200x200/icon.xbm")
        except Exception as e:
            print(e)
        atexit.register(self.cancel_game)

        # Init class data fields that we use for storing info that we need for using the API
        self.bot_id = None
        self.bot_password = None
        self.logged_in = False
        self.game_style_ids = []
        self.gameChips = 0
        self.gameDeals = 0
        self.gameStake = 0
        self.gamePrize = 0
        self.player_key = None
        self.play_again = BooleanVar()
        self.do_not_play_same_user = BooleanVar()
        self.close_after_game = False
        self.game_cancelled = False
        self.in_game = False

        self.topFrame = Frame(tk, padx=12, pady=12)
        self.middleFrame = Frame(tk, padx=12)
        self.middleFrameLeft = Frame(self.middleFrame)
        self.middleFrameRight = Frame(self.middleFrame)
        self.middleFrameRighter = Frame(self.middleFrame)

        self.topFrame.grid(row=0, sticky=W + E)

        self.middleFrame.grid(row=1, sticky=W)
        self.middleFrameLeft.grid(row=1, column=0)
        self.middleFrameRight.grid(row=1, column=1)
        self.middleFrameRighter.grid(row=1, column=2)

        # ===================================
        # Create form elements

        # Top Frame Elements
        self.botNameLabel = Label(self.topFrame, text="Bot Name:")
        self.bot_id_entry = Entry(self.topFrame)
        self.bot_id_entry.bind('<Return>', self.log_in_if_not)
        self.bot_id_entry.focus()
        self.passwordLabel = Label(self.topFrame, text="Password:"******"Login",
                                        command=self.log_in_out_clicked)

        self.balanceLabel = Label(self.topFrame, text="Bot Balance:")
        self.balance = Label(self.topFrame, text="0")
        self.close_button = Button(self.topFrame,
                                   text="Close",
                                   padx=2,
                                   command=tk.destroy)

        # Middle Frame Elements
        # Middle Frame LEFT Elements
        self.gameStyleLabel = Label(self.middleFrameLeft,
                                    font=(None, 18),
                                    pady=0,
                                    text="Game Style Selection")

        self.opponentLabel = Label(self.middleFrameLeft,
                                   text="Specify Opponent (optional):")
        self.specify_opponent_entry = Entry(self.middleFrameLeft)

        self.do_not_play_same_user_check = Checkbutton(
            self.middleFrameLeft,
            text='Don\'t play another bot in same user account as me',
            var=self.do_not_play_same_user)

        self.game_styles_listbox = Listbox(self.middleFrameLeft,
                                           background='#FFFFFF',
                                           height=8)
        self.game_styles_listbox.bind('<Double-1>',
                                      self.find_game_double_clicked)
        self.game_styles_listbox.bind(
            '<Return>', self.find_game_double_clicked
        )  # Not a double click but we want it to do the same thing

        self.refresh_game_styles_button = Button(
            self.middleFrameLeft,
            text="Refresh Game Styles",
            command=self.refresh_game_styles_clicked)

        self.thinkingTimeLabel = Label(self.middleFrameLeft,
                                       text="Add \"Thinking Time\" (ms):")
        self.thinking_time_entry = Entry(self.middleFrameLeft)

        self.auto_play_next_game_check = Checkbutton(
            self.middleFrameLeft,
            text='Play another game when complete',
            var=self.play_again)

        self.cancel_stop_game_button = Button(
            self.middleFrameLeft,
            text=CANCEL_GAME_TEXT,
            command=self.cancel_stop_game_clicked)
        self.find_game_button = Button(self.middleFrameLeft,
                                       text="Find Game",
                                       command=self.find_game_clicked)

        self.resultText = Message(
            self.middleFrameLeft,
            width=300,
            text="This is where the informational messages will appear")
        self.spacerLabel = Label(self.middleFrameLeft, text=" ")

        # Middle Frame RIGHT Elements

        self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title")
        self.gameTitleText = Text(self.middleFrameRight,
                                  height=3,
                                  background='white',
                                  spacing1=3,
                                  pady=0)

        self.player = battleships_visuals.BattleshipsVisuals(
            self.middleFrameRight)  # Game Display Table
        self.opponent = battleships_visuals.BattleshipsVisuals(
            self.middleFrameRight)  # Game Display Table
        self.gameActionLabel = Label(self.middleFrameRight, text="")

        # ===================================
        # Set initial element states

        self.set_gamestyle_controls_states(DISABLED)
        self.cancel_stop_game_button.config(state=DISABLED)
        self.game_styles_listbox.config(background='white')
        self.thinking_time_entry.insert(0, 100)
        self.gameTitleText.config(state=DISABLED)
        self.set_balance(0)
        self.gameTitleText.tag_configure("center", justify='center')
        self.gameTitleText.tag_configure("bold", font='-weight bold')

        # ===================================
        # Form Layout

        # Top Frame Form Layout
        self.topFrame.grid_rowconfigure(0, weight=1)
        self.botNameLabel.grid(row=0, column=0, sticky=E)
        self.bot_id_entry.grid(row=0, column=1, sticky=W)
        self.passwordLabel.grid(row=0, column=2, sticky=E)
        self.bot_password_entry.grid(row=0, column=3, sticky=W)
        self.log_in_out_button.grid(row=0, column=4, sticky=E)
        self.topFrame.grid_columnconfigure(5, weight=1)
        self.balanceLabel.grid(row=0, column=5, sticky=E)
        self.balance.grid(row=0, column=6, sticky=W)
        self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0))

        # Middle Frame Form Layout
        self.middleFrame.grid_rowconfigure(0, weight=1)
        self.gameStyleLabel.grid(row=0, column=0, columnspan=1, sticky=W + E)
        self.spacerLabel.grid(row=0, column=2, sticky=E)

        self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4)
        self.specify_opponent_entry.grid(row=2, column=0, sticky=E, pady=4)

        self.do_not_play_same_user_check.grid(row=3,
                                              column=0,
                                              columnspan=1,
                                              sticky='we',
                                              pady=4)
        self.game_styles_listbox.grid(row=4,
                                      column=0,
                                      columnspan=1,
                                      sticky='we',
                                      pady=4)
        self.find_game_button.grid(row=5, column=0, pady=4, sticky=W)
        self.refresh_game_styles_button.grid(row=5,
                                             column=0,
                                             columnspan=1,
                                             sticky='',
                                             pady=4)
        self.cancel_stop_game_button.grid(row=5, column=0, sticky=E)

        self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4)
        self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4)

        self.auto_play_next_game_check.grid(row=7,
                                            column=0,
                                            columnspan=1,
                                            sticky=W,
                                            pady=4)
        self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4)
        self.middleFrame.grid_columnconfigure(9, weight=1)

        self.gameTitleLabel.grid(row=0, column=3)
        self.gameTitleText.grid(row=0, column=3, columnspan=2)
        self.player.grid(row=1, column=3)
        self.opponent.grid(row=1, column=4)
        self.gameActionLabel.grid(row=11, column=3, sticky='w')

        if args.botid is not None:
            self.auto_play(args)

    def auto_play(self, args):
        self.bot_id_entry.insert(0, args.botid)
        self.bot_password_entry.insert(0, args.password)
        self.log_in_out_clicked()
        self.thinking_time_entry.insert(0, args.timeout)
        if args.playanothergame:
            self.auto_play_next_game_check.select()
        if args.dontplaysameuserbot:
            self.do_not_play_same_user_check.select()
        if args.closeaftergame:
            self.close_after_game = True
        i = 0
        for i in range(self.game_styles_listbox.size()):
            if args.gamestyle in str(self.game_styles_listbox.get(i)):
                break
        self.game_styles_listbox.select_set(i, i)
        self.find_game_clicked()

    def log_in_out_clicked(self):
        """Click handler for the 'Login'/'Logout' button."""

        # This means we're logging out
        if self.logged_in:
            self.resultText.config(text='Logged Out')

            self.master.title(APP_TITLE + " (Not Logged In)")

            self.cancel_game()

            self.bot_id = 'housebot-competition'
            self.bot_password = None
            self.clear_game_title_text()
            self.gameActionLabel.config(text="")
            self.reset_game_styles_listbox()
            self.clear_all_boards()
            self.opponent.delete("all")

            self.log_in_out_button.config(text='Login')

            self.set_login_controls_states(ENABLED)
            self.set_gamestyle_controls_states(DISABLED)

            self.logged_in = False
            self.bot_password_entry.delete(0, 'end')
            self.set_balance(0)

        # This means we're logging in
        else:
            self.bot_id = self.bot_id_entry.get()
            self.bot_password = '******'

            res = self.get_list_of_game_styles()
            if res['Result'] == 'SUCCESS':
                self.resultText.config(text='Logged In')

                game_styles = res['GameStyles']
                self.master.title(self.bot_id + " - " + APP_TITLE)

                self.set_login_controls_states(DISABLED)
                self.set_gamestyle_controls_states(ENABLED)

                self.set_game_styles_listbox(game_styles)
                self.set_balance(res['Balance'])

                self.log_in_out_button.config(text='Logout')

                self.logged_in = True

            else:
                messagebox.showerror(
                    'Error',
                    'Invalid login attempt. Please check the username and password entered.'
                )

    def log_in_if_not(self, _):
        if not self.logged_in:
            self.log_in_out_clicked()

    def clear_all_boards(self):
        self.player.delete("all")
        self.opponent.delete("all")
        self.player.myBoard = None
        self.opponent.oppBoard = None

    def set_in_game(self, value):
        self.in_game = value

    def set_game_title_text(self, text, tag):
        self.gameTitleText.config(state=ENABLED)
        self.gameTitleText.insert("end", text, ("center", tag))
        self.gameTitleText.config(state=DISABLED)

    def clear_game_title_text(self):
        self.gameTitleText.config(state=ENABLED)
        self.gameTitleText.delete("1.0", "end")
        self.gameTitleText.config(state=DISABLED)

    def set_login_controls_states(self, state):
        self.bot_id_entry.config(state=state)
        self.bot_password_entry.config(state=state)

    def set_gamestyle_controls_states(self, state):
        self.specify_opponent_entry.config(state=state)
        self.do_not_play_same_user_check.config(state=state)
        self.game_styles_listbox.config(state=state)
        self.find_game_button.config(state=state)
        self.refresh_game_styles_button.config(state=state)
        self.auto_play_next_game_check.config(state=state)
        self.thinking_time_entry.config(state=state)
        self.opponentLabel.config(state=state)
        self.thinkingTimeLabel.config(state=state)
        self.balanceLabel.config(state=state)
        self.balance.config(state=state)
        self.gameStyleLabel.config(state=state)
        self.game_styles_listbox.config(state=state)
        self.player.config(state=state)
        self.opponent.config(state=state)

    def set_balance(self, balance):
        """Set the balance field"""
        self.balance['text'] = int_with_commas(balance)
        self.balance['text'] += ' sat'

    def get_list_of_game_styles(self):
        """Get list of game styles from the server."""

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'GameTypeId': BATTLESHIPS_GAME_TYPE_ID
        }

        url = BASE_URL + GET_LIST_OF_GAME_STYLES_EXTENSION

        return BattleshipsDemoClient.make_api_call(url, req)

    def set_game_styles_listbox(self, game_styles):
        """Set the content of the game styles listbox with a list of GameStyle dictionaries.
        Keyword Arguments:
        game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles().
        """
        self.reset_game_styles_listbox()
        for index, game_style in enumerate(game_styles):
            self.game_styles_listbox.insert(
                index,
                GAME_STYLE_LISTBOX_TEXT.format(
                    game_style['GameStyleId'], game_style['Stake'],
                    game_style['GameTypeSpecificInfo']['Ships'],
                    game_style['GameTypeSpecificInfo']['Board Size'],
                    game_style['GameTypeSpecificInfo']['Timeout ms'],
                    game_style['GameTypeSpecificInfo']['DealsTotal'],
                    game_style['GameTypeSpecificInfo']['PercentageLand'],
                    game_style['GameTypeSpecificInfo']['RandomLand']))
            self.game_style_ids.append(game_style['GameStyleId'])

            # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION)

    def reset_game_styles_listbox(self):
        """Clear the content of the game styles listbox."""

        if self.game_styles_listbox.size() != 0:
            self.game_styles_listbox.delete(0, 'end')

            self.game_style_ids = []

    def refresh_game_styles_clicked(self):
        """Click handler for the 'Refresh Game Styles' button."""

        res = self.get_list_of_game_styles()
        game_styles = res['GameStyles']
        self.set_game_styles_listbox(game_styles)

    def find_game_clicked(self):
        """Click handler for the 'Find Game' button"""

        self.find_game_button.config(state=DISABLED)
        self.cancel_stop_game_button.config(state=ENABLED)
        self.clear_all_boards()

        # Here we dispatch the work to a separate thread, to keep the GUI responsive.
        if not MAC:
            threading.Thread(target=self.game_loop, daemon=True).start()
        else:
            self.game_loop()  # Doesn't work on MACs

    def find_game_double_clicked(self, _):
        self.find_game_clicked()

    def game_loop(self):
        """Loop through finding and playing games."""

        while True:
            self.clear_all_boards()
            self.find_game()
            if self.game_cancelled:
                break
            self.play_game()
            if self.close_after_game:
                self.close_button.invoke()
            if self.game_cancelled:
                break
            if not self.play_again.get():
                break

        self.find_game_button.config(state=ENABLED)
        self.cancel_stop_game_button.config(state=DISABLED,
                                            text=CANCEL_GAME_TEXT)
        self.game_cancelled = False

    def find_game(self):
        """Find a game."""

        offer_game_res = self.offer_game()

        if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD':
            self.cancel_stop_game_clicked()
            if 'ErrorMessage' in offer_game_res and offer_game_res[
                    'ErrorMessage'] == 'Check of OpponentId failed':
                self.resultText.config(text='Invalid Opponent ID')
            else:
                self.resultText.config(text='Invalid login or password')
        elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE':
            self.cancel_stop_game_clicked()
            self.resultText.config(text='Insufficient balance')
        elif offer_game_res['Result'] == 'BOT_IS_INACTIVE':
            self.cancel_stop_game_clicked()
            self.resultText.config(text='Bot is inactive')
        else:
            self.player_key = offer_game_res['PlayerKey']
            if offer_game_res['Result'] == 'WAITING_FOR_GAME':
                self.wait_for_game()

    def offer_game(self):
        """Offer a game."""

        opponent_id = self.specify_opponent_entry.get()
        if len(opponent_id) == 0:
            opponent_id = None
        try:
            game_style_id = self.game_style_ids[int(
                self.game_styles_listbox.curselection()[0])]
        except IndexError:
            self.game_styles_listbox.select_set(
                GAME_STYLE_LISTBOX_DEFAULT_SELECTION)
            game_style_id = self.game_style_ids[0]

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'MaximumWaitTime': 1000,
            'GameStyleId': game_style_id,
            'DontPlayAgainstSameUser': self.do_not_play_same_user.get(),
            'DontPlayAgainstSameBot': False,
            'OpponentId': opponent_id
        }
        url = BASE_URL + OFFER_GAME_EXTENSION

        return BattleshipsDemoClient.make_api_call(url, req)

    def wait_for_game(self):
        """Wait for game to start."""
        self.resultText.config(text='Waiting for game')
        while True:
            if self.game_cancelled:
                self.cancel_game()
                self.find_game_button.config(state=ENABLED)
                self.cancel_stop_game_button.config(state=DISABLED,
                                                    text=CANCEL_GAME_TEXT)
                break
            poll_results = self.poll_for_game_state()

            if poll_results['Result'] == 'SUCCESS':
                break
            if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[
                    'Result'] == 'GAME_HAS_ENDED' or poll_results[
                        'Result'] == 'GAME_WAS_STOPPED':
                self.game_cancelled = True
            time.sleep(2)

    def play_game(self):
        """Play a game."""
        self.resultText.config(text='Playing game')
        self.in_game = True

        poll_results = self.poll_for_game_state()

        if poll_results["Result"] != "SUCCESS":
            return

        game_state = poll_results['GameState']

        title = format('Game ID: ' + str(game_state['GameId']))
        game_style_details = self.game_styles_listbox.get('active').split(
            " | ")
        title += format(' / Style: ' + str(self.game_style_ids[int(
            self.game_styles_listbox.curselection()[0])]))
        title += format(' / Land: ' + game_style_details[6].split(" ")[2] +
                        '%')
        title += format(' / Deals: ' + game_style_details[5].split(" ")[1])
        title += format(' / ' + game_style_details[7])
        title += "\n"
        versus = format(self.bot_id + ' vs ' + game_state['OpponentId'])

        self.clear_game_title_text()
        self.set_game_title_text(title, "")
        self.set_game_title_text(versus, "bold")

        self.middleFrame.update()

        while True:
            if self.game_cancelled:
                break

            if game_state['IsMover']:
                self.resultText.config(text='Playing Game - Your Turn')
                move = battleships_move.calculateMove(game_state)
                move_results = self.make_move(move)

                if move_results['Result'] == 'INVALID_MOVE':
                    self.resultText.config(text="Invalid Move")
                elif move_results['Result'] != 'SUCCESS':
                    self.resultText.config(text='Game has ended: ' +
                                           move_results['Result'])
                    print("Game ended")
                    break
                else:
                    game_state = move_results['GameState']
            else:
                self.resultText.config(text="Playing Game - Opponent's Turn")

                # ---- Code here will be called on your opponent's turn ----

                # ----------------------------------------------------------

                poll_results = self.poll_for_game_state()

                if poll_results['Result'] != 'SUCCESS':
                    self.resultText.config(text='Game has ended: ' +
                                           poll_results['Result'])
                    break
                game_state = poll_results['GameState']

            if game_state['GameStatus'] != 'RUNNING':
                break

            self.middleFrameRight.update()

            try:
                if int(self.thinking_time_entry.get()) > 0:
                    time.sleep((int(self.thinking_time_entry.get()) / 1000))
                else:
                    time.sleep(0.1)
            except ValueError:
                time.sleep(0.1)

        self.set_in_game(False)

    def make_move(self, move):
        """Make a move."""

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'PlayerKey': self.player_key,
            'Move': move
        }
        url = BASE_URL + MAKE_MOVE_EXTENSION

        result = BattleshipsDemoClient.make_api_call(url, req)

        if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[
                'Result']:
            print(result)
            try:
                self.player.draw_game_state(result['GameState'], True)
                self.opponent.draw_game_state(result['GameState'], False)
            except Exception as e:
                print("Gamestate error: " + str(e))

        return result

    def poll_for_game_state(self):
        """Poll the server for the latest GameState."""

        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'MaximumWaitTime': 1000,
            'PlayerKey': self.player_key
        }
        url = BASE_URL + POLL_FOR_GAME_STATE_EXTENSION

        result = BattleshipsDemoClient.make_api_call(url, req)
        if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[
                'Result']:
            self.player.draw_game_state(result['GameState'], True)
            self.opponent.draw_game_state(result['GameState'], False)

        return result

    def cancel_stop_game_clicked(self):
        self.game_cancelled = True
        self.cancel_game()
        self.find_game_button.config(state=ENABLED)
        self.cancel_stop_game_button.config(state=DISABLED,
                                            text=CANCEL_GAME_TEXT)

    def cancel_game(self):
        if self.player_key is None:
            return
        req = {
            'BotId': self.bot_id,
            'BotPassword': self.bot_password,
            'PlayerKey': self.player_key
        }

        url = BASE_URL + CANCEL_GAME_OFFER_EXTENSION
        BattleshipsDemoClient.make_api_call(url, req)
        try:
            self.resultText.config(text='Cancelled game')
        except Exception as e:
            print(str(e) + " -- resultText Message object no longer exists")

    @staticmethod
    def make_api_call(url, req):
        """Make an API call."""
        while True:
            try:
                res = requests.post(url,
                                    json=req,
                                    headers=API_CALL_HEADERS,
                                    timeout=60.0)
                try:
                    jres = res.json()
                    if 'Result' in jres:
                        return jres
                    time.sleep(0.1)
                except ValueError:
                    time.sleep(0.1)
            except requests.ConnectionError:
                time.sleep(0.1)
            except requests.Timeout:
                time.sleep(0.1)
            except requests.HTTPError:
                time.sleep(0.1)
            except BaseException as e:  # Bad code but needed for testing purposes
                print(e)
                time.sleep(0.1)
class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name

    # 设置界面
    def set_init_window(self):

        self.init_window_name.title('word文档查询工具_v1.0')
        # self.init_window_name.geometry('1068x681+10+10')
        # self.init_window_name.columnconfigure (0, weight=1)
        self.init_window_name.resizable(0,0)

        # -------------------搜索目录选择设置----------------------------------
        


        self.init_data_label = Label(self.init_window_name,text = '搜索目录:')
        self.init_data_label.grid(row=0, column=0,sticky=W)

        v = StringVar(self.init_window_name, value='D:\\')
        # self.init_data_entry = Entry(self.init_window_name, width = 62, textvariable = v)
        # self.init_data_entry = Entry(self.init_window_name, textvariable = v, width=self.init_window_name.winfo_screenwidth())
        self.init_data_entry = Entry(self.init_window_name, textvariable = v)
        # self.init_data_Text.grid(row=0, column=1, rowspan=10, columnspan=10)
        self.init_data_entry.grid(row=0, column=1, columnspan=9,sticky=NSEW)

        
        # -------------------搜索关键字选择设置----------------------------------



        self.init_key_label = Label(self.init_window_name,text = '搜索关键字:')
        self.init_key_label.grid(row=1, column=0,sticky=W)
               
        # self.init_key_entry = Entry(self.init_window_name, width = 62)
        self.init_key_entry = Entry(self.init_window_name)
        # self.init_data_Text.grid(row=0, column=1, rowspan=10, columnspan=10)
        self.init_key_entry.grid(row=1, column=1, columnspan=9,sticky=NSEW)
        

        # -------------------搜索结果框表设置----------------------------------
        self.result_data_label = Label(self.init_window_name, text="搜索结果:")
        self.result_data_label.grid(row=3, column=0,sticky=W)
        # self.result_data_Text = Listbox(self.init_window_name, width=75, height=20, selectmode=MULTIPLE)  #处理结果展示
        self.result_data_Text = Listbox(self.init_window_name, height=20)  #处理结果展示
        # self.result_data_Text = Listbox(self.init_window_name, width=75, height=20)  #处理结果展示
        # self.result_data_Text.grid(row=2, column=12, rowspan=15, columnspan=10)
        self.result_data_Text.grid(row=4, columnspan=10,sticky=NSEW)
        
        # 为listbox双击绑定事件
        self.result_data_Text.bind("<Button-2>",self.openword)
        # self.result_data_Text.bind("  <<ListboxSelect>>",self.openword)
      
        # -------------------搜索日志框表设置----------------------------------
        self.log_label = Label(self.init_window_name, text="搜索日志")
        self.log_label.grid(row=5, column=0,sticky=W)
        # self.log_data_Text = Text(self.init_window_name, width=75, height=9)  # 日志框
        self.log_data_Text = scrolledtext.ScrolledText(self.init_window_name, height=9)  # 日志框
        # self.log_data_Text.grid(row=4, column=0, columnspan=10)
        self.log_data_Text.grid(row=6, columnspan=10,sticky=NSEW)


        # -------------------搜索选择项框表设置----------------------------------


        self.v_reload = IntVar()
        self.reload_set = Checkbutton(self.init_window_name, text = '重加载选项',variable = self.v_reload)
        self.reload_set.grid(row=2,column=0,sticky=NSEW)
        self.reload_set.select()
        
        self.v_debug_set = IntVar()
        self.debug_set = Checkbutton(self.init_window_name, text = '调试模式',variable = self.v_debug_set)
        self.debug_set.grid(row=2,column=1, columnspan=1,sticky=NSEW)
        self.debug_set.select()
        

        self.v_smart_mode_set = IntVar()
        self.smart_mode_set = Checkbutton(self.init_window_name, text = '智能联想模式',variable = self.v_smart_mode_set)
        self.smart_mode_set.grid(row=2,column=2,sticky=NSEW)


        self.smart_child_length_set = Label(self.init_window_name,text = '智能联想最短字符串:')
        self.smart_child_length_set.grid(row=2, column=3,sticky=NSEW)             
        # self.smart_child_length_set_entry = Entry(self.init_window_name, width = 20)
        self.smart_child_length_set_entry = Entry(self.init_window_name)
        # self.init_data_Text.grid(row=0, column=1, rowspan=10, columnspan=10)
        self.smart_child_length_set_entry.grid(row=2, column=4, columnspan=5,sticky=NSEW)
        

        self.search_start_button = Button(self.init_window_name, text = '开始检索', command = self.thread_it)
        self.search_start_button.grid(row=2,column=9,sticky=NSEW)
        
        
        # self.init_window_name.columnconfigure (0, weight=1)
    
    # 单击搜寻到的结果后打开文件,在此处添加打开文件的函数
    def openword(self, event):
        
        index_select = self.result_data_Text.curselection()[-1]
        # 此处有bug,需要实时更新双击项目情况
        value = self.result_data_Text.get(index_select)
        # print(index_select)
        # print(value)
        # self.result_data_Text.curselection().clear()
        wordapp = wc.Dispatch('Word.Application')
        doc = wordapp.Documents.Open(value.strip())
    
    # 设置线程,避免界面卡死情况
    def thread_it(self,*args):
        

        t = Thread(target=self.button_Click)

        t.setDaemon(True) 
        # 启动
        t.start()
        # 阻塞--卡死界面!
        # t.join()





    def button_Click(self):
        sleep(0.1)
        self.result_data_Text.delete(0,END)
        self.log_data_Text.delete('1.0','end')


        self.information_from_form = namedtuple('information_from_form', ['alwaysload', 'debugmode', 'smartmode', 'childlength', 'searchpath', 'keyword'])
        # 获取搜索输入的目录信息
        self.information_from_form.searchpath = self.init_data_entry.get()
        # 获取搜索输入的检索关键字信息
        self.information_from_form.keyword = self.init_key_entry.get()
        # 获取搜索输入的是否重加载复选框信息
        self.information_from_form.alwaysload = self.v_reload.get()
        # 获取搜索输入的是否开启调试模式信息
        self.information_from_form.debugmode = self.v_debug_set.get()
        # 获取搜索输入的是否启动智能搜索模式信息
        self.information_from_form.smartmode = self.v_smart_mode_set.get()
        # 获取搜索输入的子串搜索长度信息
        self.information_from_form.childlength = self.smart_child_length_set_entry.get()
        
        # 如果没有输入搜索目录,或搜索关键字,则弹出错误,并退出
        if (not self.information_from_form.searchpath):

            tkinter.messagebox.showwarning('警告','请输入搜索目录')
            return

        if (not self.information_from_form.keyword):
            tkinter.messagebox.showwarning('警告','请输入搜索关键字')
            return 
        # 获取窗口内容,并进行搜索
        instance = Searcher(self)   # 若Config.ini中未进行配置, 则采用默认搜索值

        instance.Translate()