示例#1
0
    def _init_ui(self):
        """Initializes all the UI elements."""
        self.pack(fill='both', expand=True)

        button_frame = Frame(self)
        button_frame.pack(fill='x', padx=5, pady=5)
        clear_button = Button(button_frame,
                              textvariable=self.clear_text,
                              command=self.on_clear)
        clear_button.pack(side='left')
        step_button = Button(button_frame,
                             textvariable=self.step_text,
                             command=self.on_step)
        end_button = Button(button_frame,
                            textvariable=self.end_text,
                            command=self.on_end)
        end_button.pack(side='right')
        step_button.pack(side='right')

        grid_frame = Frame(self, style=styles.GRID_FRAME)
        self.subgrids = _build_3x3_grid(grid_frame, SubGrid)
        for subgrid in self.subgrids:
            boxes = _build_3x3_grid(subgrid, Box)
            for box in boxes:
                self.boxes[box.position] = box
        grid_frame.pack(fill='both', padx=5, expand=True)

        status_bar = Label(self, textvariable=self.status_text)
        status_bar.pack(fill='x', padx=5, pady=5)
示例#2
0
    def __init__(self, url):
        self.url = url

        self.root = Tk()
        self.root.title("验证码")

        while True:
            try:
                image_bytes = urlopen(self.url).read()
                break
            except socket.timeout:
                print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                continue
            except urllib.error.URLError as e:
                if isinstance(e.reason, socket.timeout):
                    print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                    continue
        # internal data file
        data_stream = io.BytesIO(image_bytes)
        # open as a PIL image object
        self.pil_image = Image.open(data_stream)
        # convert PIL image object to Tkinter PhotoImage object
        self.tk_image = ImageTk.PhotoImage(self.pil_image)
        self.label = Label(self.root, image=self.tk_image, background='brown')
        self.label.pack(padx=5, pady=5)
        self.button = Button(self.root, text="刷新验证码", command=self.refreshImg)
        self.button.pack(padx=5, pady=5)

        randCodeLable = Label(self.root, text="验证码:")
        randCodeLable.pack(padx=5, pady=5)
        self.randCode = Entry(self.root)
        self.randCode.pack(padx=5, pady=5)

        self.loginButton = Button(self.root, text="登录", default=tkinter.ACTIVE)
        self.loginButton.pack(padx=5, pady=5)
示例#3
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.master.title("Listbox")

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

        acts = ['Monkey', 'Tiger', 'Dog', 'Rabbit', 'Dark', 'House']
        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<Animal>>", self.on_select)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def on_select(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)
示例#4
0
    def initItems(self):
        """Initialize all widgets here"""
        # First way to create a frame
        frame = Frame(self)
        frame['padding'] = (5, 10)
        frame['borderwidth'] = 2
        frame['relief'] = 'sunken'
        frame.pack(fill='both')
        lbl = Label(frame, text='sunken!')
        lbl.pack()
        lbl2 = Label(frame, text='_2!')
        lbl2.pack()

        # The second way to create a frame
        frame2 = Frame(self, borderwidth=2,
                       relief='raised')  # or constant tkinter.RAISED
        frame2.pack(fill='both')
        Label(frame2, text='raised').grid(row=1, column=1, sticky='w')
        Label(frame2, text='2col 2row').grid(row=2, column=2, sticky='we')
        Label(frame2,
              text='3col 3row',
              relief='raised',
              anchor='center',
              wraplength=50,
              width='7').grid(row=3, column=3, columnspan=2, sticky='we')
        Label(frame2, text='5col 5row').grid(row=4, column=5, sticky='e')

        # The first way to create a separator - with Frame
        sep1 = Frame(self, height=2, borderwidth=1, relief='sunken')
        sep1.pack(fill=X, padx=5, pady=10)
        Label(self, text='Between the separators').pack()
        # The second way to create a Separator - with tkinter.ttk.Separator
        sep = Separator(self, orient=tkinter.HORIZONTAL)
        sep.pack(fill=X, padx=5, pady=10)
示例#5
0
    def initUI(self):
        self.parent.title("COMPILADOR")
        self.pack(fill=BOTH, expand=True)
        global value
        value = 0
        global expr
        expr = StringVar()
        global res
        res = StringVar()

        frame1 = Frame(self)
        frame1.pack(fill=X)

        lbl1 = Label(frame1, text="FUNCION APPLY :", width=18)
        lbl1.pack(side=TOP, padx=5, pady=5)

        entry1 = Entry(frame1, textvariable=expr)
        entry1.pack(fill=Y, padx=5, expand=True)

        frame3 = Frame(self)
        frame3.pack(fill=Y)

        btnplus = Button(frame3,
                         text="VALIDAR",
                         width=8,
                         command=self.validar,
                         bg="green")
        btnplus.pack(side=TOP, anchor=N, padx=8, pady=5)
示例#6
0
    def buttonbox(self):
        self.top_frame = Frame(self)
        self.bottom_frame = Frame(self)
        self.top_frame.pack(side="top", fill="both", expand=False)
        self.bottom_frame.pack(side="bottom", fill="both", expand=False)
        self.bottom_right_frame = Frame(self.bottom_frame)
        self.bottom_left_frame = Frame(self.bottom_frame)
        self.bottom_right_frame.pack(side="right", fill="both", expand=True)
        self.bottom_left_frame.pack(side="left", fill="both", expand=True)

        l = Label(self.top_frame, text=convert65536(self.title))
        l.pack()

        w = Button(self.bottom_left_frame,
                   text="Open link",
                   width=10,
                   command=self.open,
                   default="active")
        w.pack(side="right", padx=10, pady=5)
        w = Button(self.bottom_right_frame,
                   text="Close",
                   width=10,
                   command=self.close)
        w.pack(side="left", padx=10, pady=5)

        self.bind("<Return>", self.open)
        self.bind("<Escape>", self.close)
示例#7
0
 class DateWidget(Frame):
     """Gets a date from the user."""
     def __init__(self, master):
         """Make boxes, register callbacks etc."""
         Frame.__init__(self, master)
         self.label = Label(self, text="När är du född?")
         self.label.pack()
         self.entry_text = StringVar()
         self.entry_text.trace("w", lambda *args: self.onEntryChanged())
         self.entry = Entry(self, width=date_entry_width,
              textvariable=self.entry_text)
         self.entry.insert(0, "ÅÅÅÅ-MM-DD")
         self.entry.pack(pady=small_pad)
         self.button = Button(self, text="Uppdatera",
              command=lambda: self.onDateChanged())
         self.button.pack()
         self.entry.focus_set()
         self.entry.select_range(0, END)
         self.entry.bind("<Return>", lambda x: self.onDateChanged())
     def setListener(self, pred_view):
         """Select whom to notify when a new date is entered."""
         self.pred_view = pred_view
     def onDateChanged(self):
         """Notifies the PredictionWidget that the date has been changed."""
         try:
             date = datetime.datetime.strptime(self.entry.get(),
                  "%Y-%m-%d").date()
             self.pred_view.update(date)
         except ValueError:
             self.entry.configure(foreground="red")
     def onEntryChanged(self):
         """Reset the text color."""
         self.entry.configure(foreground="")
示例#8
0
	def initUI(self):
		self.style = Style()
		self.style.theme_use("default")
		self.master.title("Analysis App - TEST")
		self.pack(fill=BOTH, expand=True)
		self.w2vmodel = None


		frame1 = Frame(self)
		frame1.pack(fill=X)
		browse_button = Button(frame1, text="Browse...",command=self.get_filename)
		browse_button.pack(side=RIGHT,padx=5,pady=5)
		file_path = Label(frame1,textvariable=self.directory)
		file_path.pack(side=LEFT,padx=5,pady=5)

		frame2 = Frame(self)
		frame2.pack(fill=X)
		keyword_label = Label(frame2,text="Keyword:")
		keyword_label.pack(side=LEFT,padx=5,pady=5)
		self.keyword_box = Entry(frame2)
		self.keyword_box.pack(fill=X,padx=5,pady=5)


		frame4 = Frame(self)
		frame4.pack(fill=BOTH,expand=True)
		quitButton = Button(frame4, text='Quit',command=self.quit_func)
		quitButton.pack(side=RIGHT, padx=5, pady=5)
		analyze_button = Button(frame4,text='Get analysis',command=self.get_analysis)
		analyze_button.pack(side=RIGHT,padx=5,pady=5)
示例#9
0
class StatusBar(TagReaderListener):
    def __init__(self, master):
        super().__init__()
        self.label = Label(master, text='', anchor=W)
        self.label.pack()
        self.index = 0
        self.expected_count = 0

    def start_task(self, text):
        self.label['text'] = text + "..."

    def task_complete(self):
        self.label['text'] += 'Done'

    def read_complete(self, elapsed_time):
        self.set("{} files read in {} milliseconds".format(self.expected_count, round(elapsed_time, 2)))

    def read_start(self, count):
        self.expected_count = count
        self.index = 0
        self.set("Reading tags in {} files".format(self.expected_count))

    def file_read(self, file):
        self.index += 1
        percent = round(100 * self.index / self.expected_count, 2)
        self.set("Reading tags in {} files: {}%".format(self.expected_count, percent))

    def counting_files(self):
        self.set("Counting files...")

    def set(self, text: str):
        self.label['text'] = text
示例#10
0
    def initUI(self):

        self.master.title("KST_from_rubric")
        self.pack(fill=BOTH, expand=True)

        frame1 = Frame(self)
        frame1.pack(fill=X)

        btn_ks = Button(frame1, text="Complexity", command=self.browse_file_ks)
        btn_ks.pack(side=LEFT, padx=5, pady=5)

        self.e_ks = Entry(frame1)
        self.e_ks.pack(fill=X, padx=5, expand=True)

        frame3 = Frame(self, height=330)
        frame3.pack(fill=X)
        frame3.pack_propagate(False)

        lbl3 = Label(frame3, text="KS", width=10)
        lbl3.pack(side=LEFT, anchor=N, padx=5, pady=5)

        self.txt_diff = Text(frame3)
        self.txt_diff.pack(fill=X, padx=5, expand=True)

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

        btn_construct = Button(frame4,
                               text="Construct",
                               command=self.construct_diff)
        btn_construct.pack(side=RIGHT)
    def initUI(self):

        self.master.title("Length Calc")
        self.pack(fill=BOTH, expand=True)

        frame1 = Frame(self)
        frame1.pack(fill=X)

        lbl1 = Label(frame1, text="x Value", width=8)
        lbl1.pack(side=LEFT, padx=5, pady=10)

        self.entry1 = Entry(frame1, textvariable=self.output1)
        self.entry1.pack(fill=X, padx=5, expand=True)

        frame2 = Frame(self)
        frame2.pack(fill=X)

        lbl2 = Label(frame2, text="y Value", width=8)
        lbl2.pack(side=LEFT, padx=5, pady=10)

        self.entry2 = Entry(frame2)
        self.entry2.pack(fill=X, padx=5, expand=True)

        frame3 = Frame(self)
        frame3.pack(fill=X)

        btn = Button(frame3, text="Calc", command=self.onClick)
        btn.pack(padx=10, pady=10)
示例#12
0
class Example(Frame):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.master.title("ListBox Application")
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlet Johansson', 'Rachel', 'Jessica Alba', 'Van Disel']

        lb = Listbox(self)

        for actress in acts:
            lb.insert(END, actress)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)
示例#13
0
class IncomeSummary(Frame, MoneyObserver):
    def __init__(self, parent):

        super().__init__(parent)
        self.initUI()

        self.income = 0
        self.subscription = 0

    def initUI(self):

        self.incomelbl = Label(self, text="Income: $0", font=("Ubuntu", 18))
        self.incomelbl.pack()
        self.availlbl = Label(self, text="Available: $0", font=("Ubuntu", 18))
        self.availlbl.pack()

        self.pack()

    def moneyUpdate(self, monies):
        self.income += monies.get("income", 0)
        self.subscription += monies.get("subscription", 0)
        self.updateText()

    def updateText(self):
        self.incomelbl["text"] = f"Income: ${self.income:.2f}"
        self.availlbl[
            "text"] = f"Available: ${self.income-self.subscription:.2f}"

    def reset(self):
        self.income = 0
        self.subscription = 0
        self.updateText()
示例#14
0
    def _setup_widgets(self):
        s = "Corona-Scraper"
        msg = Label(wraplength="4i",
                    justify="left",
                    anchor="n",
                    padding=(10, 2, 10, 6),
                    text=s)
        msg.pack(fill='x')
        topf = Frame()
        topf.pack(pady=10)
        refreshb = Button(topf, text="Refresh", command=refreshData)
        refreshb.pack(side=LEFT, padx=10)
        global modeb, themeb
        modeb = Button(topf, text="Widget Mode", command=changeMode)
        modeb.pack(side=LEFT, padx=10)
        themeb = Button(topf, text="Dark Mode", command=changeTheme)
        themeb.pack(side=LEFT, padx=10)
        exitb = Button(topf, text="Exit", command=exitAppGui)
        exitb.pack(side=RIGHT, padx=10)

        container = Frame()
        container.pack(fill='both', expand=True)
        # create a treeview with dual scrollbars
        self.tree = Treeview(columns=country_header, show="headings")
        vsb = Scrollbar(orient="vertical", command=self.tree.yview)
        hsb = Scrollbar(orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)
        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)
示例#15
0
    class test_gui(tk.Tk):
        def __init__(self, args, picker_type):
            tk.Tk.__init__(self)
            self.picker_type = picker_type
            self.title("test")
            self.geometry(f"{WIDTH}x{HEIGHT}")
            f = Frame(self)
            f.pack(expand=1, fill="both")
            self.l = Label(f, anchor="center")
            self.l.pack(side="top", expand=1, fill="both")
            if args.file:
                text = "Pick a file!"
            elif args.dir:
                text = "Pick a folder!"
            else:  #Not used
                text = "Pick something!"

            Button(
                f,
                text=text,
                command=lambda: threader.add_thread(self.get_input
                                                    )  #Lambda function to 
            ).pack(expand=0, side="bottom")

        def get_input(self):
            dialog = self.picker_type(self)  #Make the dialog window
            selection = dialog.get_input()  #
            self.l.configure(text=selection)
示例#16
0
    def _generateList(self):

        self.boxFrame = Frame(self, borderwidth=1)
        self.uiList = []

        for entry in self.subs:
            entryFrame = Frame(self.boxFrame, borderwidth=1)
            var = IntVar()
            var.set(1 * (self.record.get(entry, 0) > 0))
            button = Checkbutton(entryFrame, variable=var, command=self.update)
            button.pack(side=LEFT)

            self.subs[entry] = (self.subs[entry][0], var)

            lbl = Label(entryFrame, text=entry, font=("Ubuntu", 10))
            lbl.pack(side=LEFT)
            amtlbl = Label(entryFrame,
                           text=f"${self.subs[entry][0]}",
                           font=("Ubuntu", 10))
            amtlbl.pack(side=RIGHT)
            entryFrame.pack(fill=X)
            self.uiList.append(entryFrame)

        self.totallbl = Label(self.boxFrame, text="$0", font=("Ubuntu", 14))
        self.totallbl.pack(side=RIGHT)
        self.boxFrame.pack(side=LEFT, fill=BOTH)
示例#17
0
def on_button():
    if entry.get() == "42":
        slabel = Label(root, text="You guessed right!")
        slabel.pack()
    else:
        tlabel = Label(root, text="")
        tlabel.pack()
示例#18
0
    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(
            self,
            borderwidth=2,
            relief='sunken',
        )
        entrylabel = Label(frame,
                           anchor='w',
                           justify='left',
                           text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()

        buttons = Frame(self)
        self.button_ok = Button(buttons, text='Ok', width=8, command=self.ok)
        self.button_cancel = Button(buttons,
                                    text='Cancel',
                                    width=8,
                                    command=self.cancel)

        frame.pack(side='top', expand=True, fill='both')
        entrylabel.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side='bottom')
        self.button_ok.pack(side='left', padx=5)
        self.button_cancel.pack(side='right', padx=5)
示例#19
0
class labeledEntry(Frame):
	def __init__(self, text, *args, **kwargs):
		Frame.__init__(self, *args, **kwargs)
		self.label = Label(self, text = text)
		self.label.pack(side = 'left', expand = 0, fill = 'both', padx =2)
		self.entry = Entry(self)
		self.entry.pack(side = 'right', expand = 0, fill = 'both', padx = 2)
示例#20
0
class ContactFieldsView(Frame):
    """View displaying editable fields of a single contact."""
    def __init__(self, master, **kwargs):
        """
        Creates fields view layout and controls,
        binds entries to variables.

        :param master: application root window
        """
        super().__init__(master, **kwargs)

        # Bound field variables
        self.first_name = StringVar()
        self.surname = StringVar()
        self.phone = StringVar()
        self.email = StringVar()

        self.console_text = StringVar()

        # Displaying values and handling entries
        fields = Frame(self)
        for i, (field_name, field_var) in enumerate(
                zip(["First name:", "Surname:", "Phone:", "Email:"],
                    [self.first_name, self.surname, self.phone, self.email])):
            label = Label(fields, text=field_name)
            entry = Entry(fields, textvariable=field_var)

            label.grid(row=i, column=0, sticky=W)
            entry.grid(row=i, column=1, sticky=E)

        # Controls
        self.back_btn = Button(self, text="Back")
        self.submit_btn = Button(self, text="Submit")
        self.console = Label(self, textvariable=self.console_text)

        # Layout
        fields.pack()
        self.console.pack()
        self.back_btn.pack(side=LEFT)
        self.submit_btn.pack(side=RIGHT)

    def set_values(self, first_name="", surname="", phone="", email=""):
        """
        Displays given values in entries - used in edit view;
        clears console.
        """
        for arg_val, var in zip(
            [first_name, surname, phone, email],
            [self.first_name, self.surname, self.phone, self.email]):
            var.set(arg_val)
        self.log()

    def get_values(self):
        """Returns entries values as a tuple."""
        return (self.first_name.get(), self.surname.get(), self.phone.get(),
                self.email.get())

    def log(self, message=''):
        """Writes message on the console."""
        self.console_text.set(message)
示例#21
0
class AskElement(Toplevel):
    def __init__(self, window, callback):
        super(AskElement, self).__init__(window)
        self.window = window
        self.callback = callback

        self.clabel = Label(self,
                            text="Entrez le type de l'élément :",
                            font=("Arial", "14"))
        self.combo = Combobox(self, values=ELEMENTS)
        self.elabel = Label(self,
                            text="Entrez le nom de l'élément :",
                            font=("Arial", "14"))
        self.entry = Entry(self)
        self.button = Button(self, text="Valider", command=self.valide)

        self.combo.current(0)

        self.clabel.pack(padx=10, pady=10)
        self.combo.pack(padx=10, pady=7)
        self.elabel.pack(padx=10, pady=17)
        self.entry.pack(padx=10, pady=0)
        self.button.pack(padx=10, pady=7)

        self.title("Ajouter Element")

    def valide(self):
        name = self.entry.get()
        type_ = ELEMENTS[self.combo.current()]
        if name != "":
            self.callback(name, type_)
            self.destroy()
示例#22
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, name="frame")
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Animation")
        self.pack(fill=BOTH, expand=True)
        self.i = 0
        self.img_names = ("one.png", "two.png", "three.png", "four.png",
                          "five.png", "six.png", "seven.png", "eight.png",
                          "nine.png")
        img = Image.open(self.img_names[self.i])
        num = ImageTk.PhotoImage(img)
        self.label = Label(self, image=num)
        self.label.pack(pady=30)
        # reference must be stored
        self.label.image = num
        self.after(DELAY, self.doCycle)

    def doCycle(self):
        self.i += 1
        if (self.i >= 9):
            return
        img = ImageTk.PhotoImage(Image.open(self.img_names[self.i]))
        self.label.configure(image=img)
        self.label.image = img
        self.after(DELAY, self.doCycle)
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.hintLabel = Label(self, text='请输入需要计算的运算符:')
        self.hintLabel.pack()
        self.nameInput = Entry(self)
        self.nameInput.pack()
        self.alertButton = Button(self, text='计算', command=self.reduce)
        self.alertButton.pack()
        self.resultLabel = Label(self, text='')
        self.resultLabel.pack()

    def reduce(self):
        name = self.nameInput.get() or ''
        if name == '':
            messagebox.showinfo('提示', '请输入运算')
            return
        try:
            self.resultLabel["text"] = "输出结果:" + str(eval(name))
        except:
            messagebox.showinfo('警告', "肥仔别闹")
示例#24
0
class Form(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent

        self.parent.title("Example Form")
        self.pack(fill=BOTH, expand=True)

        f = Frame(self)
        f.pack(fill=X)

        l = Label(f, text='First Name', width=10)
        l.pack(side=LEFT, padx=5, pady=5)
       
        self.firstName = Entry(f)
        self.firstName.pack(fill=X, padx=5, expand=True)
        
        f = Frame(self)
        f.pack(fill=X)
        
        l = Label(f, text='Last Name', width=10)
        l.pack(side=LEFT, padx=5, pady=5)

        self.lastName = Entry(f)
        self.lastName.pack(fill=X, padx=5, expand=True)
        
        f = Frame(self)
        f.pack(fill=X)

        l = Label(f, text='Full Name', width=10)
        l.pack(side=LEFT, padx=5, pady=5)

        self.fullName = Label(f, text='ALEX POOPKIN', width=10)
        self.fullName.pack(fill=X, padx=5, expand=True)

        f = Frame(self)
        f.pack(fill=X)

        l = Label(f, text='', width=10)
        l.pack(side=LEFT, padx=5, pady=0)

        self.errorMessage = Label(f, text='Invalid character int the name!', foreground='red', width=30)
        self.errorMessage.pack(fill=X, padx=5, expand=True)

        f = Frame(self)
        f.pack(fill=X)

        b = Button(f, text='Close', command=lambda : self.parent.quit())
        b.pack(side=RIGHT, padx=5, pady=10)
        b['default'] = ACTIVE
        b.focus_set()

        self.clearButton = Button(f, text='Clear')
        self.clearButton.pack(side=RIGHT, padx=5, pady=10)
        self.clearButton['state'] = DISABLED

        self.sendButton = Button(f, text='Send')
        self.sendButton.pack(side=RIGHT, padx=5, pady=10)
示例#25
0
class SpanWidget:

    def __init__(self, master, db, span_id):
        self.widget = Frame(master)
        self.db = db
        self.span_id = span_id

        self.start_entry = SpanStartEntry(self)
        self.start_entry.widget.pack(side=tk.LEFT)

        self.elapsed_label = Label(self.widget)
        self.elapsed_label.pack(side=tk.LEFT)

        self.tag_entry = SpanTagEntry(self)
        self.tag_entry.widget.pack(side=tk.LEFT, fill=tk.X)

        self.refresh()

    def refresh(self):
        self.start_entry.refresh()
        self.tag_entry.refresh()
        next_span = self.db.get_next_span(self.span_id)
        if next_span is None:
            self.elapsed_label['text'] = 'ongoing'
        else:
            secs = next_span.started - self.db.get_span(self.span_id).started
            self.elapsed_label['text'] = str(timedelta(seconds=secs))
示例#26
0
def graph_report(window, data):
    """ графическое представление результатов """
    global df, cmb

    df = data

    graph = Toplevel(window)
    graph.title('Графическое представление')
    graph.minsize(width=400, height=200)

    choose_box = Frame(graph)
    lbl = Label(choose_box, text='Выбор параметра')
    lbl.pack(side=LEFT, anchor=W, padx=10, pady=10)

    cmb = Combobox(choose_box, values=list(df.index), width=35)
    cmb.current(0)
    cmb.pack(side=LEFT, anchor=W, padx=10, pady=10)

    choose_box.pack(anchor=S, padx=10, pady=10)

    fig = Figure(figsize=(5, 4), dpi=100)
    make_fig(fig, cmb.current())
    canvas = FigureCanvasTkAgg(fig, master=graph)
    canvas.draw()
    canvas.get_tk_widget().pack(side=BOTTOM, fill=BOTH, expand=1)

    cmb.bind('<<ComboboxSelected>>', lambda event, canvas=canvas, ax=fig: change_canvas(event, canvas, ax))

    toolbar = NavigationToolbar2Tk(canvas, graph)
    toolbar.update()
    canvas.get_tk_widget().pack(fill=BOTH, expand=1)
示例#27
0
class StopwatchView(Frame):
    """
    Provides an interface for the controller to the GUI code.
    """

    WINDOW_TITLE = "PyTimer"

    def __init__(self, root, controller):
        super().__init__(root)

        self.controller = controller
        self.stopwatch_label_var = StringVar()

        self._create()
        self._arrange()

    def _create(self):
        self.timer_label = Label(self,
                                 textvariable=self.stopwatch_label_var,
                                 font=("Arial", 36))
        self.timer_label.bind(
            "<Button-1>", lambda event: self.controller.set_time_callback())

        self.toggle = Button(self,
                             text="Start/Stop",
                             command=self.controller.toggle_callback)

        self.reset = Button(self,
                            text="Reset",
                            command=self.controller.reset_callback)

    def _arrange(self):
        self.timer_label.pack(fill=X, expand=NO)
        self.toggle.pack(fill=X)
        self.reset.pack(fill=X)
示例#28
0
    def _setup_widgets(self):
        msg = Label(
            wraplength="4i",
            justify="left",
            anchor="n",
            padding=(10, 2, 10, 6),
            text=("Ttk is the new Tk themed widget set. One of the widgets it "
                  "includes is a tree widget, which can be configured to "
                  "display multiple columns of informational data without "
                  "displaying the tree itself. This is a simple way to build "
                  "a listbox that has multiple columns. Clicking on the "
                  "heading for a column will sort the data by that column. "
                  "You can also change the width of the columns by dragging "
                  "the boundary between them."))
        msg.pack(fill='x')

        container = Frame()
        container.pack(fill='both', expand=True)

        # XXX Sounds like a good support class would be one for constructing
        #     a treeview with scrollbars.
        self.tree = Treeview(columns=tree_columns,
                             show="headings",
                             style='font.Treeview')
        vsb = Scrollbar(orient="vertical", command=self.tree.yview)
        hsb = Scrollbar(orient="horizontal", command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)

        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)
示例#29
0
    def initUI(self):

        self.entries = {}
        self.date = datetime.now()
        titleFrame = Frame(self, borderwidth=1)
        titleFrame.pack(fill=BOTH, expand=True)

        lbl = Label(titleFrame, text="Debits:", font=("Ubuntu", 20))
        lbl.pack(side=LEFT)

        dateFrame = Frame(self, borderwidth=1)
        lButton = Button(dateFrame, text="<-", command=self.decrementDay)
        lButton.pack(side=LEFT)
        self.dateLbl = Label(dateFrame, text="", font=("Ubuntu", 12))
        self.dateLbl.pack(side=LEFT)
        rButton = Button(dateFrame, text="->", command=self.incrementDay)
        rButton.pack(side=LEFT)
        dateFrame.pack(fill=BOTH, expand=True)

        entryFrame = Frame(self, borderwidth=1)

        for data in [("Amount", 5), ("Desc", 20)]:
            dataFrame = Frame(entryFrame, borderwidth=2)
            lbl = Label(dataFrame, text=data[0], font=("Ubuntu", 10))
            lbl.pack()
            entry = Entry(dataFrame, width=data[1])
            entry.pack()
            self.entries[data[0]] = entry

            dataFrame.pack(side=LEFT)

        okButton = Button(entryFrame, text="Submit", command=self.submitDebit)
        okButton.pack(side=LEFT)
        entryFrame.pack(fill=BOTH, expand=True)
        self.pack(fill=BOTH, expand=False)
示例#30
0
def main():

    root = Tk()
    root.geometry("250x85+1250+650")
    app = Example()

    frame1 = Frame(root)
    frame1.pack(fill=BOTH)

    lbl1 = Label(frame1, text="Enter today's work")
    lbl1.pack(fill=X, padx=5, pady=5)

    frame2 = Frame(root)
    frame2.pack(fill=BOTH)

    entry1 = Entry(frame2)
    entry1.pack(fill=X, padx=5, expand=True)
    entry1.focus_set()

    def callback():
        print(entry1.get())
        print_values(entry1.get())
        write_into_workbook(entry1.get())

    frame3 = Frame(root)
    frame3.pack(fill=BOTH, expand=True)

    subbtn = Button(frame3, text="Done", command=callback)
    subbtn.place(x=4,y=5)

    root.mainloop()
示例#31
0
class Example(Frame):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.master.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

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

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.pack(side=LEFT, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=LEFT)

    def onScale(self, val):

        v = int(float(val))
        self.var.set(v)
示例#32
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ["Scarlett Johansson", "Rachel Weiss", "Natalie Portman", "Jessica Alba", "Angelina jolie", "Emma Stone", "Sandra Bullock", "Julia Roberts",
        "Jennifer Lawrence", "Mila Kunis", "Jennifer Aniston", "Charlize Theron", "Cameron Diaz", "Nicole Kidman", "Meryl Streep", "Reese Witherspoon"]

        lb = Listbox(self, selectmode="multiple")
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)
        self.var.set(value)
示例#33
0
 def insert_entry_field(self, txt):
     frame = Frame(self.frame)
     frame.pack(fill="x")
     label = Label(frame, text=txt, width=6)
     label.pack(side="left", anchor="n", padx=5, pady=5)
     entry = Entry(frame)
     entry.pack(fill="x", padx=5, pady=5, expand=True)
     self.entries["Entry"][txt] = entry
示例#34
0
class Main(Frame):
    """Main class for our browser.
        Note that we inherit from Frame, making this a Frame object.
    """
    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.master.title("Browser")
        self.header = {"User-Agent":"Tkinter Browser 0.1"}

        # Here we make our widgets.
        self.top_frame = Frame(self)
        self.url_frame = Frame(self.top_frame)
        self.url_label = Label(self.url_frame, text="Url: ", anchor="n")
        self.url_entry = Entry(self.url_frame, width=80)
        self.url_button = Button(self.url_frame, text="Go", command=self.go_button)
        self.bottom_frame = Frame(self)
        self.text_field = Text(self.bottom_frame)

        #Here we pack our widgets.
        self.top_frame.pack(side="top", padx=15, pady=15)
        self.url_frame.pack(anchor="center")
        self.bottom_frame.pack(side="bottom", fill="both", expand=True)
        self.text_field.pack(side="bottom", fill="both", expand=True)
        self.url_label.pack(side="left")
        self.url_entry.pack(side="left", fill="x", expand=True)
        self.url_button.pack(side="left", padx=5)
        self.text_field.config(state="disabled", padx=5, pady=5)

    def go_button(self):
        url = self.url_entry.get()
        if url:
            if "http://" not in url:
                url = "http://"+url
            page_text = self.get_page(url)
            self.text_field.config(state="normal")
            self.text_field.delete(1.0, "end")
            self.text_field.insert("end", page_text)
            self.text_field.config(state="disable")

    def get_page(self, url):
        s = requests.Session()
        resp = s.get(url, headers=self.header)
        data = resp.text
        soup = bs(data, "html.parser")
        page_text = soup.find_all(text=True)
        page_text = filter(self.visible, page_text)
        return "".join([str(i)+'\n' for i in page_text])


    def visible(self, e):
        if e.parent.name in ('style', 'script', '[document]', 'head', 'title'):
            return False
        elif re.match('<!--.*-->', str(e.encode('utf-8'))):
            return False
        return True
示例#35
0
 def insert_text_field(self, txt, default=None):
     frame = Frame(self.frame)
     frame.pack(fill="x")
     label = Label(frame, text=txt, width=6)
     label.pack(side="left", anchor="n", padx=5, pady=5)
     entry = Text(frame)
     entry.pack(fill="both", pady=5, padx=5, expand=True)
     if default:
         entry.insert("end", default)
     self.entries["Text"][txt] = entry
示例#36
0
文件: query.py 项目: abalkin/cpython
    def create_widgets(self):
        super().create_widgets()
        frame = self.frame
        pathlabel = Label(frame, anchor="w", justify="left", text="Help File Path: Enter URL or browse for file")
        self.pathvar = StringVar(self, self.filepath)
        self.path = Entry(frame, textvariable=self.pathvar, width=40)
        browse = Button(frame, text="Browse", width=8, command=self.browse_file)

        pathlabel.pack(anchor="w", padx=5, pady=3)
        self.path.pack(anchor="w", padx=5, pady=3)
        browse.pack(pady=3)
示例#37
0
 def insert_entry_field(self, txt, default=None, focus=False):
     frame = Frame(self.frame)
     frame.pack(fill="x")
     label = Label(frame, text=txt, width=6)
     label.pack(side="left", anchor="n", padx=5, pady=5)
     entry = Entry(frame)
     entry.pack(fill="x", padx=5, pady=5, expand=True)
     if default:
         entry.insert("end", default)
     if focus:
         entry.focus_force()
     self.entries["Entry"][txt] = entry
示例#38
0
文件: ui.py 项目: fi-ka/DartScore
    def initUI(self, mainFrame):
        """initialize the User Interface"""
        
        # styles
        style = Style()
        style.configure("GRN.TLabel", background="#ACF059")
        style.configure("GRN.TFrame", background="#ACF059")
        style.configure("BLK.TFrame", background="#595959")
        
        
        # create top frame
        topFrame = Frame(mainFrame, style="GRN.TFrame", padding=8)
        topFrame.pack(fill=BOTH, side=TOP)
        
        # create black border
        borderFrame = Frame(mainFrame, style="BLK.TFrame")
        borderFrame.pack(fill=BOTH, side=TOP)
        
        # create add player frame
        addPlayerFrame = Frame(mainFrame, padding=8)
        addPlayerFrame.pack(side=TOP)
        
        # create text field for add button
        self.nameFieldVar = StringVar()
        self.playerNameEntry = Entry(addPlayerFrame, textvariable = self.nameFieldVar)
        self.playerNameEntry.pack(side=LEFT)
        # create add player button
        addButton = Button(addPlayerFrame, text="Add player")
        addButton.pack(side=LEFT)
        
        # create choose game list
        self.currentGame = StringVar()
        self.currentGame.set(self.gameList[0])
        gameDropDown = OptionMenu(mainFrame, self.currentGame, self.gameList[0], *self.gameList)
        gameDropDown.pack(side=TOP)

        # create start game button
        startGameButton = Button(mainFrame, text="Start")
        
        startGameButton.bind("<Button-1>", self.startGame)
        startGameButton.pack(side=TOP)
        
        # create label and set text
        self.playerString = StringVar()
        self.playerString.set(self.buildPlayerHeaderString())
        headerLabel = Label(topFrame, textvariable=self.playerString, style="GRN.TLabel")
        headerLabel.pack(side=TOP)     
        addButton.bind("<Button-1>", self.onAddPlayerClick)
        self.playerNameEntry.bind("<Key>", self.onAddPlayerEnter)
        
        #set focus
        self.playerNameEntry.focus()
示例#39
0
 def __init__(self, master, **kwargs):
     super(Merge, self).__init__(master, **kwargs)
     warning = Label(self, font=('a', 7), wraplength=300, justify='center', text=_('Warning: This tool should only be used to merge GEDCOM files from this software. If you use other GEDCOM files, the result is not guaranteed.'))
     self.files_to_merge = FilesToMerge(self)
     self.btn_add_file = Button(self, text=_('Add files'), command=self.add_files)
     buttons = Frame(self, borderwidth=20)
     self.btn_quit = Button(buttons, text=_('Quit'), command=self.quit)
     self.btn_save = Button(buttons, text=_('Merge'), command=self.save)
     warning.pack()
     self.files_to_merge.pack()
     self.btn_add_file.pack()
     self.btn_quit.pack(side='left', padx=(0, 40))
     self.btn_save.pack(side='right', padx=(40, 0))
     buttons.pack(side='bottom')
示例#40
0
文件: query.py 项目: xulukai/cpython
    def create_widgets(self):  # Call from override, if any.
        frame = Frame(self, borderwidth=2, relief="sunken")
        label = Label(frame, anchor="w", justify="left", text=self.message)
        self.entry = Entry(frame, width=30)  # Bind name for entry_ok.
        self.entry.focus_set()

        buttons = Frame(self)  # Bind buttons for invoke in unittest.
        self.button_ok = Button(buttons, text="Ok", width=8, command=self.ok)
        self.button_cancel = Button(buttons, text="Cancel", width=8, command=self.cancel)

        frame.pack(side="top", expand=TRUE, fill="both")
        label.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side="bottom")
        self.button_ok.pack(side="left", padx=5)
        self.button_cancel.pack(side="right", padx=5)
示例#41
0
 def get_info(self):
     x, y = (self.size[0]/2, self.size[1]/2)
     for i in self.info:
         label_frame= LabelFrame(self, text="name")
         label_frame.pack(fill="y")
         for entry in self.info[i]["Entry"]:
             frame = Frame(label_frame)
             frame.pack(fill="x")
             label = Label(label_frame, text=self.info[i]["Entry"][entry], width=6)
             label.pack(side="left", anchor="n", padx=5, pady=5)
         for text in self.info[i]["Text"]:
             frame = Frame(label_frame)
             frame.pack(fill="x")
             label = Label(label_frame, text=self.info[i]["Text"][text], width=6)
             label.pack(side="left", anchor="n", padx=5, pady=5)
     window = self.canvas.create_window(x, y, window=label_frame, tag="test")
示例#42
0
    def initUI(self):
        # Initialize and name Window
        self.parent.title("Poly Pocket")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        def new_baseline():

            return
        def old_baseline():
            return
        def test(baseline):
            return
        def spark_connect():
            return
        def leap_connect():
            return
        def quit():
            self.parent.destroy()
            return

        welcome = "Welcome to Poly Pocket!"
        welcome_label = Label(self, text=welcome, font=("Helvetica", 24))
        welcome_label.place(x=5, y=5)
        welcome_label.pack()
        
        baseline_button = Button(self, text="New Baseline",
                command=new_baseline())
        recover_baseline_button = Button(self, text="Recover Baseline",
                command=old_baseline())
        test_button = Button(self, text="Conduct Test",
                command=test(self.baseline))
        connect_leap_button = Button(self, text="Establish Leap Connection",
                command=leap_connect)
        connect_spark_button = Button(self, text="Establish Spark Connection",
                command=spark_connect)
        exit_button = Button(self, text="Quit",
                command=quit)
        
        baseline_button.place(relx=0.5, rely=0.3, anchor=CENTER)
        recover_baseline_button.place(relx=0.5, rely=0.4, anchor=CENTER)
        test_button.place(relx=0.5, rely=0.5, anchor=CENTER)
        connect_leap_button.place(relx=0.5, rely=0.6, anchor=CENTER)
        connect_spark_button.place(relx=0.5, rely=0.7, anchor=CENTER)
        exit_button.place(relx=0.5, rely = 0.8, anchor=CENTER)
示例#43
0
文件: query.py 项目: abalkin/cpython
    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(self, borderwidth=2, relief="sunken")
        entrylabel = Label(frame, anchor="w", justify="left", text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()

        buttons = Frame(self)
        self.button_ok = Button(buttons, text="Ok", default="active", width=8, command=self.ok)
        self.button_cancel = Button(buttons, text="Cancel", width=8, command=self.cancel)

        frame.pack(side="top", expand=True, fill="both")
        entrylabel.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side="bottom")
        self.button_ok.pack(side="left", padx=5)
        self.button_cancel.pack(side="right", padx=5)
示例#44
0
    def create_widgets(self):  # Call from override, if any.
        # Bind to self widgets needed for entry_ok or unittest.
        self.frame = frame = Frame(self, borderwidth=2, relief='sunken', )
        entrylabel = Label(frame, anchor='w', justify='left',
                           text=self.message)
        self.entryvar = StringVar(self, self.text0)
        self.entry = Entry(frame, width=30, textvariable=self.entryvar)
        self.entry.focus_set()

        buttons = Frame(self)
        self.button_ok = Button(buttons, text='Ok',
                width=8, command=self.ok)
        self.button_cancel = Button(buttons, text='Cancel',
                width=8, command=self.cancel)

        frame.pack(side='top', expand=True, fill='both')
        entrylabel.pack(padx=5, pady=5)
        self.entry.pack(padx=5, pady=5)
        buttons.pack(side='bottom')
        self.button_ok.pack(side='left', padx=5)
        self.button_cancel.pack(side='right', padx=5)
示例#45
0
class ExecuteScriptView(Frame):
  """View to execute scripts"""
  def __init__(self, master, controller):
    Frame.__init__(self,master)
    self.master = master
    self.controller = controller

    self.initialize_ui()

  def initialize_ui(self):
    default_padding = {'padx': 10, 'pady' : 10}

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

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

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

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

    self.take_picture_frame.pack(expand = True)
    
    self.button_update = Button(self, text = "Update", command = self.controller.run_update_script)
    self.button_update.pack(expand = True, fill = "x")

  def take_picture(self):
    return self.controller.run_take_picture_script(self.controller.customer_id.get(), self.picture_mode.get())
示例#46
0
    def _init_ui(self):
        """Initializes all the UI elements."""
        self.pack(fill='both', expand=True)

        button_frame = Frame(self)
        button_frame.pack(fill='x', padx=5, pady=5)
        clear_button = Button(button_frame, textvariable=self.clear_text, command=self.on_clear)
        clear_button.pack(side='left')
        step_button = Button(button_frame, textvariable=self.step_text, command=self.on_step)
        end_button = Button(button_frame, textvariable=self.end_text, command=self.on_end)
        end_button.pack(side='right')
        step_button.pack(side='right')

        grid_frame = Frame(self, style=styles.GRID_FRAME)
        self.subgrids = _build_3x3_grid(grid_frame, SubGrid)
        for subgrid in self.subgrids:
            boxes = _build_3x3_grid(subgrid, Box)
            for box in boxes:
                self.boxes[box.position] = box
        grid_frame.pack(fill='both', padx=5, expand=True)

        status_bar = Label(self, textvariable=self.status_text)
        status_bar.pack(fill='x', padx=5, pady=5)
示例#47
0
文件: panel.py 项目: Lysovenko/bpc
 def body(self, frame):
     "Place panel widgets"
     frame.grid_columnconfigure(0, weight=1)
     frame.grid_rowconfigure(1, weight=1)
     top = Frame(frame)
     top.grid(column=0, row=0, sticky="ew")
     self.mounts = Combobox(top, takefocus=False, state="readonly")
     self.mounts["postcommand"] = self.get_places
     self.mounts.bind("<<ComboboxSelected>>", self.goto_place)
     self.mounts.pack(anchor="nw")
     pthl = Label(top, textvariable=self.pwd)
     pthl.pack(expand=True, anchor="w")
     self.tree = tree = Treeview(frame,
                                 columns=("size", "modified", "mode"))
     tree.grid(column=0, row=1, sticky="nwes")
     vsb = Scrollbar(frame, command=self.tree.yview, orient="vertical")
     vsb.grid(column=1, row=1, sticky="ns")
     tree["yscrollcommand"] = lambda f, l: autoscroll(vsb, f, l)
     hsb = Scrollbar(frame, command=self.tree.xview,
                     orient="horizontal")
     hsb.grid(column=0, row=2, sticky="ew")
     tree["xscrollcommand"] = lambda f, l: autoscroll(hsb, f, l)
     tree.column("size", width=70, anchor="center")
     tree.column("modified", width=70, anchor="center")
     tree.column("mode", width=70, anchor="center")
     tree.heading("#0", command=lambda: self.on_heading("name"))
     tree.heading("size", command=lambda: self.on_heading("size"))
     tree.heading("modified", command=lambda: self.on_heading("date"))
     tree.tag_configure("selected", foreground="red")
     for i in (("<Return>", self.enter_file),
               ("<Double-Button-1>", self.enter_file),
               ("<Right>", self.enter_file), ("<Left>", self.go_back),
               ("<Tab>", self.switch), ("<Home>", self.go_top),
               ("<Button-1>", self.activate),
               ("<Insert>", self.turn_selection),
               ("<Control-r>", self.refresh)):
         tree.bind(*i)
示例#48
0
class LoginFrame:
    def __init__(self, url):
        self.url = url

        self.root = Tk()
        self.root.title("验证码")

        while True:
            try:
                image_bytes = urlopen(self.url).read()
                break
            except socket.timeout:
                print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                continue
            except urllib.error.URLError as e:
                if isinstance(e.reason, socket.timeout):
                    print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                    continue
        # internal data file
        data_stream = io.BytesIO(image_bytes)
        # open as a PIL image object
        self.pil_image = Image.open(data_stream)
        # convert PIL image object to Tkinter PhotoImage object
        self.tk_image = ImageTk.PhotoImage(self.pil_image)
        self.label = Label(self.root, image=self.tk_image, background='brown')
        self.label.pack(padx=5, pady=5)
        self.button = Button(self.root, text="刷新验证码", command=self.refreshImg)
        self.button.pack(padx=5, pady=5)

        randCodeLable = Label(self.root, text="验证码:")
        randCodeLable.pack(padx=5, pady=5)
        self.randCode = Entry(self.root)
        self.randCode.pack(padx=5, pady=5)

        self.loginButton = Button(self.root, text="登录", default=tkinter.ACTIVE)
        self.loginButton.pack(padx=5, pady=5)

    def refreshImg(self):
        url = self.url
        while True:
            try:
                image_bytes = urlopen(url).read()
                data_stream = io.BytesIO(image_bytes)
                self.pil_image = Image.open(data_stream)
                self.tk_image = ImageTk.PhotoImage(self.pil_image)
                self.label.configure(image=self.tk_image)
                break
            except socket.timeout:
                print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                continue
            except urllib.error.URLError as e:
                if isinstance(e.reason, socket.timeout):
                    print('获取验证码超时:%s\r\n重新获取.' % (self.url))
                    continue

    # 显示URL地址指定图片
    def show(self):
        w, h = self.pil_image.size

        # 窗体居中
        width = w + 100
        height = h + 160
        ws = self.root.winfo_screenwidth()
        hs = self.root.winfo_screenheight()
        x = int((ws / 2) - (width / 2))
        y = int((hs / 2) - (height / 2))
        self.root.geometry('{}x{}+{}+{}'.format(width, height, x, y))
        # 禁止窗体改变大小
        self.root.resizable(False, False)
        self.root.mainloop()


    def quit(self):
        self.root.destroy()
示例#49
0
class HTMLWindow( tk.Toplevel, ChildBox ):
    """
    """
    def __init__( self, parentWindow, filename=None ):
        """
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
            print( exp("HTMLWindow.__init__( {}, {} )").format( parentWindow, repr(filename) ) )
            assert( parentWindow )
        self.parentWindow, self.initialFilename = parentWindow, filename
        tk.Toplevel.__init__( self, self.parentWindow )
        ChildBox.__init__( self, self.parentWindow )
        self.protocol( "WM_DELETE_WINDOW", self.closeHTMLWindow )
        self.title( 'HTMLWindow' )
        self.genericWindowType = 'HTMLWindow'
        self.winType = 'HTMLWindow'
        self.moduleID = 'HTML'

        self.geometry( INITIAL_HTML_SIZE )
        self.minimumSize, self.maximumSize = MINIMUM_HTML_SIZE, MAXIMUM_HTML_SIZE
        self.minsize( *parseWindowSize( self.minimumSize ) )
        self.maxsize( *parseWindowSize( self.maximumSize ) )

        self._showStatusBarVar = tk.BooleanVar()
        self._showStatusBarVar.set( True )
        self._statusTextVar = tk.StringVar()
        self._statusTextVar.set( '' ) # first initial value

        self.createMenuBar()
        self.createToolBar()
        self.createContextMenu()
        if self._showStatusBarVar.get(): self.createStatusBar()

        self.viewMode = DEFAULT
        self.settings = None

        # Create a scroll bar to fill the right-hand side of the window
        self.vScrollbar = Scrollbar( self )
        self.vScrollbar.pack( side=tk.RIGHT, fill=tk.Y )

        #if 'textBox' in dir(self): # we have one already -- presumably a specialised one
            #halt # We have one already
        #else: # let's make one

        self.textBox = HTMLText( self, yscrollcommand=self.vScrollbar.set, state=tk.DISABLED )
        self.textBox['wrap'] = 'word'
        self.textBox.pack( expand=tk.YES, fill=tk.BOTH )
        self.vScrollbar.config( command=self.textBox.yview ) # link the scrollbar to the text box
        self.createStandardKeyboardBindings()
        self.textBox.bind( "<Button-1>", self.setFocus ) # So disabled text box can still do select and copy functions

        # Options for find, etc.
        self.optionsDict = {}
        self.optionsDict['caseinsens'] = True

        if filename:
            self.historyList = [ filename ]
            self.historyIndex = 1 # Number from the end (starting with 1)
            self.load( filename )
        else:
            self.historyList = []
            self.historyIndex = 0 # = None
    # end of HTMLWindow.__init__


    def notWrittenYet( self ):
        errorBeep()
        showerror( self, _("Not implemented"), _("Not yet available, sorry") )
    # end of HTMLWindow.notWrittenYet


    def createMenuBar( self ):
        """
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.createMenuBar()") )
        try: kBD = self.parentWindow.parentApp.keyBindingDict
        except AttributeError: kBD = self.parentApp.keyBindingDict

        self.menubar = tk.Menu( self )
        #self['menu'] = self.menubar
        self.config( menu=self.menubar ) # alternative

        fileMenu = tk.Menu( self.menubar, tearoff=False )
        self.menubar.add_cascade( menu=fileMenu, label='File', underline=0 )
        #fileMenu.add_command( label='New...', underline=0, command=self.notWrittenYet )
        #fileMenu.add_command( label='Open...', underline=0, command=self.notWrittenYet )
        #fileMenu.add_separator()
        #subfileMenuImport = tk.Menu( fileMenu )
        #subfileMenuImport.add_command( label='USX', underline=0, command=self.notWrittenYet )
        #fileMenu.add_cascade( label='Import', underline=0, menu=subfileMenuImport )
        #subfileMenuExport = tk.Menu( fileMenu )
        #subfileMenuExport.add_command( label='USX', underline=0, command=self.notWrittenYet )
        #subfileMenuExport.add_command( label='HTML', underline=0, command=self.notWrittenYet )
        #fileMenu.add_cascade( label='Export', underline=0, menu=subfileMenuExport )
        #fileMenu.add_separator()
        fileMenu.add_command( label='Info...', underline=0, command=self.doShowInfo, accelerator=kBD['Info'][0] )
        fileMenu.add_separator()
        fileMenu.add_command( label='Close', underline=0, command=self.doClose, accelerator=kBD['Close'][0] ) # close this window

        editMenu = tk.Menu( self.menubar, tearoff=False )
        self.menubar.add_cascade( menu=editMenu, label='Edit', underline=0 )
        editMenu.add_command( label='Copy', underline=0, command=self.doCopy, accelerator=kBD['Copy'][0] )
        editMenu.add_separator()
        editMenu.add_command( label='Select all', underline=0, command=self.doSelectAll, accelerator=kBD['SelectAll'][0] )

        searchMenu = tk.Menu( self.menubar )
        self.menubar.add_cascade( menu=searchMenu, label='Search', underline=0 )
        searchMenu.add_command( label='Goto line...', underline=0, command=self.doGotoLine, accelerator=kBD['Line'][0] )
        searchMenu.add_separator()
        searchMenu.add_command( label='Find...', underline=0, command=self.doFind, accelerator=kBD['Find'][0] )
        searchMenu.add_command( label='Find again', underline=5, command=self.doRefind, accelerator=kBD['Refind'][0] )

        viewMenu = tk.Menu( self.menubar, tearoff=False )
        self.menubar.add_cascade( menu=viewMenu, label='View', underline=0 )
        viewMenu.add_checkbutton( label='Status bar', underline=0, variable=self._showStatusBarVar, command=self.doToggleStatusBar )

        gotoMenu = tk.Menu( self.menubar )
        self.menubar.add_cascade( menu=gotoMenu, label='Goto', underline=0 )
        gotoMenu.add_command( label='Back', underline=0, command=self.doGoBackward )
        gotoMenu.add_command( label='Forward', underline=0, command=self.doGoForward )

        toolsMenu = tk.Menu( self.menubar, tearoff=False )
        self.menubar.add_cascade( menu=toolsMenu, label='Tools', underline=0 )
        toolsMenu.add_command( label='Options...', underline=0, command=self.notWrittenYet )

        windowMenu = tk.Menu( self.menubar, tearoff=False )
        self.menubar.add_cascade( menu=windowMenu, label='Window', underline=0 )
        windowMenu.add_command( label='Bring in', underline=0, command=self.notWrittenYet )

        helpMenu = tk.Menu( self.menubar, name='help', tearoff=False )
        self.menubar.add_cascade( menu=helpMenu, underline=0, label='Help' )
        helpMenu.add_command( label='Help...', underline=0, command=self.doHelp, accelerator=kBD['Help'][0] )
        helpMenu.add_separator()
        helpMenu.add_command( label='About...', underline=0, command=self.doAbout, accelerator=kBD['About'][0] )
    # end of HTMLWindow.createMenuBar


    def createContextMenu( self ):
        """
        Can be overriden if necessary.
        """
        try: kBD = self.parentWindow.parentApp.keyBindingDict
        except AttributeError: kBD = self.parentApp.keyBindingDict

        self.contextMenu = tk.Menu( self, tearoff=0 )
        self.contextMenu.add_command( label="Copy", underline=0, command=self.doCopy, accelerator=kBD['Copy'][0] )
        self.contextMenu.add_separator()
        self.contextMenu.add_command( label="Select all", underline=7, command=self.doSelectAll, accelerator=kBD['SelectAll'][0] )
        self.contextMenu.add_separator()
        self.contextMenu.add_command( label="Find...", underline=0, command=self.doFind, accelerator=kBD['Find'][0] )
        self.contextMenu.add_separator()
        self.contextMenu.add_command( label="Close", underline=1, command=self.doClose, accelerator=kBD['Close'][0] )

        self.bind( "<Button-3>", self.showContextMenu ) # right-click
        #self.pack()
    # end of HTMLWindow.createContextMenu


    def showContextMenu( self, event ):
        self.contextMenu.post( event.x_root, event.y_root )
    # end of HTMLWindow.showContextMenu


    def createToolBar( self ):
        """
        Designed to be overridden.
        """
        #if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
            #print( exp("This 'createToolBar' method can be overridden!") )
        pass
    # end of HTMLWindow.createToolBar


    def createStatusBar( self ):
        """
        Create a status bar containing only one text label at the bottom of the main window.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("createStatusBar()") )
        Style().configure('HTMLStatusBar.TFrame', background='yellow')
        Style().configure( 'StatusBar.TLabel', background='white' )
        #Style().map("Halt.TButton", foreground=[('pressed', 'red'), ('active', 'yellow')],
                                            #background=[('pressed', '!disabled', 'black'), ('active', 'pink')] )

        self.statusBar = Frame( self, cursor='hand2', relief=tk.RAISED, style='HTMLStatusBar.TFrame' )

        self.statusTextLabel = Label( self.statusBar, relief=tk.SUNKEN,
                                    textvariable=self._statusTextVar, style='StatusBar.TLabel' )
                                    #, font=('arial',16,tk.NORMAL) )
        self.statusTextLabel.pack( side=tk.LEFT, fill=tk.X )

        # style='Halt.TButton',
        self.forwardButton = Button( self.statusBar, text='Forward', command=self.doGoForward )
        self.forwardButton.pack( side=tk.RIGHT, padx=2, pady=2 )
        self.backButton = Button( self.statusBar, text='Back', command=self.doGoBackward )
        self.backButton.pack( side=tk.RIGHT, padx=2, pady=2 )
        self.statusBar.pack( side=tk.BOTTOM, fill=tk.X )

        #self.setReadyStatus()
        self.setStatus() # Clear it
    # end of HTMLWindow.createStatusBar

    def setStatus( self, newStatusText='' ):
        """
        Set (or clear) the status bar text.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("setStatus( {} )").format( repr(newStatusText) ) )
        #print( "SB is", repr( self._statusTextVar.get() ) )
        if newStatusText != self._statusTextVar.get(): # it's changed
            #self.statusBarTextWidget['state'] = tk.NORMAL
            #self.statusBarTextWidget.delete( '1.0', tk.END )
            #if newStatusText:
                #self.statusBarTextWidget.insert( '1.0', newStatusText )
            #self.statusBarTextWidget['state'] = tk.DISABLED # Don't allow editing
            #self.statusText = newStatusText
            self._statusTextVar.set( newStatusText )
            if self._showStatusBarVar.get(): self.statusTextLabel.update()
    # end of HTMLWindow.setStatus

    #def setWaitStatus( self, newStatusText ):
        #"""
        #Set the status bar text and change the cursor to the wait/hourglass cursor.
        #"""
        #if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
            #print( exp("setWaitStatus( {} )").format( repr(newStatusText) ) )
        ##self.rootWindow.config( cursor='watch' ) # 'wait' can only be used on Windows
        #self.setStatus( newStatusText )
        #self.update()
    ## end of HTMLWindow.setWaitStatus

    def setReadyStatus( self ):
        """
        Sets the status line to "Ready"
            and sets the cursor to the normal cursor.
        """
        self.setStatus( _("Ready") )
        #self.config( cursor='' )
    # end of HTMLWindow.setReadyStatus

    def doToggleStatusBar( self ):
        """
        Display or hide the status bar.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("doToggleStatusBar()") )
        if self._showStatusBarVar.get():
            self.createStatusBar()
        else:
            self.statusBar.destroy()
    # end of HTMLWindow.doToggleStatusBar


    def load( self, filepath ):
        """
        Loads the given HTML file into the window
            and also finds and sets the window title
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.load( {} )").format( filepath ) )
        self.folderPath, self.filename = os.path.split( filepath )
        with open( filepath, 'rt' ) as HTMLFile:
            fileContents = HTMLFile.read()
        match = re.search( '<title>(.+?)</title>', fileContents )
        if match:
            #print( '0', repr(match.group(0)) ) # This includes the entire match, i.e., with the <title> tags, etc.
            #print( '1', repr(match.group(1)) ) # This is just the title
            title = match.group(1).replace( '\n', ' ' ).replace( '\r', ' ' ).replace( '  ', ' ' )
            #print( "title", repr(title) )
            self.title( title )
        else: self.title( 'HTMLWindow' )
        self.setAllText( fileContents )
    # end of HTMLWindow.load


    def gotoLink( self, link ):
        """
        Loads the given HTML file into the window
            and also finds and sets the window title
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.gotoLink( {} )").format( link ) )
        if not os.path.isabs( link ): # relative filepath
            link = os.path.join( self.folderPath, link )
        self.load( link )
        self.historyList.append( link )
        self.historyIndex = 1
    # end of HTMLWindow.gotoLink


    def overLink( self, link ):
        """
        Loads the given HTML file into the window
            and also finds and sets the window title
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.overLink( {} )").format( link ) )
        self.setStatus( link ) # Display it
    # end of HTMLWindow.overLink


    def leaveLink( self ):
        """
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.leaveLink()") )
        self.setStatus() # Clear it
    # end of HTMLWindow.leaveLink


    def doGoForward( self ):
        """
        """
        if self.historyIndex > 1:
            self.historyIndex -= 1
            self.load( self.historyList[ -self.historyIndex ] )
    # end of BibleResourceWindow.doGoForward


    def doGoBackward( self ):
        """
        """
        if self.historyIndex < len( self.historyList ):
            self.historyIndex += 1
            self.load( self.historyList[ -self.historyIndex ] )
    # end of BibleResourceWindow.doGoBackward


    def doHelp( self, event=None ):
        """
        Display a help box.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.doHelp()") )
        from Help import HelpBox

        helpInfo = ProgNameVersion
        helpInfo += "\nHelp for {}".format( self.winType )
        helpInfo += "\n  Keyboard shortcuts:"
        for name,shortcut in self.myKeyboardBindingsList:
            helpInfo += "\n    {}\t{}".format( name, shortcut )
        hb = HelpBox( self, self.genericWindowType, helpInfo )
    # end of HTMLWindow.doHelp


    def doAbout( self, event=None ):
        """
        Display an about box.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.doAbout()") )
        from About import AboutBox

        aboutInfo = ProgNameVersion
        aboutInfo += "\nInformation about {}".format( self.winType )
        ab = AboutBox( self, self.genericWindowType, aboutInfo )
    # end of HTMLWindow.doAbout


    def doClose( self, event=None ):
        """
        Called from the GUI.

        Can be overridden.
        """
        self.closeHTMLWindow()
    # end of HTMLWindow.doClose

    def closeHTMLWindow( self ):
        """
        Called to finally and irreversibly remove this window from our list and close it.
        """
        if BibleOrgSysGlobals.debugFlag and debuggingThisModule: print( exp("HTMLWindow.closeHTMLWindow()") )
        try: cWs = self.parentWindow.parentApp.childWindows
        except AttributeError: cWs = self.parentApp.childWindows
        if self in cWs:
            cWs.remove( self )
            self.destroy()
        else: # we might not have finished making our window yet
            if BibleOrgSysGlobals.debugFlag:
                print( exp("HTMLWindow.closeHTMLWindow() for {} wasn't in list").format( self.winType ) )
            try: self.destroy()
            except tk.TclError: pass # never mind
        if BibleOrgSysGlobals.debugFlag: self.parentWindow.parentApp.setDebugText( "Closed HTML window" )
示例#50
0
bottom_frame = Frame(main_frame)

label = Label(top_frame, text="This is my Label")
entry = Entry(top_frame, textvariable=mystring)
radio = Radiobutton(top_frame, text="Enable", variable=myint, value=1)

text1 = Text(mid_frame)
text2 = Text(mid_frame)

ok_button = Button(bottom_frame, text="Ok", command=okbutton)
cancel_button = Button(bottom_frame, text="Cancel", command=exit)

###### Pack our Widgets #######
main_frame.pack()
top_frame.pack()
mid_frame.pack()
bottom_frame.pack(anchor="e")

label.pack(side="left")
entry.pack(side="left")
radio.pack(side="left")

text1.pack(side="left")
text2.pack(side="left")

cancel_button.pack(side="right", padx=5, pady=5)
ok_button.pack(side="right")


root.mainloop()
示例#51
0
def _gui():
  try:
    from tkinter import Tk, ttk, filedialog, messagebox, StringVar, IntVar
    from tkinter.ttk import Button, Entry, Frame, Label, LabelFrame, Notebook, Radiobutton, Style
  except:
    sys.exit("Unable to load tkinter. Aborting.")
  
  def _check_single(): #check the input and accordingly give the output... for the f_single tab
    if txt_f_single_entry.get()=="":
      lbl_f_single_result.config(text="", style="TLabel")
    elif check_afm(txt_f_single_entry.get()):
      lbl_f_single_result.config(text="Έγκυρο ΑΦΜ.", style="valid.TLabel")
    else:
      lbl_f_single_result.config(text="Άκυρο ΑΦΜ.", style="invalid.TLabel")
  
  def _select_input_file():
    strv_f_file_input.set(filedialog.askopenfilename(title="Άνοιγμα αρχείου"))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
#TODO a much better mechanism to enable / disable btn_f_file_submit is needed.
  def _select_output_file():
    strv_f_file_output.set(filedialog.asksaveasfilename(title="Αποθήκευση ως..."))
    if strv_f_file_input.get() != "" and strv_f_file_output.get() != "":
      btn_f_file_submit.config(state="normal")
    else: btn_f_file_submit.config(state="disabled")
  
  def _check_file():#TODO this could / should be merged with the TUI version...
    input_filepath = strv_f_file_input.get()
    output_filepath = strv_f_file_output.get()
    filter_output = intvar_filter_sel.get()
    try:
      input_file = open(input_filepath, "r")
      output_file = open(output_filepath, "w")
    except:
      messagebox.showerror(title="Σφάλμα", message="Αδυναμία διαχείρησης των αρχείων που ορίσατε.\n\nΠαρακαλώ επιβεβαιώστε πως το αρχείο με τα δεδομένα υπάρχει, πως έχετε δικαιώματα ανάγνωσης, και πως έχετε δικαιώματα εγγραφής στον κατάλογο εξαγωγής των αποτελεσμάτων.")
      return
    counter = {True:0, False:0}
    for entry in input_file:
      validation = check_afm(entry.strip())
      counter[validation]+=1
      if filter_output == 3 and validation == False:
        output_file.write(entry)
      elif filter_output == 2 and validation == True:
        output_file.write(entry)
      elif filter_output == 1:
        output_file.write(entry.strip() + "\t" + str(validation) + "\n\r")
    lbl_f_file_result.config(text="Σύνολο: "+str(counter[True]+counter[False])+"\nΈγκυρα: "+str(counter[True])+"\nΆκυρα: "+str(counter[False]))

  #create the window
  main_window = Tk()
  main_window.title("Έλεγχος εγκυρότητας Α.Φ.Μ. (v 2.0)")
  main_window.geometry("600x180")
  main_window.minsize(600,180)

  #fool arround with styling
  style = ttk.Style()
  style.configure("valid.TLabel", background="green")
  style.configure("empty.TLabel", background="white")
  style.configure("invalid.TLabel", background="red")
  style.configure("TNotebook", padding = 10)
  
  #create the Notebook
  tabs = Notebook(main_window)
  f_single = Frame(tabs)
  f_file = Frame(tabs)
  tabs.add(f_single, text="Μεμονομένα Α.Φ.Μ.")
  tabs.add(f_file, text="Λίστα από αρχείο")#add state="disabled" prior to git push until ready
  tabs.pack(anchor="nw")
  
  #add some widgets in f_single tab
  lbl_f_single_instructions = Label(f_single, text="Εισάγετε έναν ΑΦΜ για έλεγχο")
  lbl_f_single_instructions.grid(column=0, row=0)

  lbl_f_single_result = Label(f_single, text="", width=10, justify="center")
  lbl_f_single_result.grid(column=1, row=0, rowspan=2, sticky="ewns")

  txt_f_single_entry = Entry(f_single, width=11)
  txt_f_single_entry.focus()
  txt_f_single_entry.bind("<KeyRelease>", lambda e: _check_single() )
  txt_f_single_entry.grid(column=0,row=1)

  #btn_f_single_submit = Button(f_single, text="Έλεγχος", command=_check_single)
  #btn_f_single_submit.grid(column=0,row=2)
    
  #add some widgets in f_file tab
  lbl_f_file_finput = Label(f_file, text="Άνοιγμα...")
  lbl_f_file_finput.grid(column=0, row=0)
  strv_f_file_input = StringVar()
  txt_f_file_finput = Entry(f_file, textvariable = strv_f_file_input)
  txt_f_file_finput.grid(column=1, row=0)
  btn_f_file_finput = Button(f_file, text="...", width=3, command=_select_input_file)
  btn_f_file_finput.grid(column=2, row=0, sticky="W")
  
  lbl_f_file_foutput = Label(f_file, text="Αποθήκευση ως...")
  lbl_f_file_foutput.grid(column=0, row=1)
  strv_f_file_output = StringVar()
  txt_f_file_foutput = Entry(f_file, textvariable = strv_f_file_output)
  txt_f_file_foutput.grid(column=1, row=1)
  btn_f_file_foutput = Button(f_file, text="...", width=3, command=_select_output_file)
  btn_f_file_foutput.grid(column=2, row=1, sticky="W")
  
  lf_filter = LabelFrame(f_file, text="Επιστροφή")
  lf_filter.grid(column=3, row=0, rowspan=2, sticky="ewns")
  intvar_filter_sel = IntVar()
  rb_filter_all = Radiobutton(lf_filter, text="Όλων", variable=intvar_filter_sel, value=1) #TODO maybe add command
  rb_filter_all.pack(anchor="w")
  rb_filter_all.invoke()
  rb_filter_true = Radiobutton(lf_filter, text="Έγκυρων", variable=intvar_filter_sel, value=2)
  rb_filter_true.pack(anchor="w")
  rb_filter_false = Radiobutton(lf_filter, text="Άκυρων", variable=intvar_filter_sel, value=3)
  rb_filter_false.pack(anchor="w")
  
  lf_result = LabelFrame(f_file, text="Σύνοψη")
  lf_result.grid(column=4, row=0, rowspan=2, sticky="ewns")
  lbl_f_file_result = Label(lf_result, text="", width=12)#TODO bring results
  lbl_f_file_result.pack()
  
  btn_f_file_submit = Button(f_file, text="Επεξεργασία", state="disabled", command=_check_file)
  btn_f_file_submit.grid(column=0, row=2, columnspan=3)
  
  btn_main_exit = Button(main_window, text="Έξοδος", command=sys.exit)
  btn_main_exit.pack(anchor="se")

  main_window.mainloop()
示例#52
0
    def create_widgets(self):
        self.frame = frame = Frame(self, borderwidth=2, relief='sunken')
        frame.pack(side='top', expand=True, fill='both')

        frame_buttons = Frame(self)
        frame_buttons.pack(side='bottom', fill='x')

        self.button_ok = Button(frame_buttons, text='OK',
                                width=8, command=self.ok)
        self.button_ok.grid(row=0, column=0, padx=5, pady=5)
        self.button_cancel = Button(frame_buttons, text='Cancel',
                                   width=8, command=self.cancel)
        self.button_cancel.grid(row=0, column=1, padx=5, pady=5)

        # Basic entry key sequence.
        self.frame_keyseq_basic = Frame(frame, name='keyseq_basic')
        self.frame_keyseq_basic.grid(row=0, column=0, sticky='nsew',
                                      padx=5, pady=5)
        basic_title = Label(self.frame_keyseq_basic,
                            text=f"New keys for '{self.action}' :")
        basic_title.pack(anchor='w')

        basic_keys = Label(self.frame_keyseq_basic, justify='left',
                           textvariable=self.key_string, relief='groove',
                           borderwidth=2)
        basic_keys.pack(ipadx=5, ipady=5, fill='x')

        # Basic entry controls.
        self.frame_controls_basic = Frame(frame)
        self.frame_controls_basic.grid(row=1, column=0, sticky='nsew', padx=5)

        # Basic entry modifiers.
        self.modifier_checkbuttons = {}
        column = 0
        for modifier, variable in zip(self.modifiers, self.modifier_vars):
            label = self.modifier_label.get(modifier, modifier)
            check = Checkbutton(self.frame_controls_basic,
                                command=self.build_key_string, text=label,
                                variable=variable, onvalue=modifier, offvalue='')
            check.grid(row=0, column=column, padx=2, sticky='w')
            self.modifier_checkbuttons[modifier] = check
            column += 1

        # Basic entry help text.
        help_basic = Label(self.frame_controls_basic, justify='left',
                           text="Select the desired modifier keys\n"+
                                "above, and the final key from the\n"+
                                "list on the right.\n\n" +
                                "Use upper case Symbols when using\n" +
                                "the Shift modifier.  (Letters will be\n" +
                                "converted automatically.)")
        help_basic.grid(row=1, column=0, columnspan=4, padx=2, sticky='w')

        # Basic entry key list.
        self.list_keys_final = Listbox(self.frame_controls_basic, width=15,
                                       height=10, selectmode='single')
        self.list_keys_final.insert('end', *AVAILABLE_KEYS)
        self.list_keys_final.bind('<ButtonRelease-1>', self.final_key_selected)
        self.list_keys_final.grid(row=0, column=4, rowspan=4, sticky='ns')
        scroll_keys_final = Scrollbar(self.frame_controls_basic,
                                      orient='vertical',
                                      command=self.list_keys_final.yview)
        self.list_keys_final.config(yscrollcommand=scroll_keys_final.set)
        scroll_keys_final.grid(row=0, column=5, rowspan=4, sticky='ns')
        self.button_clear = Button(self.frame_controls_basic,
                                   text='Clear Keys',
                                   command=self.clear_key_seq)
        self.button_clear.grid(row=2, column=0, columnspan=4)

        # Advanced entry key sequence.
        self.frame_keyseq_advanced = Frame(frame, name='keyseq_advanced')
        self.frame_keyseq_advanced.grid(row=0, column=0, sticky='nsew',
                                         padx=5, pady=5)
        advanced_title = Label(self.frame_keyseq_advanced, justify='left',
                               text=f"Enter new binding(s) for '{self.action}' :\n" +
                                     "(These bindings will not be checked for validity!)")
        advanced_title.pack(anchor='w')
        self.advanced_keys = Entry(self.frame_keyseq_advanced,
                                   textvariable=self.key_string)
        self.advanced_keys.pack(fill='x')

        # Advanced entry help text.
        self.frame_help_advanced = Frame(frame)
        self.frame_help_advanced.grid(row=1, column=0, sticky='nsew', padx=5)
        help_advanced = Label(self.frame_help_advanced, justify='left',
            text="Key bindings are specified using Tkinter keysyms as\n"+
                 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
                 "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
                 "Upper case is used when the Shift modifier is present!\n\n" +
                 "'Emacs style' multi-keystroke bindings are specified as\n" +
                 "follows: <Control-x><Control-y>, where the first key\n" +
                 "is the 'do-nothing' keybinding.\n\n" +
                 "Multiple separate bindings for one action should be\n"+
                 "separated by a space, eg., <Alt-v> <Meta-v>." )
        help_advanced.grid(row=0, column=0, sticky='nsew')

        # Switch between basic and advanced.
        self.button_level = Button(frame, command=self.toggle_level,
                                  text='<< Basic Key Binding Entry')
        self.button_level.grid(row=2, column=0, stick='ew', padx=5, pady=5)
        self.toggle_level()
示例#53
0
class Download(Frame):
    def __init__(self, master, **kwargs):
        super(Download, self).__init__(master, borderwidth=20, **kwargs)
        self.fs = None
        self.tree = None
        self.logfile = None

        # User informations
        self.info_tree = False
        self.start_time = None
        info = Frame(self, borderwidth=10)
        self.info_label = Label(info, wraplength=350, borderwidth=20, justify='center', font=('a', 10, 'bold'))
        self.info_indis = Label(info)
        self.info_fams = Label(info)
        self.info_sources = Label(info)
        self.info_notes = Label(info)
        self.time = Label(info)
        self.info_label.grid(row=0, column=0, columnspan=2)
        self.info_indis.grid(row=1, column=0)
        self.info_fams.grid(row=1, column=1)
        self.info_sources.grid(row=2, column=0)
        self.info_notes.grid(row=2, column=1)
        self.time.grid(row=3, column=0, columnspan=2)

        self.form = Frame(self)
        self.sign_in = SignIn(self.form)
        self.options = None
        self.title = Label(self, text=_('Sign In to FamilySearch'), font=('a', 12, 'bold'))
        buttons = Frame(self)
        self.btn_quit = Button(buttons, text=_('Quit'), command=Thread(target=self.quit).start)
        self.btn_valid = Button(buttons, text=_('Sign In'), command=self.command_in_thread(self.login))
        self.title.pack()
        self.sign_in.pack()
        self.form.pack()
        self.btn_quit.pack(side='left', padx=(0, 40))
        self.btn_valid.pack(side='right', padx=(40, 0))
        info.pack()
        buttons.pack(side='bottom')
        self.pack()
        self.update_needed = False

    def info(self, text):
        self.info_label.config(text=text)

    def save(self):
        filename = filedialog.asksaveasfilename(title=_('Save as'), defaultextension='.ged', filetypes=(('GEDCOM', '.ged'), (_('All files'), '*.*')))
        if not filename:
            return
        with open(filename, 'w', encoding='utf-8') as file:
            self.tree.print(file)

    def login(self):
        global _
        username = self.sign_in.username.get()
        password = self.sign_in.password.get()
        if not (username and password):
            messagebox.showinfo(message=_('Please enter your FamilySearch username and password.'))
            return
        self.btn_valid.config(state='disabled')
        self.info(_('Login to FamilySearch...'))
        self.logfile = open('download.log', 'w', encoding='utf-8')
        self.fs = Session(self.sign_in.username.get(), self.sign_in.password.get(), verbose=True, logfile=self.logfile, timeout=1)
        if not self.fs.logged:
            messagebox.showinfo(_('Error'), message=_('The username or password was incorrect'))
            self.btn_valid.config(state='normal')
            self.info('')
            return
        self.tree = Tree(self.fs)
        _ = self.fs._
        self.title.config(text=_('Options'))
        cache.delete('lang')
        cache.add('lang', self.fs.lang)
        self.options = Options(self.form, True)
        self.info('')
        self.sign_in.destroy()
        self.options.pack()
        self.master.change_lang()
        self.btn_valid.config(command=self.command_in_thread(self.download), state='normal', text=_('Download'))
        self.options.start_indis.add_indi(self.fs.get_userid())
        self.update_needed = False

    def quit(self):
        self.update_needed = False
        if self.logfile:
            self.logfile.close()
        super(Download, self).quit()
        # prevent exception during download
        os._exit(1)

    def download(self):
        todo = [self.options.start_indis.indis[key] for key in sorted(self.options.start_indis.indis)]
        for fid in todo:
            if not re.match(r'[A-Z0-9]{4}-[A-Z0-9]{3}', fid):
                messagebox.showinfo(_('Error'), message=_('Invalid FamilySearch ID: ') + fid)
                return
        self.start_time = time.time()
        self.options.destroy()
        self.form.destroy()
        self.title.config(text='FamilySearch to GEDCOM')
        self.btn_valid.config(state='disabled')
        self.info(_('Download starting individuals...'))
        self.info_tree = True
        self.tree.add_indis(todo)
        todo = set(todo)
        done = set()
        for i in range(self.options.ancestors.get()):
            if not todo:
                break
            done |= todo
            self.info(_('Download ') + str(i + 1) + _('th generation of ancestors...'))
            todo = self.tree.add_parents(todo) - done

        todo = set(self.tree.indi.keys())
        done = set()
        for i in range(self.options.descendants.get()):
            if not todo:
                break
            done |= todo
            self.info(_('Download ') + str(i + 1) + _('th generation of descendants...'))
            todo = self.tree.add_children(todo) - done

        if self.options.spouses.get():
            self.info(_('Download spouses and marriage information...'))
            todo = set(self.tree.indi.keys())
            self.tree.add_spouses(todo)
        ordi = self.options.ordinances.get()
        cont = self.options.contributors.get()

        async def download_stuff(loop):
            futures = set()
            for fid, indi in self.tree.indi.items():
                futures.add(loop.run_in_executor(None, indi.get_notes))
                if ordi:
                    futures.add(loop.run_in_executor(None, self.tree.add_ordinances, fid))
                if cont:
                    futures.add(loop.run_in_executor(None, indi.get_contributors))
            for fam in self.tree.fam.values():
                futures.add(loop.run_in_executor(None, fam.get_notes))
                if cont:
                    futures.add(loop.run_in_executor(None, fam.get_contributors))
            for future in futures:
                await future

        loop = asyncio.get_event_loop()
        self.info(_('Download notes') + (((',' if cont else _(' and')) + _(' ordinances')) if ordi else '') + (_(' and contributors') if cont else '') + '...')
        loop.run_until_complete(download_stuff(loop))

        self.tree.reset_num()
        self.btn_valid.config(command=self.save, state='normal', text=_('Save'))
        self.info(text=_('Success ! Click below to save your GEDCOM file'))
        self.update_info_tree()
        self.update_needed = False

    def command_in_thread(self, func):
        def res():
            self.update_needed = True
            Thread(target=self.update_gui).start()
            Thread(target=func).start()
        return res

    def update_info_tree(self):
        if self.info_tree and self.start_time and self.tree:
            self.info_indis.config(text=_('Individuals: %s') % len(self.tree.indi))
            self.info_fams.config(text=_('Families: %s') % len(self.tree.fam))
            self.info_sources.config(text=_('Sources: %s') % len(self.tree.sources))
            self.info_notes.config(text=_('Notes: %s') % len(self.tree.notes))
            t = round(time.time() - self.start_time)
            minutes = t // 60
            seconds = t % 60
            self.time.config(text=_('Elapsed time: %s:%s') % (minutes, '00%s'[len(str(seconds)):] % seconds))

    def update_gui(self):
        while self.update_needed:
            self.update_info_tree()
            self.master.update()
            time.sleep(0.1)
示例#54
0
class autoClicker(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()
    
    def initUI(self):
        self.sliderTime=0
        self.running = 0
        self.leftclick = 0
        self.middleclick = 0
        self.rightclick = 0
                
        self.parent.overrideredirect(True)
        self.style = Style()
        self.style.theme_use("default")
        self.parent.wm_attributes("-topmost", 1)
        self.parent.resizable(0,0)
        
        self.gripBar = BitmapImage(data=GRIPBAR)
        self.closeBox = BitmapImage(data=CLOSEBOX)
        self.closeHover = BitmapImage(data=CLOSEHOVER)
        self.leftClick = BitmapImage(data=LEFTCLICK)
        self.leftClickDown = BitmapImage(data=LEFTCLICKDOWN)
        self.middleClick = BitmapImage(data=MIDDLECLICK)
        self.middleClickDown = BitmapImage(data=MIDDLECLICKDOWN)
        self.rightClick = BitmapImage(data=RIGHTCLICK)
        self.rightClickDown = BitmapImage(data=RIGHTCLICKDOWN)
        
        self.barFrame = Frame(self)
        self.barFrame.pack(side=TOP, fill=BOTH)
        self.clickFrame = Frame(self, borderwidth=0)
        self.clickFrame.pack(side=TOP, fill=BOTH, padx=12, expand=1)

        self.sliderScale = Scale(self, from_=0, to=1, resolution=.01, orient=HORIZONTAL, borderwidth=0, showvalue=0)
        self.sliderScale.pack(side=TOP, fill="x", expand=1)
        
        self.buttonFrame = Frame(self, borderwidth=0)
        self.buttonFrame.pack(side=TOP, fill=BOTH, expand=1)
        
        self.grip = Label(self.barFrame, image=self.gripBar)
        self.grip.image=self.gripBar
        self.grip.pack(side=LEFT, fill="x")
        self.grip.bind("<ButtonPress-1>", self.startMove)
        self.grip.bind("<ButtonRelease-1>", self.stopMove)
        self.grip.bind("<B1-Motion>", self.onMotion)
        
        self.closeButton = Label(self.barFrame, image=self.closeBox)
        self.closeButton.image=self.closeBox
        self.closeButton.pack(side=RIGHT, fill="none")
        self.closeButton.bind("<ButtonPress-1>", self.sysExit)
        self.closeButton.bind("<Enter>", self.onHover)
        self.closeButton.bind("<Leave>", self.onLeave)
        
        self.leftClickToggle = Label(self.clickFrame, image=self.leftClick, borderwidth=0)
        self.leftClickToggle.image=self.leftClick
        self.leftClickToggle.pack(side=LEFT, expand=1)
        self.leftClickToggle.bind("<Button-1>", self.leftToggle)
        
        self.middleClickToggle = Label(self.clickFrame, image=self.middleClick, borderwidth=0)
        self.middleClickToggle.image=self.middleClick
        self.middleClickToggle.pack(side=LEFT, expand=1)
        self.middleClickToggle.bind("<Button-1>", self.middleToggle)

        self.rightClickToggle = Label(self.clickFrame, image=self.rightClick, borderwidth=0)
        self.rightClickToggle.image=self.rightClick
        self.rightClickToggle.pack(side=LEFT, expand=1)
        self.rightClickToggle.bind("<Button-1>", self.rightToggle)

        self.startButton = Button(self.buttonFrame, text="Start", relief=FLAT, activebackground="lightgrey", borderwidth=0)
        self.startButton.pack(fill=BOTH, expand=1)
        self.startButton.bind("<Button-1>", self.startClick)
        self.startButton.bind("<space>", self.startClick)
                
        w = 116
        h = 74

        ws = self.winfo_screenwidth() # width of the screen
        hs = self.winfo_screenheight() # height of the screen

        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.parent.config(bg="black")
        self.pack(fill="both", padx=1, pady=1)
        
    def leftToggle(self,event):
        if self.running == 0:
            if self.leftclick == 0:
                event.widget.configure(image=self.leftClickDown)
                self.leftclick = 1;
            else:
                event.widget.configure(image=self.leftClick)
                self.leftclick = 0;
                
    def middleToggle(self,event):
        if self.running == 0:
            if self.middleclick == 0:
                event.widget.configure(image=self.middleClickDown)
                self.middleclick = 1;
            else:
                event.widget.configure(image=self.middleClick)
                self.middleclick = 0;
                
    def rightToggle(self,event):
        if self.running == 0:
            if self.rightclick == 0:
                event.widget.configure(image=self.rightClickDown)
                self.rightclick = 1;
            else:
                event.widget.configure(image=self.rightClick)
                self.rightclick = 0;

    def onHover(self,event):
        event.widget.configure(image=self.closeHover)
    
    def onLeave(self,event):
        event.widget.configure(image=self.closeBox)

    def startMove(self,event):
        self.parent.x = event.x
        self.parent.y = event.y
        
    def onMotion(self, event):
        deltax = event.x - self.parent.x
        deltay = event.y - self.parent.y
        x = self.parent.winfo_x() + deltax
        y = self.parent.winfo_y() + deltay
        self.parent.geometry("+%s+%s" % (x, y))
        
    def stopMove(self, event):
        event.x = None
        event.y = None

    def sysExit(self, event):
        self.running = 0
        sys.exit()
            
    def startClick(self, event):
        if self.running == 0 and not (self.leftclick == 0 and self.middleclick==0 and self.rightclick == 0):
            self.running = 1
            event.widget.config(text="Stop")
            currentMouseX, currentMouseY = pyautogui.position()
            pyautogui.moveTo(currentMouseX, currentMouseY+50)
            threading.Thread(target=self.startLoop, args=()).start()
        else:
            self.running = 0
            event.widget.config(text="Start")
        time.sleep(0.2)
        return

    def startLoop(self):
        while self.running == 1:
            if self.leftclick == 1:
                pyautogui.click()
            if self.middleclick == 1:
                pyautogui.click(button="middle")
            if self.rightclick == 1:
                pyautogui.click(button="right")
            delay = self.sliderScale.get()
            time.sleep(delay)
        return
示例#55
0
文件: sudoku.py 项目: j4321/Sudoku-Tk
class Sudoku(Tk):
    def __init__(self, file=None):
        Tk.__init__(self, className="Sudoku-Tk")
        self.title("Sudoku-Tk")
        self.resizable(0, 0)
        self.protocol("WM_DELETE_WINDOW", self.quitter)
        cst.set_icon(self)
        self.columnconfigure(3, weight=1)

        # --- style
        bg = '#dddddd'
        activebg = '#efefef'
        pressedbg = '#c1c1c1'
        lightcolor = '#ededed'
        darkcolor = '#cfcdc8'
        bordercolor = '#888888'
        focusbordercolor = '#5E5E5E'
        disabledfg = '#999999'
        disabledbg = bg

        button_style_config = {'bordercolor': bordercolor,
                               'background': bg,
                               'lightcolor': lightcolor,
                               'darkcolor': darkcolor}

        button_style_map = {'background': [('active', activebg),
                                           ('disabled', disabledbg),
                                           ('pressed', pressedbg)],
                            'lightcolor': [('pressed', darkcolor)],
                            'darkcolor': [('pressed', lightcolor)],
                            'bordercolor': [('focus', focusbordercolor)],
                            'foreground': [('disabled', disabledfg)]}

        style = Style(self)
        style.theme_use(cst.STYLE)
        style.configure('TFrame', background=bg)
        style.configure('TLabel', background=bg)
        style.configure('TScrollbar', gripcount=0, troughcolor=pressedbg,
                        **button_style_config)
        style.map('TScrollbar', **button_style_map)
        style.configure('TButton', **button_style_config)
        style.map('TButton', **button_style_map)
        style.configure('TCheckutton', **button_style_config)
        style.map('TCheckutton', **button_style_map)
        self.option_add('*Toplevel.background', bg)
        self.option_add('*Menu.background', bg)
        self.option_add('*Menu.activeBackground', activebg)
        self.option_add('*Menu.activeForeground', "black")
        self.configure(bg=bg)

        style.configure("bg.TFrame", background="grey")
        style.configure("case.TFrame", background="white")
        style.configure("case.TLabel", background="white", foreground="black")
        style.configure("case_init.TFrame", background="lightgrey")
        style.configure("case_init.TLabel", background="lightgrey", foreground="black")
        style.configure("erreur.TFrame", background="white")
        style.configure("erreur.TLabel", background="white", foreground="red")
        style.configure("solution.TFrame", background="white")
        style.configure("solution.TLabel", background="white", foreground="blue")
        style.configure("pause.TLabel", foreground="grey", background='white')

        # --- images
        self.im_erreur = open_image(cst.ERREUR)
        self.im_pause = open_image(cst.PAUSE)
        self.im_restart = open_image(cst.RESTART)
        self.im_play = open_image(cst.PLAY)
        self.im_info = open_image(cst.INFO)
        self.im_undo = open_image(cst.UNDO)
        self.im_redo = open_image(cst.REDO)
        self.im_question = open_image(cst.QUESTION)

        # --- timer
        self.chrono = [0, 0]
        self.tps = Label(self, text=" %02i:%02i" % tuple(self.chrono),
                         font="Arial 16")
        self.debut = False  # la partie a-t-elle commencée ?
        self.chrono_on = False  # le chrono est-il en marche ?

        # --- buttons
        self.b_pause = Button(self, state="disabled", image=self.im_pause,
                              command=self.play_pause)
        self.b_restart = Button(self, state="disabled", image=self.im_restart,
                                command=self.recommence)
        self.b_undo = Button(self, image=self.im_undo, command=self.undo)
        self.b_redo = Button(self, image=self.im_redo, command=self.redo)

        # --- tooltips
        self.tooltip_wrapper = TooltipWrapper(self)
        self.tooltip_wrapper.add_tooltip(self.b_pause, _("Pause game"))
        self.tooltip_wrapper.add_tooltip(self.b_restart, _("Restart game"))
        self.tooltip_wrapper.add_tooltip(self.b_undo, _("Undo"))
        self.tooltip_wrapper.add_tooltip(self.b_redo, _("Redo"))

        # --- numbers
        frame_nb = Frame(self, style='bg.TFrame', width=36)
        self.progression = []
        for i in range(1, 10):
            self.progression.append(Progression(frame_nb, i))
            self.progression[-1].pack(padx=1, pady=1)

        # --- level indication
        frame = Frame(self)
        frame.grid(row=0, columnspan=5, padx=(30, 10), pady=10)
        Label(frame, text=_("Level") + ' - ', font="Arial 16").pack(side='left')
        self.label_level = Label(frame, font="Arial 16", text=_("Unknown"))
        self.label_level.pack(side='left')
        self.level = "unknown"  # puzzle level

        # --- frame contenant la grille de sudoku
        self.frame_puzzle = Frame(self, style="bg.TFrame")
        self.frame_pause = Frame(self, style="case.TFrame")
        self.frame_pause.grid_propagate(False)
        self.frame_pause.columnconfigure(0, weight=1)
        self.frame_pause.rowconfigure(0, weight=1)
        Label(self.frame_pause, text='PAUSE', style='pause.TLabel',
              font='Arial 30 bold').grid()

        # --- placement
        frame_nb.grid(row=1, column=6, sticky='en', pady=0, padx=(0, 30))
        self.frame_puzzle.grid(row=1, columnspan=5, padx=(30, 15))
        self.tps.grid(row=2, column=0, sticky="e", padx=(30, 10), pady=30)
        self.b_pause.grid(row=2, column=1, sticky="w", padx=2, pady=30)
        self.b_restart.grid(row=2, column=2, sticky="w", padx=2, pady=30)
        self.b_undo.grid(row=2, column=3, sticky="e", pady=30, padx=2)
        self.b_redo.grid(row=2, column=4, sticky="w", pady=30, padx=(2, 10))

        # --- menu
        menu = Menu(self, tearoff=0)

        menu_nouveau = Menu(menu, tearoff=0)

        menu_levels = Menu(menu_nouveau, tearoff=0)
        menu_levels.add_command(label=_("Easy"), command=self.new_easy)
        menu_levels.add_command(label=_("Medium"), command=self.new_medium)
        menu_levels.add_command(label=_("Difficult"), command=self.new_difficult)

        menu_nouveau.add_cascade(label=_("Level"), menu=menu_levels)
        menu_nouveau.add_command(label=_("Generate a puzzle"),
                                 command=self.genere_grille,
                                 accelerator="Ctrl+G")
        menu_nouveau.add_command(label=_("Empty grid"),
                                 command=self.grille_vide,
                                 accelerator="Ctrl+N")

        menu_ouvrir = Menu(menu, tearoff=0)
        menu_ouvrir.add_command(label=_("Game"), command=self.import_partie,
                                accelerator="Ctrl+O")
        menu_ouvrir.add_command(label=_("Puzzle"), command=self.import_grille,
                                accelerator="Ctrl+Shift+O")

        menu_game = Menu(menu, tearoff=0)
        menu_game.add_command(label=_("Restart"), command=self.recommence)
        menu_game.add_command(label=_("Solve"), command=self.resolution)
        menu_game.add_command(label=_("Save"), command=self.sauvegarde,
                              accelerator="Ctrl+S")
        menu_game.add_command(label=_("Export"), command=self.export_impression,
                              accelerator="Ctrl+E")
        menu_game.add_command(label=_("Evaluate level"),
                              command=self.evaluate_level)

        menu_language = Menu(menu, tearoff=0)
        self.langue = StringVar(self)
        self.langue.set(cst.LANGUE[:2])
        menu_language.add_radiobutton(label="Français",
                                      variable=self.langue,
                                      value="fr", command=self.translate)
        menu_language.add_radiobutton(label="English", variable=self.langue,
                                      value="en", command=self.translate)

        menu_help = Menu(menu, tearoff=0)
        menu_help.add_command(label=_("Help"), command=self.aide, accelerator='F1')
        menu_help.add_command(label=_("About"), command=self.about)

        menu.add_cascade(label=_("New"), menu=menu_nouveau)
        menu.add_cascade(label=_("Open"), menu=menu_ouvrir)
        menu.add_cascade(label=_("Game"), menu=menu_game)
        menu.add_cascade(label=_("Language"), menu=menu_language)
        menu.add_command(label=_("Statistics"), command=self.show_stat)
        menu.add_cascade(label=_("Help"), menu=menu_help)

        self.configure(menu=menu)

        # --- clavier popup
        self.clavier = None

        # --- cases
        self.nb_cases_remplies = 0
        self.blocs = np.zeros((9, 9), dtype=object)
        for i in range(9):
            for j in range(9):
                self.blocs[i, j] = Case(self.frame_puzzle, i, j, self.update_nbs, width=50, height=50)
                px, py = 1, 1
                if i % 3 == 2 and i != 8:
                    py = (1, 3)
                if j % 3 == 2 and j != 8:
                    px = (1, 3)
                self.blocs[i, j].grid(row=i, column=j, padx=px, pady=py)
                self.blocs[i, j].grid_propagate(0)

        # --- undo/redo stacks
        self._undo_stack = []
        self._redo_stack = []

        # --- raccourcis clavier et actions de la souris
        self.bind("<Button>", self.edit_case)
        self.bind("<Control-z>", lambda e: self.undo())
        self.bind("<Control-y>", lambda e: self.redo())
        self.bind("<Control-s>", lambda e: self.sauvegarde())
        self.bind("<Control-e>", lambda e: self.export_impression())
        self.bind("<Control-o>", lambda e: self.import_partie())
        self.bind("<Control-Shift-O>", lambda e: self.import_grille())
        self.bind("<Control-n>", lambda e: self.grille_vide())
        self.bind("<Control-g>", lambda e: self.genere_grille())
        self.bind("<FocusOut>", self.focus_out)
        self.bind("<F1>", self.aide)

        # --- open game
        if file:
            try:
                self.load_sudoku(file)
            except FileNotFoundError:
                one_button_box(self, _("Error"),
                               _("The file %(file)r does not exist.") % file,
                               image=self.im_erreur)
            except (KeyError, EOFError, UnpicklingError):
                try:
                    self.load_grille(file)
                except Exception:
                    one_button_box(self, _("Error"),
                                   _("This file is not a valid sudoku file."),
                                   image=self.im_erreur)
        elif exists(cst.PATH_SAVE):
            self.load_sudoku(cst.PATH_SAVE)
            remove(cst.PATH_SAVE)

    @property
    def level(self):
        return self._level

    @level.setter
    def level(self, level):
        self._level = level
        self.label_level.configure(text=_(level.capitalize()))

    def update_nbs(self, nb, delta):
        self.progression[nb - 1].nb += delta

    def reset_nbs(self):
        for p in self.progression:
            p.nb = 0

    def evaluate_level(self):
        grille = Grille()
        for i in range(9):
            for j in range(9):
                val = self.blocs[i, j].get_val()
                if val:
                    grille.ajoute_init(i, j, val)
        self.level = difficulte_grille(grille)

    def show_stat(self):
        """ show best times """
        def reset():
            """ reset best times """
            for level in ["easy", "medium", "difficult"]:
                CONFIG.set("Statistics", level, "")
            top.destroy()

        if self.chrono_on:
            self.play_pause()
        top = Toplevel(self)
        top.transient(self)
        top.columnconfigure(1, weight=1)
        top.resizable(0, 0)

        top.title(_("Statistics"))
        top.grab_set()

        Label(top, text=_("Best times"), font="Sans 12 bold").grid(row=0, columnspan=2,
                                                                   padx=30, pady=10)

        for i, level in enumerate(["easy", "medium", "difficult"]):
            Label(top, text=_(level.capitalize()),
                  font="Sans 10 bold").grid(row=i + 1, column=0, padx=(20, 4),
                                            pady=4, sticky="e")
            tps = CONFIG.get("Statistics", level)
            if tps:
                tps = int(tps)
                m = tps // 60
                s = tps % 60
                Label(top, text=" %i min %i s" % (m, s),
                      font="Sans 10").grid(row=i + 1, column=1,
                                           sticky="w", pady=4,
                                           padx=(4, 20))
        Button(top, text=_("Close"), command=top.destroy).grid(row=4, column=0, padx=(10, 4), pady=10)
        Button(top, text=_("Clear"), command=reset).grid(row=4, column=1, padx=(4, 10), pady=10)

    def new_easy(self):
        nb = np.random.randint(1, 101)
        fichier = join(cst.PUZZLES_LOCATION, "easy", "puzzle_easy_%i.txt" % nb)
        self.import_grille(fichier)
        self.level = "easy"

    def new_medium(self):
        nb = np.random.randint(1, 101)
        fichier = join(cst.PUZZLES_LOCATION, "medium", "puzzle_medium_%i.txt" % nb)
        self.import_grille(fichier)
        self.level = "medium"

    def new_difficult(self):
        nb = np.random.randint(1, 101)
        fichier = join(cst.PUZZLES_LOCATION, "difficult", "puzzle_difficult_%i.txt" % nb)
        self.import_grille(fichier)
        self.level = "difficult"

    def translate(self):
        """ changement de la langue de l'interface """
        one_button_box(self, _("Information"),
                       _("The language setting will take effect after restarting the application"),
                       image=self.im_info)
        CONFIG.set("General", "language", self.langue.get())

    def focus_out(self, event):
        """ met en pause si la fenêtre n'est plus au premier plan """
        try:
            if not self.focus_get() and self.chrono_on:
                self.play_pause()
        except KeyError:
            # erreur déclenchée par la présence d'une tkMessagebox
            if self.chrono_on:
                self.play_pause()

    def stacks_reinit(self):
        """efface l'historique des actions"""
        self._undo_stack.clear()
        self._redo_stack.clear()
        self.b_undo.configure(state="disabled")
        self.b_redo.configure(state="disabled")

    def stacks_modif(self, action):
        """Record action and clear redo stack."""
        self._undo_stack.append(action)
        self.b_undo.configure(state="normal")
        self.b_redo.configure(state="disabled")
        self._redo_stack.clear()

    def about(self):
        if self.chrono_on:
            self.play_pause()
        About(self)

    def aide(self, event=None):
        if self.chrono_on:
            self.play_pause()
        Aide(self)

    def quitter(self):
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to interrupt the current puzzle?"),
                                 _("Yes"), _("No"), image=self.im_question)
        if rep == _("Yes"):
            if self.debut:
                self.save(cst.PATH_SAVE)
            self.destroy()

    def undo(self):
        if self._undo_stack and self.chrono_on:
            self.b_redo.configure(state="normal")
            i, j, val_prec, pos_prec, modifs, val, pos = self._undo_stack.pop(-1)
            self._redo_stack.append((i, j, val_prec, pos_prec, modifs, val, pos))
            if not self._undo_stack:
                self.b_undo.configure(state="disabled")

            if self.blocs[i, j].get_val():
                self.modifie_nb_cases_remplies(-1)
                self.update_nbs(self.blocs[i, j].get_val(), -1)
            self.blocs[i, j].efface_case()
            if val_prec:
                self.modifie_nb_cases_remplies(self.blocs[i, j].edit_chiffre(val_prec))
                if not self.test_case(i, j, val):
                    self.update_grille(i, j, val)
            else:
                for nb in pos_prec:
                    v = int(nb)
                    self.modifie_nb_cases_remplies(self.blocs[i, j].edit_possibilite(v))
                    self.test_possibilite(i, j, v)
            for k, l in modifs:
                self.blocs[k, l].edit_possibilite(val)

    def redo(self):
        if self._redo_stack and self.chrono_on:
            self.b_undo.configure(state="normal")
            i, j, val_prec, pos_prec, modifs, val, pos = self._redo_stack.pop(-1)
            self._undo_stack.append((i, j, val_prec, pos_prec, modifs, val, pos))
            if not self._redo_stack:
                self.b_redo.configure(state="disabled")
            val_prec = self.blocs[i, j].get_val()
            if val_prec:
                self.modifie_nb_cases_remplies(-1)
                self.update_nbs(val_prec, -1)
            self.blocs[i, j].efface_case()
            if val:
                self.modifie_nb_cases_remplies(self.blocs[i, j].edit_chiffre(val))
                if not self.test_case(i, j, val_prec):
                    self.update_grille(i, j, val_prec)
            else:
                for nb in pos:
                    v = int(nb)
                    self.modifie_nb_cases_remplies(self.blocs[i, j].edit_possibilite(v))
                    self.test_possibilite(i, j, v)

    def restart(self, m=0, s=0):
        """ réinitialise le chrono et les boutons """
        self.chrono = [m, s]
        self.chrono_on = False
        self.debut = False
        self.tps.configure(text=" %02i:%02i" % tuple(self.chrono))
        self.b_undo.configure(state="disabled")
        self.b_pause.configure(state="disabled", image=self.im_pause)
        self.b_redo.configure(state="disabled")
        self.b_restart.configure(state="disabled")
        self.stacks_reinit()
        self.frame_pause.place_forget()

    def play_pause(self):
        """ Démarre le chrono s'il était arrêté, le met en pause sinon """
        if self.debut:
            if self.chrono_on:
                self.chrono_on = False
                self.b_pause.configure(image=self.im_play)
                self.b_redo.configure(state="disabled")
                self.b_undo.configure(state="disabled")
                self.tooltip_wrapper.set_tooltip_text(self.b_pause, _("Resume game"))
                self.frame_pause.place(in_=self.frame_puzzle, x=0, y=0, anchor='nw',
                                       relwidth=1, relheight=1)
            elif self.nb_cases_remplies != 81:
                self.chrono_on = True
                self.b_pause.configure(image=self.im_pause)
                self.tps.after(1000, self.affiche_chrono)
                if self._undo_stack:
                    self.b_undo.configure(state="normal")
                if self._redo_stack:
                    self.b_redo.configure(state="normal")
                self.tooltip_wrapper.set_tooltip_text(self.b_pause, _("Pause game"))
                self.frame_pause.place_forget()

    def affiche_chrono(self):
        """ Met à jour l'affichage du temps """
        if self.chrono_on:
            self.chrono[1] += 1
            if self.chrono[1] == 60:
                self.chrono[0] += 1
                self.chrono[1] = 0
            self.tps.configure(text=" %02i:%02i" % tuple(self.chrono))
            self.tps.after(1000, self.affiche_chrono)

    def modifie_nb_cases_remplies(self, nb):
        self.nb_cases_remplies += nb

    def edit_case(self, event):
        if event.num in [1, 3]:
            if not self.debut and self.nb_cases_remplies != 81:
                self.debut = True
                self.b_pause.configure(state="normal")
                self.b_restart.configure(state="normal")
                self.play_pause()
            if str(event.widget) != "." and self.chrono_on:
                if self.clavier:
                    self.clavier.quitter()
                ref = self.blocs[0, 0].winfo_parent()
                case = event.widget.grid_info().get("in", None)
                if str(case) == ref:
                    case = event.widget
                try:
                    if case.is_modifiable():
                        if event.num == 1:
                            self.clavier = Clavier(self, case, "val")
                        elif event.num == 3:
                            self.clavier = Clavier(self, case, "possibilite")
                        self.clavier.display("+%i+%i" % (case.winfo_rootx() - 25, case.winfo_rooty() + 50))
                except AttributeError:
                    if self.clavier:
                        self.clavier.quitter()

            elif self.clavier:
                self.clavier.quitter()

    def test_case(self, i, j, val_prec=0):
        """ Teste si la valeur de la case est en contradiction avec celles des
            autres cases de la ligne / colonne / bloc et renvoie True s'il y a une erreur."""
        val = self.blocs[i, j].get_val()
        a, b = i // 3, j // 3
        error = False
        if val:
            if ((self.blocs[i, :] == val).sum() > 1 or (self.blocs[:, j] == val).sum() > 1 or
               (self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)] == val).sum() > 1):
                # erreur !
                self.blocs[i, j].affiche_erreur()
                error = True
        if val_prec:
            # a number was removed, remove obsolete errors
            line = self.blocs[i, :] == val_prec
            column = self.blocs[:, j] == val_prec
            bloc = self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)] == val_prec
            if line.sum() == 1:
                self.blocs[i, line.argmax()].no_error()
                self.test_case(i, line.argmax())
            if column.sum() == 1:
                self.blocs[column.argmax(), j].no_error()
                self.test_case(column.argmax(), j)
            if bloc.sum() == 1:
                x, y = divmod(bloc.argmax(), 3)
                self.blocs[3 * a + x, 3 * b + y].no_error()
                self.test_case(3 * a + x, 3 * b + y)
        return error

    def test_possibilite(self, i, j, val):
        """ Teste si la possibilité val de la case est en contradiction avec les valeurs des
            autres cases de la ligne / colonne / bloc """
        a, b = i // 3, j // 3
        if ((self.blocs[i, :] == val).sum() > 0 or (self.blocs[:, j] == val).sum() > 0 or
           (self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)] == val).sum() > 0):
            # erreur !
            self.blocs[i, j].affiche_erreur_possibilite(val)

    def test_remplie(self):
        """ Test si la grille est remplie """
        if self.nb_cases_remplies == 81:
            grille = Grille()
            for i in range(9):
                for j in range(9):
                    val = self.blocs[i, j].get_val()
                    if val:
                        grille.ajoute_init(i, j, val)
            sol = grille.solve()
            if type(sol) == np.ndarray:
                self.play_pause()
                self.frame_pause.place_forget()
                one_button_box(self, _("Information"),
                               _("You solved the puzzle in %(min)i minutes and %(sec)i secondes.") % {"min": self.chrono[0], "sec": self.chrono[1]},
                               image=self.im_info)
                if self.level != "unknown":
                    best = CONFIG.get("Statistics", self.level)
                    current = self.chrono[0] * 60 + self.chrono[1]
                    if best:
                        best = int(best)
                        if current < best:
                            CONFIG.set("Statistics", self.level, str(current))
                    else:
                        CONFIG.set("Statistics", self.level, str(current))
                self.b_pause.configure(state="disabled")
                self.debut = False

            else:
                i, j = sol[1]
                if self.blocs[i, j].get_val():
                    self.blocs[i, j].affiche_erreur()
                one_button_box(self, _("Information"), _("There is a mistake."),
                               image=self.im_info)

    def update_grille(self, i, j, val_prec=0):
        """ Enlève les possibilités devenues impossibles suite à l'ajout d'une
            valeur dans la case (i, j) """
        val = self.blocs[i, j].get_val()
        modif = []
        a, b = i // 3, j // 3
        if val_prec:
            x, y = divmod(val_prec - 1, 3)
        for k, (line, column, bloc) in enumerate(zip(self.blocs[i, :], self.blocs[:, j], self.blocs[3 * a: 3 * (a + 1), 3 * b: 3 * (b + 1)].flatten())):
            # works because if line is bloc then pos1 is pos3 and both are edited at once
            pos1 = line.get_possibilites()
            pos2 = column.get_possibilites()
            pos3 = bloc.get_possibilites()
            if val in pos1:
                self.blocs[i, k].edit_possibilite(val)
                modif.append((i, k))
            if val in pos2:
                self.blocs[k, j].edit_possibilite(val)
                modif.append((k, j))
            if val in pos3:
                m, n = divmod(k, 3)
                self.blocs[3 * a + m, 3 * b + n].edit_possibilite(val)
                modif.append((3 * a + m, 3 * b + n))
            if val_prec:
                if val_prec in pos1:
                    self.blocs[i, k].pas_erreur(x, y)
                    self.test_possibilite(i, k, val_prec)
                if val_prec in pos2:
                    self.blocs[k, j].pas_erreur(x, y)
                    self.test_possibilite(k, j, val_prec)
                if val_prec in pos3:
                    m, n = divmod(k, 3)
                    m, n = 3 * a + m, 3 * b + n
                    if m != i and n != j:
                        self.blocs[m, n].pas_erreur(x, y)
                        self.test_possibilite(m, n, val_prec)
        return modif

    def set_clavier(self, c):
        self.clavier = c

    def grille_vide(self):
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            self.nb_cases_remplies = 0
            self.restart()
            self.level = "unknown"
            self.reset_nbs()
            for i in range(9):
                for j in range(9):
                    self.blocs[i, j].set_modifiable(True)
                    self.blocs[i, j].efface_case()

    def genere_grille(self):
        """ Génère une nouvelle grille """
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)

        if rep == _("Yes"):
            self.configure(cursor="watch")
            self.update()
            rep2 = _("Retry")
            while rep2 == _("Retry"):
                grille = genere_grille()
                diff = difficulte_grille(grille)
                nb = grille.nb_cases_remplies()
                self.configure(cursor="")
                rep2 = two_button_box(self, _("Information"),
                                      _("The generated puzzle contains %(nb)i numbers and its level is %(difficulty)s.") % ({"nb": nb, "difficulty": _(diff.capitalize())}),
                                      _("Play"), _("Retry"), image=self.im_info)
            if rep2 == _("Play"):
                self.level = diff
                self.affiche_grille(grille.get_sudoku())

    def recommence(self):
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you really want to start again?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            self.reset_nbs()
            for i in range(9):
                for j in range(9):
                    if self.blocs[i, j].is_modifiable():
                        if self.blocs[i, j].get_val():
                            self.nb_cases_remplies -= 1
                        self.blocs[i, j].efface_case()
                    else:
                        self.update_nbs(self.blocs[i, j].get_val(), 1)
            self.restart()
        elif self.debut:
            self.play_pause()

    def save(self, path):
        grille = np.zeros((9, 9), dtype=int)
        modif = np.zeros((9, 9), dtype=bool)
        possibilites = []
        for i in range(9):
            possibilites.append([])
            for j in range(9):
                grille[i, j] = self.blocs[i, j].get_val()
                modif[i, j] = self.blocs[i, j].is_modifiable()
                possibilites[i].append(self.blocs[i, j].get_possibilites())
        with open(path, "wb") as fich:
            p = Pickler(fich)
            p.dump(grille)
            p.dump(modif)
            p.dump(possibilites)
            p.dump(self.chrono)
            p.dump(self.level)

    def sauvegarde(self):
        if self.chrono_on:
            self.play_pause()
        fichier = asksaveasfilename(initialdir=cst.INITIALDIR,
                                    defaultextension='.sudoku',
                                    filetypes=[('Sudoku', '*.sudoku')])
        if fichier:
            self.save(fichier)

    def affiche_grille(self, grille):
        """ Affiche la grille """
        self.nb_cases_remplies = 0
        self.restart()
        self.reset_nbs()
        for i in range(9):
            for j in range(9):
                nb = grille[i, j]
                self.blocs[i, j].efface_case()
                if nb:
                    self.blocs[i, j].set_modifiable(False)
                    self.nb_cases_remplies += 1
                    self.blocs[i, j].edit_chiffre(nb)
                else:
                    self.blocs[i, j].set_modifiable(True)

    def load_sudoku(self, file):
        with open(file, "rb") as fich:
            dp = Unpickler(fich)
            grille = dp.load()
            modif = dp.load()
            possibilites = dp.load()
            chrono = dp.load()
            self.level = dp.load()
        self.nb_cases_remplies = 0
        self.reset_nbs()
        self.restart(*chrono)
        for i in range(9):
            for j in range(9):
                self.blocs[i, j].efface_case()
                if grille[i, j]:
                    self.nb_cases_remplies += 1
                    self.blocs[i, j].edit_chiffre(grille[i, j])
                else:
                    for pos in possibilites[i][j]:
                        self.blocs[i, j].edit_possibilite(pos)
                self.blocs[i, j].set_modifiable(modif[i, j])

    def import_partie(self):
        """ importe une partie stockée dans un fichier .sudoku """
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            fichier = askopenfilename(initialdir=cst.INITIALDIR,
                                      defaultextension='.sudoku',
                                      filetypes=[('Sudoku', '*.sudoku')])
            if fichier:
                try:
                    self.load_sudoku(fichier)
                except FileNotFoundError:
                    one_button_box(self, _("Error"),
                                   _("The file %(file)r does not exist.") % fichier,
                                   image=self.im_erreur)
                except (KeyError, EOFError, UnpicklingError):
                    one_button_box(self, _("Error"),
                                   _("This file is not a valid sudoku file."),
                                   image=self.im_erreur)
        elif self.debut:
            self.play_pause()

    def resolution_init(self):
        """ Résolution de la grille initiale (sans tenir compte des valeurs rentrées par l'utilisateur. """
        grille = Grille()
        for i in range(9):
            for j in range(9):
                if not self.blocs[i, j].is_modifiable():
                    val = self.blocs[i, j].get_val()
                    grille.ajoute_init(i, j, val)
        self.configure(cursor="watch")
        self.update()
        sol = grille.solve()
        self.configure(cursor="")
        if type(sol) == np.ndarray:
            for i in range(9):
                for j in range(9):
                    val = self.blocs[i, j].get_val()
                    if not val:
                        self.blocs[i, j].edit_chiffre(sol[i, j])
                        self.blocs[i, j].affiche_solution()
                    elif self.blocs[i, j].is_modifiable():
                        if val != sol[i, j]:
                            self.blocs[i, j].edit_chiffre(sol[i, j])
                            self.blocs[i, j].affiche_erreur()
            self.restart()
            self.nb_cases_remplies = 81

        elif sol[1]:
            i, j = sol[1]
            if self.blocs[i, j].get_val():
                self.blocs[i, j].affiche_erreur()
            one_button_box(self, _("Error"), _("The grid is wrong. It cannot be solved."),
                           image=self.im_erreur)
        else:
            one_button_box(self, _("Error"), _("Resolution failed."),
                           image=self.im_erreur)

    def resolution(self):
        if self.chrono_on:
            self.play_pause()
        rep = two_button_box(self, _("Confirmation"),
                             _("Do you really want to get the solution?"),
                             _("Yes"), _("No"), image=self.im_question)
        if rep == _("Yes"):
            self.frame_pause.place_forget()
            grille = Grille()
            for i in range(9):
                for j in range(9):
                    val = self.blocs[i, j].get_val()
                    if val:
                        grille.ajoute_init(i, j, val)
            self.configure(cursor="watch")
            self.update()
            sol = grille.solve()
            self.configure(cursor="")
            if type(sol) == np.ndarray:
                for i in range(9):
                    for j in range(9):
                        val = self.blocs[i, j].get_val()
                        if not val:
                            self.blocs[i, j].edit_chiffre(sol[i, j])
                            self.blocs[i, j].affiche_solution()
                self.restart()
                self.b_restart.configure(state="normal")
                self.nb_cases_remplies = 81
            elif sol[1]:
                i, j = sol[1]
                if self.blocs[i, j].get_val():
                    self.blocs[i, j].affiche_erreur()
                i, j = 0, 0
                while i < 9 and self.blocs[i, j].is_modifiable():
                    j += 1
                    if j == 9:
                        i += 1
                        j = 0
                if i < 9:
                    # il y a au moins une case de type "initial"
                    rep = two_button_box(self, _("Error"),
                                         _("The grid is wrong. It cannot be solved. Do you want the solution of the initial grid?"),
                                         _("Yes"), _("No"), image=self.im_erreur)
                    if rep == _("Yes"):
                        self.resolution_init()
                else:
                    one_button_box(self, _("Error"), _("The grid is wrong. It cannot be solved."),
                                   image=self.im_erreur)
            else:
                one_button_box(self, _("Error"), _("Resolution failed."),
                               image=self.im_erreur)

    def load_grille(self, file):
        gr = np.loadtxt(file, dtype=int)
        if gr.shape == (9, 9):
            self.affiche_grille(gr)
            self.level = "unknown"
        else:
            one_button_box(self, _("Error"), _("This is not a 9x9 sudoku grid."),
                           image=self.im_erreur)

    def import_grille(self, fichier=None):
        """ importe une grille stockée dans un fichier txt sous forme de
            chiffres séparés par des espaces (0 = case vide) """
        if self.chrono_on:
            self.play_pause()
        rep = _("Yes")
        if self.debut:
            rep = two_button_box(self, _("Confirmation"),
                                 _("Do you want to abandon the current puzzle?"),
                                 _("Yes"), _("No"), self.im_question)
        if rep == _("Yes"):
            if not fichier:
                fichier = askopenfilename(initialdir=cst.INITIALDIR,
                                          defaultextension='.txt',
                                          filetypes=[('Text', '*.txt'), ('Tous les fichiers', "*")])
            if fichier:
                try:
                    self.load_grille(fichier)
                except (ValueError, UnicodeDecodeError):
                    one_button_box(self, _("Error"),
                                   _("The file does not have the right format. It should be a .txt file with cell values separated by one space. 0 means empty cell."),
                                   image=self.im_erreur)
                except FileNotFoundError:
                    one_button_box(self, _("Error"),
                                   _("The file %(file)r does not exist.") % fichier,
                                   image=self.im_erreur)
        elif self.debut:
            self.play_pause()

    def export_impression(self):
        """ exporte la grille en image (pour pouvoir l'imprimer) """
        if self.chrono_on:
            self.play_pause()
        fichier = asksaveasfilename(title=_("Export"),
                                    initialdir=cst.INITIALDIR,
                                    defaultextension='.png',
                                    filetypes=[('PNG', '*.png'),
                                               ('JPEG', 'jpg')])
        if fichier:
            grille = np.zeros((9, 9), dtype=int)
            for i in range(9):
                for j in range(9):
                    grille[i, j] = self.blocs[i, j].get_val()
            font = ImageFont.truetype("arial.ttf", 64)
            im = Image.new("RGB", (748, 748), "white")
            draw = ImageDraw.Draw(im)
            i = 0
            l = 1
            while i < 10:
                if i % 3 == 0:
                    w = 4
                else:
                    w = 2
                draw.line((l, 1, l, 748), width=w, fill="black")
                draw.line((1, l, 748, l), width=w, fill="black")
                l += 80 + w
                i += 1

            for i in range(9):
                for j in range(9):
                    if grille[i, j]:
                        draw.text((26 + j * 82 + 2 * (j // 3),
                                   10 + i * 82 + 2 * (i // 3)),
                                  " %i" % grille[i, j], fill="black", font=font)

            del draw
            im.save(fichier)
示例#56
0
class CreateCustomer(Frame):
  """Create customer screen"""
  
  def __init__(self, master):
    Frame.__init__(self,master)
    
    self.master = master
    self.frame = Frame(self.master)
    self.initUI()
  
  def initUI(self):
    self.master.title("3D Printer - Add Customer")
    self.style = Style()

    default_padding = {'padx': 10, 'pady' : 10}

    #TODO change alignment    
    #Left frame for labels
    self.left_frame = Frame(self.master)
    
    self.name_label = Label(self.left_frame, text = "Name", style="BW.TLabel")
    self.name_label.pack(default_padding)

    self.surname_label = Label(self.left_frame, text = "Surname", style="BW.TLabel")
    self.surname_label.pack(default_padding)    

    self.email_label = Label(self.left_frame, text = "Email", style="BW.TLabel")
    self.email_label.pack(default_padding)

    self.cellphone_label = Label(self.left_frame, text = "Cellphone", style="BW.TLabel")
    self.cellphone_label.pack(default_padding)

    #Right frame for entries
    self.right_frame = Frame(self.master)
    
    self.name_entry = Entry(self.right_frame)
    self.name_entry.pack(default_padding)    

    self.surname_entry = Entry(self.right_frame)
    self.surname_entry.pack(default_padding)

    self.email_entry = Entry(self.right_frame)
    self.email_entry.pack(default_padding)

    self.cellphone_entry = Entry(self.right_frame)
    self.cellphone_entry.pack(default_padding)
    
    #Bottom frame for button
    self.button_frame = Frame(self.master)
    self.create_customer_button = Button(self.button_frame, text = "Create Customer", command = self.save_customer)
    self.create_customer_button.pack(default_padding)

    self.button_frame.pack(side = BOTTOM, fill = "x", expand = True)
    self.left_frame.pack(side = LEFT, expand = True, fill = "y")
    self.right_frame.pack(side = RIGHT, expand = True, fill = "y")

    self.frame.pack()

  def save_customer(self):
    print("saving customer")

    self.customer = Customer(self.name_entry.get(), self.surname_entry.get(),
                             self.email_entry.get(), self.cellphone_entry.get())
    if not self.customer.validate():
      messagebox.showerror(message = "All fields are mandatory, please fill in all the fields")
      return
    
    db = TinyDB('db/db.json')
    self.customer_id = db.insert(self.customer.__dict__)
    
    #TODO redirect to next page
    self.go_to_execute_script()
  
  def go_to_execute_script(self):
    """redirect to next page"""
    
    self.execute_script = Toplevel(self, self.master)
    self.app = ExecuteScript(self.execute_script)
示例#57
0
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

        self.parent.title("InstaDjango")

        self.pack(fill=BOTH, expand=1)
        self.size_and_center_window()

        self.style = Style()
        self.style.theme_use("clam")
        self.style.configure("TFrame", background="#808080", foreground="white")
        self.style.configure("TButton", background="#808080", foreground="white")
        self.style.configure("high.TButton", background="#8FBC8B", foreground="white")
        self.style.configure("TLabel", background="#808080", foreground="white")
        self.style.map("TButton", background=[("pressed", "#404040"), ("active", "#A0A0A0")])

        frame = Frame(self, relief=FLAT, borderwidth=1)
        frame.pack(fill=BOTH, expand=1)

        subframe_0 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_0.pack(fill=X)
        lbl_0 = Label(subframe_0, text="App's machine-readable name (used for naming folders locally and remotely):", style="TLabel")
        lbl_0.pack(fill=BOTH, padx=10, pady=10)
        entry_0 = Entry(subframe_0)
        entry_0.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_0, "")

        subframe_1 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_1.pack(fill=X)
        lbl_1 = Label(
            subframe_1, text="Where to create the app's folder locally:", style="TLabel")
        lbl_1.pack(fill=BOTH, padx=10, pady=10)
        entry_1 = Entry(subframe_1)

        def action_1():
            cdir = filedialog.askdirectory(title="Please select a directory")
            if cdir:
                self.set_entry_text(entry_1, cdir)

        button_1 = Button(subframe_1, text="Choose", command=action_1, style="TButton")
        button_1.pack(side=RIGHT, padx=10, pady=0)
        entry_1.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_1, "")

        subframe_2 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_2.pack(fill=X)
        lbl_2 = Label(subframe_2, text="Remote host:", style="TLabel")
        lbl_2.pack(fill=BOTH, padx=10, pady=10)
        entry_2 = Entry(subframe_2)
        entry_2.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_2, "")

        subframe_3 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_3.pack(fill=X)
        lbl_3 = Label(
            subframe_3, text="Remote SSH port (empty will mean the default port):", style="TLabel")
        lbl_3.pack(fill=BOTH, padx=10, pady=10)
        entry_3 = Entry(subframe_3)
        entry_3.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_3, "")

        subframe_4 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_4.pack(fill=X)
        lbl_4 = Label(subframe_4, text="Remote user:"******"TLabel")
        lbl_4.pack(fill=BOTH, padx=10, pady=10)
        entry_4 = Entry(subframe_4)
        entry_4.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_4, "")

        subframe_5 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_5.pack(fill=X)
        lbl_5 = Label(
            subframe_5, text="Local path to the SSH private key:", style="TLabel")
        lbl_5.pack(fill=BOTH, padx=10, pady=10)
        entry_5 = Entry(subframe_5)

        def action_5():
            cdir = filedialog.askopenfilename(title="Please select a private key")
            if cdir:
                self.set_entry_text(entry_5, cdir)

        button_5 = Button(subframe_5, text="Choose", command=action_5, style="TButton")
        button_5.pack(side=RIGHT, padx=10, pady=0)
        entry_5.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_5, "")

        subframe_6 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_6.pack(fill=X)
        lbl_6 = Label(
            subframe_6, text="Where to create the app's folder remotely (should not be owned by root):", style="TLabel")
        lbl_6.pack(fill=BOTH, padx=10, pady=10)
        entry_6 = Entry(subframe_6)
        entry_6.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_6, "/var/www")

        subframe_7 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_7.pack(fill=X)
        lbl_7 = Label(subframe_7, text="Sudo password:"******"TLabel")
        lbl_7.pack(fill=BOTH, padx=10, pady=10)
        entry_7 = Entry(subframe_7, show="*")
        entry_7.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_7, "")

        subframe_8 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_8.pack(fill=X)
        lbl_8 = Label(subframe_8, text="Database password:"******"TLabel")
        lbl_8.pack(fill=BOTH, padx=10, pady=10)
        entry_8 = Entry(subframe_8, show="*")
        entry_8.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_8, "")

        subframe_9 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_9.pack(fill=X)
        lbl_9 = Label(subframe_9, text="Domain:", style="TLabel")
        lbl_9.pack(fill=BOTH, padx=10, pady=10)
        entry_9 = Entry(subframe_9)
        entry_9.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_9, "dev.example.com")

        subframe_10 = Frame(frame, relief=FLAT, borderwidth=0)
        subframe_10.pack(fill=X)
        lbl_10 = Label(subframe_10, text="Django installation type (local, production, staging):", style="TLabel")
        lbl_10.pack(fill=BOTH, padx=10, pady=10)
        entry_10 = Entry(subframe_10)
        entry_10.pack(fill=X, padx=10, ipady=5)
        self.set_entry_text(entry_10, "local")

        def go():
            setup_django_project(
                proj=entry_0.get(),
                proj_local_parent_dir=entry_1.get(),
                host=entry_2.get(),
                port=entry_3.get(),
                user=entry_4.get(),
                ssh_key=entry_5.get(),
                proj_remote_parent_dir=entry_6.get(),
                sudo_pass=entry_7.get(),
                db_pass=entry_8.get(),
                domain=entry_9.get(),
                insta_type=entry_10.get())
            self.quit()
        inst_button = Button(self, text="Go", command=go, style="high.TButton")
        inst_button.pack(side=RIGHT, padx=10, pady=10)

        quit_button = Button(self, text="Quit", command=self.quit, style="TButton")
        quit_button.pack(side=RIGHT, pady=10)