def initUI(self):
        self.parent.title("Mario's Picross Puzzle Editor")
        self.puzzles = None

        # Build the menu
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        self.fileMenu = fileMenu
        fileMenu.add_command(label="Open Mario's Picross ROM...",
                              command=self.onOpen)
        fileMenu.add_command(label="Save ROM as...",
                             command=self.onSave,
                             state=DISABLED)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

        # Navigation
        Label(self.parent).grid(row=0, column=0)
        Label(self.parent).grid(row=0, column=4)
        self.parent.grid_columnconfigure(0, weight=1)
        self.parent.grid_columnconfigure(4, weight=1)

        prevButton = Button(self.parent,
                            text="<--",
                            command=self.onPrev,
                            state=DISABLED
        )
        self.prevButton = prevButton
        prevButton.grid(row=0, column=1)

        puzzle_number = 1
        self.puzzle_number = puzzle_number
        puzzleNumber = Label(self.parent, text="Puzzle #{}".format(puzzle_number))
        self.puzzleNumber = puzzleNumber
        puzzleNumber.grid(row=0, column=2)

        nextButton = Button(self.parent,
                            text="-->",
                            command=self.onNext,
                            state=DISABLED
        )
        self.nextButton = nextButton
        nextButton.grid(row=0, column=3)

        # Canvas
        canvas = Canvas(self.parent)
        self.canvas = canvas
        for i in range(15):
            for j in range(15):
                fillcolor = "gray80"
                self.canvas.create_rectangle(10+20*j,     10+20*i,
                                             10+20*(j+1), 10+20*(i+1),
                                             fill=fillcolor,
                                             tags="{},{}".format(i, j)
                )
        self.canvas.bind("<ButtonPress-1>", self.onClick)
        canvas.grid(row=1, columnspan=5, sticky=W+E+N+S)
        self.parent.grid_rowconfigure(1, weight=1)
class SlideShow(Tk):
    # inherit GUI framework extending tkinter
    def __init__(self, msShowTimeBetweenSlides=1500):
        # initialize tkinter super class
        Tk.__init__(self)
        
        # time each slide will be shown
        self.showTime = msShowTimeBetweenSlides
        
        # look for images in current working directory where this module lives
        listOfSlides = [slide for slide in listdir() if slide.endswith('gif')]

        # endlessly read in the slides so we can show them on the tkinter Label 
        self.iterableCycle = cycle((PhotoImage(file=slide), slide) for slide in listOfSlides)
        
        # create tkinter Label widget which can also display images
        self.slidesLabel = Label(self)
        
        # create the Frame widget
        self.slidesLabel.pack()
 
 
    def slidesCallback(self):
        # get next slide from iterable cycle
        currentInstance, nameOfSlide = next(self.iterableCycle)
        
        # assign next slide to Label widget
        self.slidesLabel.config(image=currentInstance)
        
        # update Window title with current slide
        self.title(nameOfSlide)
        
        # recursively repeat the Show
        self.after(self.showTime, self.slidesCallback)
Ejemplo n.º 3
0
    def make_widgets(self):
        self.lines = ['Red Line', 'Blue Line', 'Brown Line', 'Purple Line',
                 'Orange Line', 'Green Line', 'Pink Line', 'Yellow Line']

        headimg = PhotoImage(file='header.gif')
        header = Label(self, image=headimg)
        header.image = headimg
        header.grid(row=0, columnspan=2)
        
        r = 1
        c = 0
        for b in self.lines:
            rel = 'ridge'
            cmd = lambda x=b: self.click(x)
            splt = b.split()
            if splt[0] not in 'OrangeGreenPinkYellow':
                Button(self,text=b, width = 19, height=2, relief=rel,
                       bg = splt[0], fg = "#FFF", font = ("Helvetica", 16),
                       command=cmd).grid(row=r,column=c)
            else:
                Button(self,text=b, width = 19, relief=rel,
                       bg = splt[0], fg = "#000", height=2, font = ("Helvetica", 16),
                       command=cmd).grid(row=r,column=c) 
            c += 1
            if c > 1:
                c = 0
                r += 1
Ejemplo n.º 4
0
    def __init__(self, master=None):
        # Avoiding to send it continuously.
        self.lock = False

        Frame.__init__(self, master)
        self.grid()
        self.master = master
        # Setting for ComboBox.
        self.url_lang_combobox_str = StringVar()
        self.url_lang_combobox_list = lang_list
        # UI components.
        self.receiver_email_text = Label(self, text="Receiver:")
        self.receiver_email_field = Entry(self, width=50)
        self.subject_text = Label(self, text='Subject:')
        self.subject_field = Entry(self, width=50)
        self.receiver_name_text = Label(self, text='Name:')
        self.receiver_name_field = Entry(self, width=50)
        self.url_lang_text = Label(self, text='Link lang:')
        self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly')
        self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300)
        self.send_button = Button(self, text='Send', command=self._send_mail)
        self.quit_button = Button(self, text='Exit', command=self.__exit)
        self.log_msg_text = ScrolledText(self)
        # Attachment.
        self.mail_attachment_list = attachment_list[:]
        self.url_lang_link_title = None
        self.url_lang_link = copy.deepcopy(content_link)
        # Mailer
        self._mailer = None

        # Let Mailer can control components.
        Mailer.window_content = self

        self.__create_widgets()
Ejemplo n.º 5
0
    def __init__(self, parent, frames, forks, wheelsets, groups, components):
        """
        inicjalizacja obiektu okna - nieistotne dla idei zdania
        """
        super(ConfigurationWindow, self).__init__(parent)
        self._bike = None
        self.parent = parent
        self.frames = frames
        self.forks = forks
        self.wheelsets = wheelsets
        self.groups = groups
        self.components = components
        self.parent.title("Bicycle configurator")
        self._bike_price = StringVar(self.parent)
        self._bike_weight = StringVar(self.parent)
        self._bike_travel = StringVar(self.parent)
        self.price_label = Label(self.parent, textvariable=self._bike_price)
        self.weight_label = Label(self.parent, textvariable=self._bike_weight)
        self.travel_label = Label(self.parent, textvariable=self._bike_travel)

        self.createInterface()
        self.createBike()

        self.price_label.pack()
        self.weight_label.pack()
        self.travel_label.pack()
        
        self.pack(fill=BOTH, expand=1)
Ejemplo n.º 6
0
    def create_widgets(self):
        """ Login form """

        frame_top = Frame(self, pady=15, padx=15)
        frame_top.pack()

        self.email = StringVar()
        self.email_label = Label(frame_top, text="Email")
        self.email_entry = Entry(frame_top, textvariable=self.email)

        self.password = StringVar()
        self.password_label = Label(frame_top, text="Password")
        self.password_entry = Entry(frame_top,
                                    textvariable=self.password, show='*')

        frame_bottom = Frame(self, pady=15, padx=15)
        frame_bottom.pack()

        self.submit = Button(frame_bottom)
        self.submit["text"] = "Login"
        self.submit["command"] = self.sign_in

        #layout widgets in grid
        self.email_label.grid(row=1, column=0)
        self.email_entry.grid(row=1, column=1)
        self.password_label.grid(row=2, column=0)
        self.password_entry.grid(row=2, column=1)
        self.submit.grid(row=2, column=0)
Ejemplo n.º 7
0
 def __init__(self, master):
     self.top = Toplevel(master)
     self.entry_width = 15
     self.set_none_limits()
     self.real_max_label = Label(self.top, text="Real Max: ")
     self.real_min_label = Label(self.top, text="Real Min: ")
     self.imag_max_label = Label(self.top, text="Imag Max: ")
     self.imag_min_label = Label(self.top, text="Imag Min: ")
     self.real_max_entry = Entry(self.top, width=self.entry_width)
     self.real_min_entry = Entry(self.top, width=self.entry_width)
     self.imag_max_entry = Entry(self.top, width=self.entry_width)
     self.imag_min_entry = Entry(self.top, width=self.entry_width)
     self.submit_button = Button(self.top, text="Submit", command=self.submit)
     self.cancel_button = Button(self.top, text="Cancel", command=self.top.destroy)
     self.real_max_label.grid(row=0, column=0)
     self.real_min_label.grid(row=1, column=0)
     self.imag_max_label.grid(row=2, column=0)
     self.imag_min_label.grid(row=3, column=0)
     self.real_max_entry.grid(row=0, column=1)
     self.real_min_entry.grid(row=1, column=1)
     self.imag_max_entry.grid(row=2, column=1)
     self.imag_min_entry.grid(row=3, column=1)
     self.submit_button.grid(row=4, column=0)
     self.cancel_button.grid(row=4, column=1)
     self.top.bind("<Return>", self.submit)
     self.top.bind("<Escape>", self.top.destroy)
     self.real_max_entry.focus()
Ejemplo n.º 8
0
    def _reset_controls(self):
        """ Resets the controls on the form. """
        image = ImageTk.PhotoImage(file="bg.png")
        
        # Initialize controls
        self.lbl_bg = Label(self, image=image)
        self.lbl_dir = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.lbl_anon = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.lbl_id = Label(self, bg="white", fg="#668FA7", font=("Courier", 14))
        self.btn_dir_select = Button(self, text="Select data folder", command=self._btn_dir_press)
        self.btn_id = Button(self, text="Identify data", command=self._btn_id_press)
        self.btn_anon = Button(self, text="Anonymize data", command=self._btn_anon_press)
        self.tb_study = Entry(self, bg="#668FA7", fg="white")
        self.prg_id = Progressbar(self, orient="horizontal", length=200, mode="determinate")
        self.prg_anon = Progressbar(self, orient="horizontal", length=200, mode="determinate")

        # Place controls
        self.lbl_bg.place(x=0, y=0, relwidth=1, relheight=1)
        self.lbl_anon.place(x=400, y=400)
        self.lbl_id.place(x=400, y=325)
        self.btn_dir_select.place(x=250, y=250)
        self.btn_id.place(x=250, y=325)
        self.btn_anon.place(x=250, y=400)
        self.tb_study.place(x=250, y=175)
        self.prg_id.place(x=410, y=290)
        self.prg_anon.place(x=410, y=370)

        # Other formatting
        self.lbl_bg.image = image
        self.btn_id['state'] = "disabled"
        self.btn_anon['state'] = "disabled"
        self.prg_id['maximum'] = 100
        self.prg_anon['maximum'] = 100
Ejemplo n.º 9
0
 def _initfilepanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=0, sticky=E + W + S + N)
     
     label = Label(frame, text="File List: ")
     label.grid(sticky=N + W)
     
     self.filelist = Listbox(frame, width=40)
     self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
     
     self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection)
     
     hsl.config(command=self.filelist.xview)
     vsl.config(command=self.filelist.yview)
     
     upbtn = Button(frame, text="Up", width=7, command=self._upfile)
     upbtn.grid(row=1, column=4, padx=5, pady=5)
     
     downbtn = Button(frame, text="Down", width=7, command=self._downfile)
     downbtn.grid(row=2, column=4, padx=5, pady=5)
     
     newbtn = Button(frame, text="New", width=7, command=self._addfile)
     newbtn.grid(row=4, column=1, pady=5, sticky=E + S)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletefile)
     delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S)
Ejemplo n.º 10
0
def ua_win_tk(url, pipe = None):
    from tkinter import Tk, Frame, Label, Entry, StringVar, BOTH, Button, RIGHT
    import sys
    sys.stdout.flush()
    instructions = "Visit the following URL to authorize the application:"
    response = {"x": False}
    root = Tk()
    root.title("oAuth2 Authorization Required")
    webbox = Frame(root)
    instructions = Label(webbox, text = instructions)
    instructions.pack(padx = 5, pady = 5)
    urlstr = StringVar(value = url)
    urlbox = Entry(webbox, textvariable = urlstr, state = "readonly")
    urlbox.pack(padx = 5, pady = 5)
    def open_browser():
        from subprocess import Popen
        p = Popen(["sensible-browser", url])
    browserbutton = Button(webbox, text = "Open in web browser", command = open_browser)
    browserbutton.pack(padx = 5, pady = 5)
    webbox.pack(fill = BOTH, expand = 1)
    if pipe:
        def poll():
            if pipe.poll():
                root.destroy()
                #Mutability ftw... wat
                response["x"] = True
            else:
                root.after(300, poll)
        root.after(300, poll)
    cancelbutton = Button(root, text = "Cancel", command = root.destroy)
    cancelbutton.pack(side = RIGHT, padx = 5, pady = 5)
    root.mainloop()
    return response["x"]
Ejemplo n.º 11
0
def display_image(title,image):
    win = Toplevel(root)
    photo = ImageTk.PhotoImage(image)
    win.title(title)
    label = Label(win,image=photo)
    label.image = photo #Kludge: keep a reference to avoid garbage collection!
    label.pack()
Ejemplo n.º 12
0
 def _initjoincondpanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5)
     
     label = Label(frame, text="Join Condition: ")
     label.grid(sticky=N + W)
     
     self.joincondlist = Listbox(frame)
     self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
     
     self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     
     hsl.config(command=self.joincondlist.xview)
     vsl.config(command=self.joincondlist.yview)
     
     newbtn = Button(frame, text="New", width=7, command=self._addjoincondition)
     newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletejoincondition)
     delbtn.grid(row=3, column=1, sticky=E)
     
     modbtn = Button(frame, text="Update", width=7, command=self._modifyjoincondition)
     modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
Ejemplo n.º 13
0
 def view_new_title(self, Medikom, entry_type):
     self.selected_id = False
     self.overview(Medikom)
     if entry_type == 0:
         text = "Titel der neuen Aufgabe:"
     elif entry_type == 1:
         text = "Titel der neuen Information:"
     details_label = Label(
         self, text=text, font='Liberation 10',
         fg='Black')
     details_label.place(
         x=self.SPACE_TWO / 2,
         y=(self.n + 2) * (self.ROW_HIGHT + self.ROW_SPACE),
         width=self.WIN_WIDTH - self.SPACE_TWO, height=self.ROW_HIGHT)
     textframe = Text(self, font='Liberation 12', height=1, width=int(self.WIN_WIDTH / 4))
     textframe.place(
         x=self.SPACE_TWO, y=(self.n + 3) * (self.ROW_HIGHT + self.ROW_SPACE),
         width=self.WIN_WIDTH - self.SPACE_ONE - 10, height=self.ROW_HIGHT)
     create_button = Button(
         self, text='Erstellen',
         command=lambda: self.add_entry(Medikom, entry_type, textframe.get(1.0, END).strip()))
     create_button.place(
         x=(self.WIN_WIDTH / 2) - (self.WIN_WIDTH / 16),
         y=(self.n + 4) * (self.ROW_HIGHT + self.ROW_SPACE),
         width=self.WIN_WIDTH / 8, height=self.ROW_HIGHT)
Ejemplo n.º 14
0
class statusBar(Frame):
    def __init__(self):
        """ Create the initial application GUI environment (tool bars, and other static elements) """
        Frame.__init__(self)
        self.messageText = Label()
        self.messageText['text'] = "Thread #:"
        self.messageText.pack()
Ejemplo n.º 15
0
class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT) # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
Ejemplo n.º 16
0
    def __init__(self, root):
        
        # create labels and frames with initial values and bind them
        self.root = root
        self.main = Frame(root)
        
        self.header = Frame(root)
        self.header_label = Label(self.header, text='2048 Game')
        self.score_label = Label(self.header)
        self.turn_label = Label(self.header, wraplength=150, height=3)        
        self.reset = Button(self.header, text="Restart", command = self.new_board)
        self.reset.pack()
        self.header.pack()
        self.header_label.pack()
        self.score_label.pack()
        self.turn_label.pack()
        self.main.pack()
        self.root.bind('<Left>', self.game_play)
        self.root.bind('<Right>', self.game_play)
        self.root.bind('<Up>', self.game_play)
        self.root.bind('<Down>', self.game_play)
        
        self.new_board()

        # start tkinter gui
        self.root.mainloop()
Ejemplo n.º 17
0
    def home_page(self, master):
        frame = Frame(master)
        frame.grid(row=0, column=0)

        image = PhotoImage(file="img/guido.gif")
        bg = Label(frame, image=image)
        bg.image = image
        bg.grid(row=0, column=0, rowspan=4, columnspan=2)

        index = 0
        while index < 3:
            frame.grid_columnconfigure(index, minsize=200)
            frame.grid_rowconfigure(index, minsize=80)
            index += 1

        summary_button = HomeButton(frame, self.to_summary, 'img/summary.png')
        summary_button.grid(row=0, column=0, sticky='w')

        edit_button = HomeButton(frame, self.to_edit, 'img/edit.png')
        edit_button.grid(row=0, column=1, sticky='e')

        momentary_button = HomeButton(frame, self.to_momentary, 'img/momentary.png')
        momentary_button.grid(row=1, column=0, sticky='w')

        preferences_button = HomeButton(frame, self.to_pref, 'img/preferences.png')
        preferences_button.grid(row=1, column=1, sticky='e')

        music = HomeButton(frame, self.to_summary, 'img/music.png')
        music.grid(row=2, column=0, sticky='w')

        info = HomeButton(frame, self.to_summary, 'img/info.png')
        info.grid(row=2, column=1, sticky='e')

        return frame
Ejemplo n.º 18
0
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

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

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

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

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

        # LAYOUT
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=5, sticky=W + E)
        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.multiply_button.grid(row=2, column=2)
        # self.divide_button.grid(row=2, column=3)
        self.reset_button.grid(row=2, column=4, sticky=W + E)
Ejemplo n.º 19
0
    def initialize(self):
        self.top = Frame(self.canvas)
        self.top.grid(row=0,column=0, columnspan=3, padx=5, pady=10)

        self.label = Label(self.top, text="PATH :", anchor="w", fg="black")
        self.label.pack(side=LEFT)

        self.pathEntry = Entry(self.top, textvariable=self.trackPath, width="75")
        self.pathEntry.pack(side=LEFT, padx=5)


        self.sliderFrame = Frame(self.canvas)
        self.sliderFrame.grid(row=1, column=0,columnspan=4, pady=10, padx=5)


        for i in range(10):
            slider = SliderFrequency(self.sliderFrame, self.freqs[i],10.0,0.0,20.0, i)
            self.sliders.append(slider)


        self.infoLabel = Label(self.canvas, text="", textvariable=self.info)
        self.infoLabel.grid(row=2, column=0,columnspan=2)
        self._afficheInfo("Choose music to equalize")

        self.startBtn = Button(self.canvas, text="Start", command=self.start)
        self.startBtn.grid(row=2, column=2, pady=10)
        self.startBtn = Button(self.canvas, text="Reset", command=self.reset)
        self.startBtn.grid(row=2, column=3, pady=10)
Ejemplo n.º 20
0
 def __init__(self, method=None, master=None):
     self.method = method
     self.picframe = Frame.__init__(self, master)
     self.master.title("Robobackup")
     self.image = PhotoImage()
     self.image["file"] = os.path.join(os.path.dirname(\
         os.path.relpath(__file__)), "resources", "ASK.png")
     self.piclabel = Label(self.picframe, image=self.image)
     self.piclabel.grid(row=0, column=0, columnspan=4, rowspan=6)
     self.clocklabel = Label(self.picframe, text=_("Elapsed time:"))
     self.clocklabel.grid(row=0, column=4, sticky="NSEW")
     self.clock = Label(self.picframe, text="")
     self.clock.grid(row=1, column=4, sticky="NSEW")
     self.start = Button(self.picframe, text=_("Start Backup"), command=self.__clk)
     self.start.grid(row=3, column=4, sticky="NSEW")
     self.errorlabel = Label(self.picframe)
     self.errorlabel.grid(row=4, column=4, sticky="NSEW")
     self.close = Button(self.picframe, text=_("Close"), command=self.__cls)
     self.close.grid(row=5, column=4, sticky="NSEW")
     self.loglabel = Label(self.picframe, text=_("Log:"), justify="left")
     self.loglabel.grid(row=6, column=0, columnspan=5, sticky="NSEW")
     self.text = Text(self.picframe)
     self.text.grid(row=7, column=0, rowspan=6, columnspan=5, sticky="NSEW")
     self.timeout = False
     self.starttime = -1
Ejemplo n.º 21
0
 def __init__(self, master):
     """
     Establish the GUI of this popup
     """
     BuilderPopup.__init__(self, master)
     self.top_left = complex(0, 0)
     self.bottom_right = complex(0, 0)
     self.lines = 0
     self.top_left_label = Label(self.top, text="\"Top Left\"")
     self.top_left_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.bottom_right_label = Label(self.top, text="\"Bottom Right\"")
     self.bottom_right_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.resolution_label = Label(self.top, text="Lines")
     self.resolution_entry = Entry(self.top, width=5)
     self.build_grid_submit = Button(self.top, text="Build!", command=self.cleanup)
     self.top.bind("<Return>", self.cleanup)
     self.top_left_label.grid(row=0, column=0)
     self.top_left_entry.grid(row=0, column=1)
     self.bottom_right_label.grid(row=1, column=0)
     self.bottom_right_entry.grid(row=1, column=1)
     self.resolution_label.grid(row=2, column=0)
     self.resolution_entry.grid(row=2, column=1)
     self.build_grid_submit.grid(row=3, column=0, columnspan=2)
     self.top_left_entry.focus()
     self.data = (0, 0, 0)
Ejemplo n.º 22
0
class CircleBuilderPopup(BuilderPopup):
    """
    Class that launches a popup and collects user data to pass data back to the main window
    to build a circle.
    """
    def __init__(self, master):
        """
        Establish the GUI of this popup
        """
        BuilderPopup.__init__(self, master)
        self.data = (0, 0)
        self.radius = Label(self.top, text="Radius")
        self.radius_entry = Entry(self.top, width=self.width, bd=self.bd)
        self.center = Label(self.top, text="Center")
        self.center_entry = Entry(self.top, width=self.width, bd=self.bd)
        self.build_circle_submit = Button(self.top, text="Build!", command=self.cleanup)
        self.top.bind("<Return>", self.cleanup)
        self.radius.grid(row=0, column=0)
        self.radius_entry.grid(row=0, column=1)
        self.center.grid(row=1, column=0)
        self.center_entry.grid(row=1, column=1)
        self.build_circle_submit.grid(row=2, column=0, columnspan=2)
        self.top_left = 0
        self.bottom_right = 0
        self.radius_entry.focus()

    def cleanup(self, entry=None):
        """
        Collect the data from the user and package it into object variables, then close.
        """
        center = complex(0, 0)
        if self.center_entry.get():
            center = complex(allow_constants(self.center_entry.get()))
        self.data = (float(allow_constants(self.radius_entry.get())), center)
        self.top.destroy()
Ejemplo n.º 23
0
class InfoWindow(Toplevel):

    def __init__(self, master=None, text=None, textvariable=None, title=None,
                 font=tkinter.font.nametofont("TkHeadingFont"), **kw):
        Toplevel.__init__(self, master, **kw)
        self._window(master, title, text, textvariable, font)

    def _window(self, master, title, text, textvariable, font):
        title = title if title is not None else _("{prg}").format(prg=PROGNAME)
        self.title(title)
        self.protocol("WM_DELETE_WINDOW", self._doNotQuit)
        self.resizable(width=False, height=False)
        self.transient(master)

        if text is not None:
            kwargs = {"text": text}
        else:
            kwargs = {"textvariable": textvariable}

        self.label = Label(self, borderwidth=20, font=font, **kwargs)
        self.label.pack()
        self.update_idletasks()
        self.grab_set()         # make the dialog modal

    def _doNotQuit(self):
        """Dumb method to override window's close button."""
        return
Ejemplo n.º 24
0
Archivo: tkui.py Proyecto: mindhog/mawb
class ProgramWidget(Frame):

    def __init__(self, parent, client):
        super(ProgramWidget, self).__init__(parent)
        self.client = client
        self.client.onProgramChange = self.programChanged

        self.programLabel = Label(self, text = 'Program:')
        self.programLabel.grid(row = 0, column = 0)
        self.programEntry = Entry(self, text = 'Program name',
                                  state = 'readonly')
        self.programEntry.grid(row = 0, column = 1)
        self.buttonPanel = Frame(self)
        self.buttonPanel.grid(row = 1, column = 0, columnspan = 2, sticky = W)
        self.newButton = Button(self.buttonPanel, text='New',
                                command = self.newProgram)
        self.newButton.pack(side = LEFT)

    def programChanged(self):
        self.__setProgramText(str(self.client.state))

    def __setProgramText(self, text):
        self.programEntry.configure(state = NORMAL)
        self.programEntry.delete(0)
        self.programEntry.insert(0, text)
        self.programEntry.configure(state = 'readonly')

    def newProgram(self):
        self.client.makeNewProgram()
Ejemplo n.º 25
0
    def __init__(self,master):

        self.master = master
        self.nupud = []
        self.laua_suurus = 15
        self.laua_suurusR = self.laua_suurus ** 2
        self.kaik = 0
        self.alustav_mangija = 6
        
        self.main_frame = Frame(master)
        self.main_frame.pack(fill="both", expand=True)
        self.label = Label(self.main_frame, text='Andre Gomoku', height=2, bg='white smoke', fg='darkblue')
        self.label.pack(fill="both", expand=True)

        self.ülemine_frame = Frame(self.main_frame)
        self.ülemine_frame.pack(fill="both", expand=True)
        self.player1 = Label(self.ülemine_frame, text="Player1 score: 0", height=1, bg='white', fg='purple')
        self.player1.pack(fill="both", expand=True, side=LEFT)
        self.player2 = Label(self.ülemine_frame, text="Player2 score: 0", height=1, bg='white', fg='green')
        self.player2.pack(fill="both", expand=True, side=RIGHT)
        
        self.label.pack(fill="both", expand=True)
        self.canvas = Canvas(self.main_frame, width=525, height=425)
        self.canvas.pack(fill="both", expand=True)
        
        self.alumine_frame = Frame(self.main_frame)
        self.alumine_frame.pack(fill="both", expand=True)
        
        self.vs_inimene = Button(self.alumine_frame, text='Vajuta siia, et mängida Sõbra vastu',
                                 command=self.inimene_inimene, height=2, bg='white', fg='purple')
        self.vs_inimene.pack(fill="both", expand=True, side=LEFT)
        self.vs_arvuti = Button(self.alumine_frame, text='Vajuta siia, et mängida Arvuti vastu',
                                command=self.inimene_arvuti, height=2, bg='white', fg='green')
        self.vs_arvuti.pack(fill="both", expand=True, side=RIGHT)
Ejemplo n.º 26
0
class _Testdialog:
    """Only used to test dialog from CLI"""
    def __init__(self, master):
        """Initialize CLI test GUI"""
        frame = Frame(master, width=300, height=300)
        self.master = master
        self.x, self.y, self.w, self.h = -1,-1,-1,-1

        self.Button_1 = Button(frame, text="My Popup", relief="raised", width="15")
        self.Button_1.pack()
        self.Button_1.bind("<ButtonRelease-1>", self.Button_1_Click)

        statframe = Frame(frame)
        master.statusMessage = StringVar()
        master.statusMessage.set('Welcome')
        self.statusbar = Label(statframe, textvariable=master.statusMessage,
                               bd=1, relief=SUNKEN, anchor=W)
        self.statusbar.pack(anchor=SW, fill=X, side=BOTTOM)
        statframe.pack(anchor=SW, fill=X, side=BOTTOM)
        self.dx = 30
        self.dy = 30

        frame.pack()

        self.dialog = None

    # pylint: disable=W0613
    def Button_1_Click(self, event): #click method for component ID=1
        """Launch Select_Py_Version for CLI testing."""
        self.dialog = SatelliteWindow(self, self.master, "Test Dialog", dx=self.dx, dy=self.dy)
        self.dx += 30
        self.dy += 30
Ejemplo n.º 27
0
 def __init__(self, master):
     """
     Establish the GUI of this popup
     """
     BuilderPopup.__init__(self, master)
     self.data = (0, 0, 0)
     self.radius = Label(self.top, text="Radius")
     self.radius_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.n_circles_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.n_circles_label = Label(self.top, text="Number of circles")
     self.center = Label(self.top, text="Center")
     self.center_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.spindles = Label(self.top, text="Number of \"Roots\"")
     self.spindles_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.build_spindle_submit = Button(self.top, text="Build!", command=self.cleanup)
     self.top.bind("<Return>", self.cleanup)
     self.radius.grid(row=0, column=0)
     self.radius_entry.grid(row=0, column=1)
     self.n_circles_label.grid(row=1, column=0)
     self.n_circles_entry.grid(row=1, column=1)
     self.center.grid(row=2, column=0)
     self.center_entry.grid(row=2, column=1)
     self.spindles_entry.grid(row=3, column=1)
     self.spindles.grid(row=3, column=0)
     self.build_spindle_submit.grid(row=4, column=0, columnspan=2)
     self.top_left = 0
     self.bottom_right = 0
     self.radius_entry.focus()
Ejemplo n.º 28
0
class InfoFrame(Frame):
    def __init__(self,master=None, thread=None):
        Frame.__init__(self, master)
        self.controlThread=thread
        
        self.stringVar=StringVar()
        
        self.grid()
        self.createWidgets()
        
    def createWidgets(self):
        self.inputText=Label(self)
        if self.inputText != None:
            self.inputText['textvariable']=self.stringVar
            self.inputText["width"] = 50
            self.inputText.grid(row=0, column=0, columnspan=6)
        else:
            pass
        
        
        self.cancelBtn = Button(self, command=self.clickCancelBtn)   # need to implement
        if self.cancelBtn !=None:
            self.cancelBtn["text"] = "Cancel"
            self.cancelBtn.grid(row=0, column=6)
        else:
            pass
        
    def clickCancelBtn(self):
        print("close the InfoDialog")
        self.controlThread.setStop()
            
    def updateInfo(self, str):
        self.stringVar.set(str)
Ejemplo n.º 29
0
def goodUser():
    errorMsg = Tk()

    goodCRN = Label(errorMsg, text="Please enter a valid Villanova username")

    goodCRN.pack()
    errorMsg.mainloop()
Ejemplo n.º 30
0
    return_value(temp + 1)
    position_track.set(temp + 1)
    update_value(temp + 1)


def prev_value():
    global position_track
    if position_track.get() == -1:
        position_track.set(len(name_array) - 1)
    temp = position_track.get()
    return_value(temp - 1)
    position_track.set(temp - 1)
    update_value(temp - 1)


label_first_name = Label(window, text='First Name:', justify='right', padx=5)
entry_first_name = Entry(window, textvariable=first_name)
label_last_name = Label(window, text='Last Name:', justify='right', padx=5)
entry_last_name = Entry(window, textvariable=last_name)
label_email = Label(window, text='Email Address:', justify='right', padx=5)
entry_email = Entry(window, textvariable=email)

button_first = Button(window, text='First', command=first_value)
button_last = Button(window, text='Last', command=last_value)
button_prev = Button(window, text='Prev', command=prev_value)
button_next = Button(window, text='Next', command=next_value)
button_quit = Button(window, text='Quit')
button_quit.configure(command=window.destroy)

labels = [label_first_name, label_last_name, label_email]
entries = [entry_first_name, entry_last_name, entry_email]
Ejemplo n.º 31
0
def draw():
    """draw the default layout."""
    c_row = 0
    for region in CFG['TimeZones']:
        for city in CFG['TimeZones'][region]:
            o_city = CFG['TimeZones'][region][city]
            c_row += 1
            FRAME[city] = {}
            LABEL_DESC[city] = {}

            for i in range(0, 3):
                FRAME[city][i] = Frame(
                    ROOT,
                    width=CFG['defaults']['frame']['width'],
                    height=CFG['defaults']['frame']['height'],
                    background=CFG['defaults']['colors']['background'])

                FRAME[city][i].grid(row=c_row - 1, column=i, sticky=W)

            desc = o_city.get('description', o_city['tz'])

            city_colors = CFG['defaults']['colors'].copy()
            if 'colors' in o_city:
                for cell in o_city['colors']:
                    city_colors[cell] = o_city['colors'][cell]

            _background = CFG['defaults']['colors']['background']
            _font = (CFG['defaults']['label']['font']['face'],
                     CFG['defaults']['label']['font']['size'],
                     CFG['defaults']['label']['font']['weight'])
            _padx = CFG['defaults']['label']['padding']['x']
            _pady = CFG['defaults']['label']['padding']['y']
            _justify = CFG['defaults']['label']['justify']

            LABEL_DESC[city] = Label(FRAME[city][0],
                                     text=desc,
                                     background=_background,
                                     fg=city_colors['description'],
                                     font=_font,
                                     padx=_padx,
                                     pady=_pady,
                                     justify=_justify)
            LABEL_T[city] = Label(FRAME[city][1],
                                  text=desc,
                                  background=_background,
                                  fg=city_colors['time'],
                                  font=_font,
                                  padx=_padx,
                                  pady=_pady,
                                  justify=_justify)
            LABEL_D[city] = Label(FRAME[city][2],
                                  text=desc,
                                  background=_background,
                                  fg=city_colors['date'],
                                  font=_font,
                                  padx=_padx,
                                  pady=_pady,
                                  justify=_justify)

            LABEL_DESC[city].pack()
            LABEL_T[city].pack()
            LABEL_D[city].pack()
Ejemplo n.º 32
0
window = Tk()
window.title("Feet to Meter Conversion App")
window.configure(background="light green")
window.geometry("320x220")
window.resizable(width=False,height=False)

def convert():
    value = float(ft_entry.get())
    meter = value * 0.3048
    mt_value.set("%.4f" % meter)




ft_lbl = Label(window,text="Feet",bg="purple",fg="white",width=14)
ft_lbl.grid(column=0,row=0,padx=15,pady=15)

ft_value = DoubleVar()
ft_entry = Entry(window,textvariable=ft_value,width=14)
ft_entry.grid(column=1,row=0)
ft_entry.delete(0,'end')

ft_lbl = Label(window,text="Feet",bg="purple",fg="white",width=14)
ft_lbl.grid(column=0,row=0,padx=15,pady=15)

mt_lbl = Label(window,text="Meter",bg="brown",fg="white",width=14)
mt_lbl.grid(column=0,row=1)

mt_value = DoubleVar()
mt_entry = Entry(window,textvariable=mt_value,width=14)
Ejemplo n.º 33
0
 def iniciar_labels(self, painel):
     # Labels Fixas
     label1 = Label(painel, text="Bem Vindo ao Muzic Player!")
     label2 = Label(painel, text="Selecione a música que você deseja ouvir")
     # Labels com os dados do Objeto Musica
     label_nome_musica = Label(painel, text="Nome: Ilustrativo")
     label_artista_musica = Label(painel, text="Artista: Inventado")
     label_album_musica = Label(painel, text=f"Album: Iluminismo")
     # Label Grids
     label1.grid(row=0, column=1)
     label2.grid(row=1, column=1)
     label_nome_musica.grid(row=2, column=1)
     label_artista_musica.grid(row=3, column=1)
     label_album_musica.grid(row=4, column=1)
Ejemplo n.º 34
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 20:14:27 2020

@author: guill
"""


from tkinter import Tk, Label, Entry, RAISED

root = Tk()

#Mortgage
label = Label(root, text='Loan Amount:')
label.grid(row=1, column=0)

Ent = Entry(root)
Ent.grid(row=1, column=1)

label = Label(root, text='Interest rate:')
label.grid(row=2, column=0)

Ent = Entry(root)
Ent.grid(row=2, column=1)

label = Label(root, text='Loan terms:')
label.grid(row=3, column=0)

Ent = Entry(root)
Ent.grid(row=3, column=1)
Ejemplo n.º 35
0
def main():

    bot = Tk()
    bot.title('telegram bot')
    bot.geometry("500x200")

    # string var
    st = StringVar()
    img = StringVar()
    btex = StringVar()
    burl = StringVar()
    tim = StringVar()
    st.set('please submit details..')

    image = Label(bot, text='image location')
    image.grid(row=0, column=0, padx=5, pady=5)
    image_loc = Entry(bot, textvariable=img)
    image_loc.grid(row=0, column=1, padx=5, pady=5)

    button = Label(bot, text='button text')
    button.grid(row=1, column=0, padx=5, pady=5)
    button_text = Entry(bot, textvariable=btex)
    button_text.grid(row=1, column=1, padx=5, pady=5)

    button_u = Label(bot, text='button url')
    button_u.grid(row=2, column=0, padx=5, pady=5)
    button_url = Entry(bot, textvariable=burl)
    button_url.grid(row=2, column=1, padx=5, pady=5)

    time = Label(bot, text='time')
    time.grid(row=3, column=0, padx=5, pady=5)
    time_mint = Entry(bot, textvariable=tim)
    time_mint.grid(row=3, column=1, padx=5, pady=5)

    submit_add = Button(
        bot,
        text="Submit add",
        width=10,
        command=lambda: start_add_fun(st, img, burl, btex, tim, status))
    submit_add.grid(row=5, column=1, padx=10, pady=10)

    status = Label(bot, textvariable=st, bg='blue', fg='white')
    status.grid(row=0, column=4, padx=0, pady=5)

    delete_add = Button(
        bot,
        text="Delete add",
        width=10,
        command=lambda: delete_add_fun(st, img, burl, btex, tim, status))
    delete_add.grid(row=1, column=4, padx=10, pady=10)

    lab = Label(bot, text='Status:-')
    lab.grid(row=0, column=3, padx=20, pady=5)

    txt = Label(bot, text='text')
    txt.grid(row=0, column=4, padx=0, pady=5)

    text = Text(
        bot,
        width=10,
        command=lambda: delete_add_fun(st, img, burl, btex, tim, status))
    text.grid(row=1, column=4, padx=10, pady=10)
    bot.mainloop()
Ejemplo n.º 36
0
 def __init__(self):
     self.path = Path(__file__).parent.absolute(
     )  #Получаем абсолютный путь к директории текущего файла
     self.toaster = ToastNotifier()
     self.window = Tk()
     self.timer = [
         0, 0
     ]  #Список для хранения и вычисления значений минут и секунд (timer[0] - минуты, timer[1] - секунды)
     self.pomodorocount = 0  #Переменная для хранения выполненных помидоров
     self.status = 1  #Переменная для определения состояния (0 - работа, 1 - короткий отдых, 2 - длинный отдых)
     self.after_id = 0  #Переменная для хранения идентификатора метода after (Для остановки таймера будем передавать этот идентификатор в метод after_cancel)
     self.timestr = str(self.timer[0]) + ':' + str(
         self.timer[1]
     )  #Переменная типа str для обновления метки с таймером
     self.window.title('Pomodoro Timer')
     self.window.geometry('400x400')
     self.label_work = Label(text='Время работы')
     self.frame_work = Frame()  #Используется для группировки виджетов
     self.entry_m_work = Entry(self.frame_work, width=5)
     self.entry_s_work = Entry(self.frame_work, width=5)
     text = '25'
     self.entry_m_work.insert(
         0, text)  #Прописываем начальные значения в поле ввода
     text = '0'
     self.entry_s_work.insert(0, text)
     self.label_relax = Label(text='Время отдыха')
     self.frame_relax = Frame()
     self.entry_m_relax = Entry(self.frame_relax, width=5)
     self.entry_s_relax = Entry(self.frame_relax, width=5)
     text = '5'
     self.entry_m_relax.insert(0, text)
     text = '0'
     self.entry_s_relax.insert(0, text)
     self.label_longrelax = Label(text='Время длинного отдыха')
     self.frame_longrelax = Frame()
     self.entry_m_longrelax = Entry(self.frame_longrelax, width=5)
     self.entry_s_longrelax = Entry(self.frame_longrelax, width=5)
     text = '30'
     self.entry_m_longrelax.insert(0, text)
     text = '0'
     self.entry_s_longrelax.insert(0, text)
     self.label_infopomodoro = Label(text='Выполнено помидоров: {}'.format(
         self.pomodorocount),
                                     font=("Times", 20))
     self.label_infostatus = Label(text='Начните работу!',
                                   fg="blue",
                                   font=("Times", 20))
     self.label_time = Label(text='0:0', font=("Area", 100))
     self.frame_button = Frame()
     self.button_start = Button(self.frame_button,
                                width=5,
                                text='Старт',
                                command=self.start)
     self.button_reset = Button(self.frame_button,
                                width=10,
                                text='Перезапуск',
                                command=self.reset,
                                state='disabled')
Ejemplo n.º 37
0
class pomodoro():
    def __init__(self):
        self.path = Path(__file__).parent.absolute(
        )  #Получаем абсолютный путь к директории текущего файла
        self.toaster = ToastNotifier()
        self.window = Tk()
        self.timer = [
            0, 0
        ]  #Список для хранения и вычисления значений минут и секунд (timer[0] - минуты, timer[1] - секунды)
        self.pomodorocount = 0  #Переменная для хранения выполненных помидоров
        self.status = 1  #Переменная для определения состояния (0 - работа, 1 - короткий отдых, 2 - длинный отдых)
        self.after_id = 0  #Переменная для хранения идентификатора метода after (Для остановки таймера будем передавать этот идентификатор в метод after_cancel)
        self.timestr = str(self.timer[0]) + ':' + str(
            self.timer[1]
        )  #Переменная типа str для обновления метки с таймером
        self.window.title('Pomodoro Timer')
        self.window.geometry('400x400')
        self.label_work = Label(text='Время работы')
        self.frame_work = Frame()  #Используется для группировки виджетов
        self.entry_m_work = Entry(self.frame_work, width=5)
        self.entry_s_work = Entry(self.frame_work, width=5)
        text = '25'
        self.entry_m_work.insert(
            0, text)  #Прописываем начальные значения в поле ввода
        text = '0'
        self.entry_s_work.insert(0, text)
        self.label_relax = Label(text='Время отдыха')
        self.frame_relax = Frame()
        self.entry_m_relax = Entry(self.frame_relax, width=5)
        self.entry_s_relax = Entry(self.frame_relax, width=5)
        text = '5'
        self.entry_m_relax.insert(0, text)
        text = '0'
        self.entry_s_relax.insert(0, text)
        self.label_longrelax = Label(text='Время длинного отдыха')
        self.frame_longrelax = Frame()
        self.entry_m_longrelax = Entry(self.frame_longrelax, width=5)
        self.entry_s_longrelax = Entry(self.frame_longrelax, width=5)
        text = '30'
        self.entry_m_longrelax.insert(0, text)
        text = '0'
        self.entry_s_longrelax.insert(0, text)
        self.label_infopomodoro = Label(text='Выполнено помидоров: {}'.format(
            self.pomodorocount),
                                        font=("Times", 20))
        self.label_infostatus = Label(text='Начните работу!',
                                      fg="blue",
                                      font=("Times", 20))
        self.label_time = Label(text='0:0', font=("Area", 100))
        self.frame_button = Frame()
        self.button_start = Button(self.frame_button,
                                   width=5,
                                   text='Старт',
                                   command=self.start)
        self.button_reset = Button(self.frame_button,
                                   width=10,
                                   text='Перезапуск',
                                   command=self.reset,
                                   state='disabled')

    def pack(self):
        #Используем метод pack для виджетов в этой функции
        self.label_work.pack()
        self.frame_work.pack()
        self.entry_m_work.pack(side=LEFT)
        self.entry_s_work.pack(side=LEFT)
        self.label_relax.pack()
        self.frame_relax.pack()
        self.entry_m_relax.pack(side=LEFT)
        self.entry_s_relax.pack(side=LEFT)
        self.label_longrelax.pack()
        self.frame_longrelax.pack()
        self.entry_m_longrelax.pack(side=LEFT)
        self.entry_s_longrelax.pack(side=LEFT)
        self.label_infopomodoro.pack()
        self.label_infostatus.pack()
        self.label_time.pack()
        self.frame_button.pack()
        self.button_start.pack(side=LEFT)
        self.button_reset.pack(side=LEFT)

    def start(self):
        #Функция вызывается при нажатии кнопки Start
        self.button_start.configure(state='disabled')
        self.button_reset.configure(state='active')
        self.status_check()

    def tick(self):
        #Функция для обновления таймера
        self.timer[1] -= 1  #Вычитаем одну секунду
        if self.timer[1] == -1:  #Когда значение становится -1:
            self.timer[1] = 59  #Устанавливаем значение секунд в 59
            self.timer[0] -= 1  #Вычитаем одну минуту
        self.timestr = str(self.timer[0]) + ':' + str(
            self.timer[1]
        )  #Объединяем значения из списка в переменную timestr в виде 0:0
        self.label_time.configure(text=self.timestr)  #Обновляем метку
        self.status_check()  #Вызываем функцию проверки

    def status_check(self):
        #Функция проверки статуса (работаем или отдыхаем)
        if self.timestr == '0:0':  #Проверяем закончилось ли время таймера
            if self.status == 0:  #Если работаем
                self.pomodorocount += 1  #Прибавляем 1 к выполненным помидорам
                self.label_infopomodoro.configure(
                    text='Выполнено помидоров: {}'.format(self.pomodorocount),
                    font=("Times", 20))  #Обновляем метку
                if self.pomodorocount % 4 == 0:  #Если кол-во помидоров кратно 4
                    self.status = 2  #Обновляем статус в 2 (длинный отдых)
                    self.status_change()  #Вызываем функцию изменения статуса
                else:
                    self.status = 1  #Обновляем статус в 1 (короткий отдых)
                    self.status_change()  #Вызываем функцию изменения статуса
            elif self.status == 1 or self.status == 2:  #Если отдыхаем
                self.status = 0  #Обновляем статус в 0 (работа)
                self.status_change()  #Вызываем функцию изменения статуса
        else:
            self.after_id = self.label_time.after(
                1000, self.tick
            )  #Если время не кончилось, вызываем метод after для выполнения функции tick каждую секунду

    def status_change(self):
        #Функция изменения статуса (проверяем значение в переменной status)
        if self.status == 0:  #Работа
            #Показываем уведомление + прописываем абсолютный путь к иконке timer.ico (должная лежать рядом с текущим файлом)
            self.toaster.show_toast("Pomodoro Timer",
                                    "Время работы!",
                                    threaded=True,
                                    icon_path='{}\\timer.ico'.format(
                                        self.path))
            self.label_infostatus.configure(
                text='Время работы!', fg="red",
                font=("Times", 20))  #Обновляем метку со статусом
            self.timer[0] = int(self.entry_m_work.get(
            ))  #Записываем значения полей ввода в список timer
            self.timer[1] = int(self.entry_s_work.get())
        elif self.status == 1:  #Короткий отдых
            self.toaster.show_toast("Pomodoro Timer",
                                    "Время отдыха!",
                                    threaded=True,
                                    icon_path='{}\\timer.ico'.format(
                                        self.path))
            self.label_infostatus.configure(text='Время отдыха!',
                                            fg="green",
                                            font=("Times", 20))
            self.timer[0] = int(self.entry_m_relax.get())
            self.timer[1] = int(self.entry_s_relax.get())
        elif self.status == 2:  #Длинный отдых
            self.toaster.show_toast("Pomodoro Timer",
                                    "Время длинного отдыха!",
                                    threaded=True,
                                    icon_path='{}\\timer.ico'.format(
                                        self.path))
            self.label_infostatus.configure(text='Время длинного отдыха!',
                                            fg="lime",
                                            font=("Times", 20))
            self.timer[0] = int(self.entry_m_longrelax.get())
            self.timer[1] = int(self.entry_s_longrelax.get())
        if self.timer[
                1] > 60:  #Если в поле ввода секунд было значение больше 60, то выставляем значение 60
            self.timer[1] = 60
        if self.timer[
                1] == 0:  #Если в поле ввода секунд был ноль, то вычитаем из минут 1 и выставляем значение секунд в 60
            self.timer[0] -= 1
            self.timer[1] = 60
        self.after_id = self.label_time.after(
            1000, self.tick
        )  #Вызываем метод after для выполнения функции tick каждую секунду

    def reset(self):
        #Функция перезапука таймера - выставляем начальные значения переменных, обновляем метки и кнопки
        self.button_reset.configure(state='disabled')
        self.label_time.after_cancel(
            self.after_id)  #Остановка таймера по идентификатору after
        self.timer = [0, 0]
        self.pomodorocount = 0
        self.status = 1
        self.after_id = 0
        self.timestr = str(self.timer[0]) + ':' + str(self.timer[1])
        self.label_time.configure(text=self.timestr)
        self.button_start.configure(state='active')
        self.label_infopomodoro.configure(
            text='Выполнено помидоров: {}'.format(self.pomodorocount),
            font=("Times", 20))
        self.label_infostatus.configure(text='Начните работу!',
                                        fg="blue",
                                        font=("Times", 20))

    def mainloop(self):
        self.window.mainloop()
class MainWindow():
    # Конструктор класса MainWindow
    def __init__(self):
        # ------------------------------------------------ Переменные класса-------------------------------------------------
        self.image = None
        self.blur_type = IntVar()
        self.angle = None
        self.radius = None
        self.sharpness = None
        self.noise = None
        self.cv_img = None
        self.furier_img = None
        self.psf_pic = None
        self.result_image = None
        self.start_image = None
        self.path = None
        self.res = None
        self.spectrum_res = None
        # -------------------------------------------------- Тип смазывания -------------------------------------------------
        self.label_frame = LabelFrame(root,
                                      text='Types of Blur',
                                      bg='#fffff0',
                                      bd=1,
                                      fg='#696969',
                                      font='Courier 16',
                                      height=100,
                                      width=300)
        self.label_frame.place(relx=0.025, rely=0.025)

        self.rb1 = Radiobutton(self.label_frame,
                               text='Out of focus',
                               background='#fffff0',
                               fg='#696969',
                               font='Courier 14',
                               variable=self.blur_type,
                               value=1,
                               command=lambda par=1: self.process_image(par))
        self.rb1.pack(expand=1, anchor=W)
        self.rb2 = Radiobutton(self.label_frame,
                               text='Motion',
                               background='#fffff0',
                               fg='#696969',
                               font='Courier 14',
                               variable=self.blur_type,
                               value=0,
                               command=lambda par=0: self.process_image(par))
        self.rb2.pack(expand=1, anchor=W)

        # ------------------------------------------------ Параметры ------------------------------------------------
        self.par_frame = LabelFrame(root,
                                    text='Settings',
                                    bg='#fffff0',
                                    bd=1,
                                    fg='#696969',
                                    font='Courier 16',
                                    height=150,
                                    width=300)
        self.par_frame.place(relx=0.025, rely=0.2)

        self.angle_label = Label(self.par_frame,
                                 text='Angle:',
                                 bg='#fffff0',
                                 fg='#696969',
                                 font='Courier 12')
        self.angle_label.pack(expand=1, anchor=W)

        self.angle_scrollbar = Scale(self.par_frame,
                                     bg='#fffff0',
                                     cursor='hand1',
                                     from_=0,
                                     to=180,
                                     orient=HORIZONTAL,
                                     showvalue=1,
                                     relief=FLAT,
                                     length=172,
                                     command=self.process_image)
        self.angle_scrollbar.pack(expand=1, anchor=W)

        self.radius_label = Label(self.par_frame,
                                  text='Radius:',
                                  bg='#fffff0',
                                  fg='#696969',
                                  font='Courier 12')
        self.radius_label.pack(expand=1, anchor=W)

        self.radius_scrollbar = Scale(self.par_frame,
                                      bg='#fffff0',
                                      cursor='hand1',
                                      from_=0,
                                      to=50,
                                      orient=HORIZONTAL,
                                      showvalue=1,
                                      variable=self.radius,
                                      relief=FLAT,
                                      length=172,
                                      command=self.process_image)
        self.radius_scrollbar.pack(expand=1, anchor=W)

        self.sharpness_label = Label(self.par_frame,
                                     text='Sharpness:',
                                     bg='#fffff0',
                                     fg='#696969',
                                     font='Courier 12')
        self.sharpness_label.pack(expand=1, anchor=W)

        self.sharpness_scrollbar = Scale(self.par_frame,
                                         bg='#fffff0',
                                         cursor='hand1',
                                         from_=0,
                                         to=50,
                                         orient=HORIZONTAL,
                                         showvalue=1,
                                         variable=self.sharpness,
                                         relief=FLAT,
                                         length=172,
                                         command=self.process_image)
        self.sharpness_scrollbar.pack(expand=1, anchor=W)

        # ------------------------------------------------ Место для фото ------------------------------------------------
        self.img_frame = LabelFrame(root,
                                    text='',
                                    bg='#fffff0',
                                    bd=1,
                                    height=465,
                                    width=740)
        self.img_frame.place(relx=0.25, rely=0.04)

        self.img_canvas = Canvas(self.img_frame,
                                 bg='#fffff0',
                                 bd=1,
                                 height=465,
                                 width=740)
        self.img_canvas.place(relx=0, rely=0)

        # --------------------------------------------------------------- PSF -----------------------------------------------------------
        self.psf_frame = LabelFrame(root,
                                    text='PSF',
                                    bg='#fffff0',
                                    bd=1,
                                    fg='#696969',
                                    font='Courier 16',
                                    height=172,
                                    width=172)
        self.psf_frame.place(relx=0.025, rely=0.55)

        self.psf_img = Canvas(self.psf_frame,
                              bg='#fffff0',
                              bd=1,
                              height=172,
                              width=172)
        self.psf_img.place(relx=0, rely=0)

        # ------------------------------------------------ О программе ------------------------------------------------
        self.caption = "Welcome!\nApp was created\nby Irina Skurko\nGroup 814301\nBSUIR 2019"
        self.about_label_frame = LabelFrame(root,
                                            text=self.caption,
                                            bg='#fffff0',
                                            bd=0.5,
                                            fg='#696969',
                                            font='Courier 12',
                                            height=120,
                                            width=172)
        self.about_label_frame.place(relx=0.025, rely=0.8)

        # ------------------------------------------------ Кнопки ------------------------------------------------
        self.load_img_button = Button(text='  Load  image  ',
                                      bg='#E7D7D3',
                                      activebackground='#F5E5E2',
                                      font='Courier 16',
                                      command=self.input_img)
        self.load_img_button.place(relx=0.3, rely=0.8)

        self.show_orig_button = Button(text=' Show original ',
                                       bg='#E7D7D3',
                                       activebackground='#F5E5E2',
                                       font='Courier 16',
                                       command=self.show_start_image)
        self.show_orig_button.place(relx=0.54, rely=0.8)

        self.show_result_button = Button(text=' Show result ',
                                         bg='#E7D7D3',
                                         activebackground='#F5E5E2',
                                         font='Courier 16',
                                         command=self.show_result_image)
        self.show_result_button.place(relx=0.78, rely=0.8)

        self.show_orig_button = Button(text='Save image',
                                       bg='#E7D7D3',
                                       activebackground='#F5E5E2',
                                       font='Courier 16',
                                       command=self.save_result)
        self.show_orig_button.place(relx=0.35, rely=0.9)

        self.pfc_button = Button(text='  Spectrum  ',
                                 bg='#E7D7D3',
                                 activebackground='#F5E5E2',
                                 font='Courier 16',
                                 command=self.spectrum)
        self.pfc_button.place(relx=0.55, rely=0.9)

        self.hist_button = Button(text='Histogram',
                                  bg='#E7D7D3',
                                  activebackground='#F5E5E2',
                                  font='Courier 16',
                                  command=self.hist)
        self.hist_button.place(relx=0.8, rely=0.9)

    # Поместить иллюстрацию с PSF в Canvas
    def process_image(self, par):
        self.angle = self.angle_scrollbar.get()
        self.radius = self.radius_scrollbar.get()
        self.sharpness = self.sharpness_scrollbar.get()
        self.new_blur_type = self.blur_type.get()

        self.furier_img = cv2.dft(self.cv_img, flags=cv2.DFT_COMPLEX_OUTPUT)
        self.noise = 10**(-0.1 * self.sharpness)
        if self.new_blur_type == 1:
            self.psf = Deconvolution.defocus_kernel(self.radius)
        else:
            self.psf = Deconvolution.motion_kernel(self.angle, self.radius)
        psf = self.psf

        _psf = Image.fromarray(self.psf * 255)
        result_psf = _psf.resize((160, 160), Image.ANTIALIAS)
        self.psf_pic = ImageTk.PhotoImage(result_psf)
        self.psf_img.create_image(80, 80, image=self.psf_pic)
        self.psf_img.update()

        psf /= psf.sum()
        psf_pad = np.zeros_like(self.cv_img)
        kh, kw = psf.shape
        psf_pad[:kh, :kw] = psf

        PSF = cv2.dft(psf_pad, flags=cv2.DFT_COMPLEX_OUTPUT, nonzeroRows=kh)
        PSF2 = (PSF**2).sum(-1)
        iPSF = PSF / (PSF2 + self.noise)[..., np.newaxis]

        RES = cv2.mulSpectrums(self.furier_img, iPSF, 0)
        self.res = cv2.idft(RES, flags=cv2.DFT_SCALE | cv2.DFT_REAL_OUTPUT)

        self.res = np.roll(
            self.res, -kh // 2, 0
        )  #Элементы, которые выходят за пределы последней позиции, повторно вводятся при первой
        self.res = np.roll(self.res, -kw // 2, 1)

        self.spectrum_res = self.res

        res_image = Image.fromarray(self.res * 255)
        self.image = ImageTk.PhotoImage(res_image)
        self.result_image = self.image

        self.img_canvas.create_image(350, 200, image=self.image)
        self.img_canvas.update()

    def input_img(self):
        self.path = askopenfilename(filetypes=(("JPG image", "*.jpg"),
                                               ("PNG image", "*.png"),
                                               ("ALL files", "*.*")))
        image = Image.open(self.path)
        image = image.convert('L')
        h = image.height
        w = image.width
        if h > 500 or w > 800:
            if h < w:
                koef = int(h / 465)
            else:
                koef = int(w / 740)
            image = image.resize((int(h / koef), int(w / koef)),
                                 Image.ANTIALIAS)
        self.cv_img = np.float32(image) / 255.0

        image = Image.fromarray(self.cv_img * 255)
        self.image = ImageTk.PhotoImage(image)

        self.start_image = self.image
        self.img_canvas.delete("all")
        self.img_canvas.create_image(350, 200, image=self.image)
        self.cv_img = Deconvolution.blur_edge(self.cv_img)
        self.spectrum_image = self.cv_img

    def show_start_image(self):
        self.image = self.start_image
        self.img_canvas.create_image(350, 200, image=self.image)
        self.img_canvas.update()

    def show_result_image(self):
        self.image = self.result_image
        self.img_canvas.create_image(350, 200, image=self.image)
        self.img_canvas.update()

    def save_result(self):
        plt.imshow(self.spectrum_res, cmap='gray')
        plt.xticks([]), plt.yticks([])
        plt.show()

    def spectrum(self):
        input_img = self.spectrum_image
        dft_input_img = cv2.dft(input_img, flags=cv2.DFT_COMPLEX_OUTPUT)
        plt.subplot(221), plt.imshow(input_img, cmap='gray')
        plt.title('Input Image'), plt.xticks([]), plt.yticks([])

        image_shift = np.fft.fftshift(dft_input_img)
        magnitude_spectrum = 20 * np.log(
            cv2.magnitude(image_shift[:, :, 0], image_shift[:, :, 1]))
        plt.subplot(222), plt.imshow(magnitude_spectrum, cmap='gray')
        plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])

        plt.subplot(223), plt.imshow(self.res, cmap='gray')
        plt.title('Output Image'), plt.xticks([]), plt.yticks([])

        img = self.spectrum_res
        furier_img = cv2.dft(img, flags=cv2.DFT_COMPLEX_OUTPUT)

        image_shift = np.fft.fftshift(furier_img)
        magnitude_spectrum = 20 * np.log(
            cv2.magnitude(image_shift[:, :, 0], image_shift[:, :, 1]))
        plt.subplot(224), plt.imshow(magnitude_spectrum, cmap='gray')
        plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])

        plt.show()

    def hist(self):
        plt.hist(abs(self.spectrum_res))
        plt.title("Histogram")
        plt.show()
    def __init__(self):
        # ------------------------------------------------ Переменные класса-------------------------------------------------
        self.image = None
        self.blur_type = IntVar()
        self.angle = None
        self.radius = None
        self.sharpness = None
        self.noise = None
        self.cv_img = None
        self.furier_img = None
        self.psf_pic = None
        self.result_image = None
        self.start_image = None
        self.path = None
        self.res = None
        self.spectrum_res = None
        # -------------------------------------------------- Тип смазывания -------------------------------------------------
        self.label_frame = LabelFrame(root,
                                      text='Types of Blur',
                                      bg='#fffff0',
                                      bd=1,
                                      fg='#696969',
                                      font='Courier 16',
                                      height=100,
                                      width=300)
        self.label_frame.place(relx=0.025, rely=0.025)

        self.rb1 = Radiobutton(self.label_frame,
                               text='Out of focus',
                               background='#fffff0',
                               fg='#696969',
                               font='Courier 14',
                               variable=self.blur_type,
                               value=1,
                               command=lambda par=1: self.process_image(par))
        self.rb1.pack(expand=1, anchor=W)
        self.rb2 = Radiobutton(self.label_frame,
                               text='Motion',
                               background='#fffff0',
                               fg='#696969',
                               font='Courier 14',
                               variable=self.blur_type,
                               value=0,
                               command=lambda par=0: self.process_image(par))
        self.rb2.pack(expand=1, anchor=W)

        # ------------------------------------------------ Параметры ------------------------------------------------
        self.par_frame = LabelFrame(root,
                                    text='Settings',
                                    bg='#fffff0',
                                    bd=1,
                                    fg='#696969',
                                    font='Courier 16',
                                    height=150,
                                    width=300)
        self.par_frame.place(relx=0.025, rely=0.2)

        self.angle_label = Label(self.par_frame,
                                 text='Angle:',
                                 bg='#fffff0',
                                 fg='#696969',
                                 font='Courier 12')
        self.angle_label.pack(expand=1, anchor=W)

        self.angle_scrollbar = Scale(self.par_frame,
                                     bg='#fffff0',
                                     cursor='hand1',
                                     from_=0,
                                     to=180,
                                     orient=HORIZONTAL,
                                     showvalue=1,
                                     relief=FLAT,
                                     length=172,
                                     command=self.process_image)
        self.angle_scrollbar.pack(expand=1, anchor=W)

        self.radius_label = Label(self.par_frame,
                                  text='Radius:',
                                  bg='#fffff0',
                                  fg='#696969',
                                  font='Courier 12')
        self.radius_label.pack(expand=1, anchor=W)

        self.radius_scrollbar = Scale(self.par_frame,
                                      bg='#fffff0',
                                      cursor='hand1',
                                      from_=0,
                                      to=50,
                                      orient=HORIZONTAL,
                                      showvalue=1,
                                      variable=self.radius,
                                      relief=FLAT,
                                      length=172,
                                      command=self.process_image)
        self.radius_scrollbar.pack(expand=1, anchor=W)

        self.sharpness_label = Label(self.par_frame,
                                     text='Sharpness:',
                                     bg='#fffff0',
                                     fg='#696969',
                                     font='Courier 12')
        self.sharpness_label.pack(expand=1, anchor=W)

        self.sharpness_scrollbar = Scale(self.par_frame,
                                         bg='#fffff0',
                                         cursor='hand1',
                                         from_=0,
                                         to=50,
                                         orient=HORIZONTAL,
                                         showvalue=1,
                                         variable=self.sharpness,
                                         relief=FLAT,
                                         length=172,
                                         command=self.process_image)
        self.sharpness_scrollbar.pack(expand=1, anchor=W)

        # ------------------------------------------------ Место для фото ------------------------------------------------
        self.img_frame = LabelFrame(root,
                                    text='',
                                    bg='#fffff0',
                                    bd=1,
                                    height=465,
                                    width=740)
        self.img_frame.place(relx=0.25, rely=0.04)

        self.img_canvas = Canvas(self.img_frame,
                                 bg='#fffff0',
                                 bd=1,
                                 height=465,
                                 width=740)
        self.img_canvas.place(relx=0, rely=0)

        # --------------------------------------------------------------- PSF -----------------------------------------------------------
        self.psf_frame = LabelFrame(root,
                                    text='PSF',
                                    bg='#fffff0',
                                    bd=1,
                                    fg='#696969',
                                    font='Courier 16',
                                    height=172,
                                    width=172)
        self.psf_frame.place(relx=0.025, rely=0.55)

        self.psf_img = Canvas(self.psf_frame,
                              bg='#fffff0',
                              bd=1,
                              height=172,
                              width=172)
        self.psf_img.place(relx=0, rely=0)

        # ------------------------------------------------ О программе ------------------------------------------------
        self.caption = "Welcome!\nApp was created\nby Irina Skurko\nGroup 814301\nBSUIR 2019"
        self.about_label_frame = LabelFrame(root,
                                            text=self.caption,
                                            bg='#fffff0',
                                            bd=0.5,
                                            fg='#696969',
                                            font='Courier 12',
                                            height=120,
                                            width=172)
        self.about_label_frame.place(relx=0.025, rely=0.8)

        # ------------------------------------------------ Кнопки ------------------------------------------------
        self.load_img_button = Button(text='  Load  image  ',
                                      bg='#E7D7D3',
                                      activebackground='#F5E5E2',
                                      font='Courier 16',
                                      command=self.input_img)
        self.load_img_button.place(relx=0.3, rely=0.8)

        self.show_orig_button = Button(text=' Show original ',
                                       bg='#E7D7D3',
                                       activebackground='#F5E5E2',
                                       font='Courier 16',
                                       command=self.show_start_image)
        self.show_orig_button.place(relx=0.54, rely=0.8)

        self.show_result_button = Button(text=' Show result ',
                                         bg='#E7D7D3',
                                         activebackground='#F5E5E2',
                                         font='Courier 16',
                                         command=self.show_result_image)
        self.show_result_button.place(relx=0.78, rely=0.8)

        self.show_orig_button = Button(text='Save image',
                                       bg='#E7D7D3',
                                       activebackground='#F5E5E2',
                                       font='Courier 16',
                                       command=self.save_result)
        self.show_orig_button.place(relx=0.35, rely=0.9)

        self.pfc_button = Button(text='  Spectrum  ',
                                 bg='#E7D7D3',
                                 activebackground='#F5E5E2',
                                 font='Courier 16',
                                 command=self.spectrum)
        self.pfc_button.place(relx=0.55, rely=0.9)

        self.hist_button = Button(text='Histogram',
                                  bg='#E7D7D3',
                                  activebackground='#F5E5E2',
                                  font='Courier 16',
                                  command=self.hist)
        self.hist_button.place(relx=0.8, rely=0.9)
Ejemplo n.º 40
0
    if bullet.ycor() > 220:
        bullet.state = "ready"
        # moves bullet off screen
        bullet.hideturtle()
        bullet.setposition(0,-600)

    background.update()

    time.sleep(delay)


# displays the game over screen when the player is reached
if game == False:
    player.hideturtle()
    window = Tk()
    window.geometry("35x65")
    # displays game over message
    Label(window, text="Game over").grid(row=0, column=0)
    Label(window, text="Score: ").grid(row=1, column=0)

    # displays the score
    output_score = Text(master=window, width=5, height=1)
    output_score.grid(row=1, column=1)
    output_score.insert(END, score)


    # keeps the final screen up
    window.mainloop()
# keeps the game screen up
turtle.done()
Ejemplo n.º 41
0
from tkinter import Tk, Button, Entry, Frame, Label, LabelFrame

root = Tk()
root.geometry('600x400+500+200')

l = Label(root,
          text='HELLO',
          font=15,
          fg='#fff',
          bg='#f1c40f',
          width=8,
          height=4)
l.pack(fill='y', expand=1)

root.mainloop()
Ejemplo n.º 42
0
class Player(object):

    """Player class"""

    def __init__(self):

        """Initialisation of the Player object"""

        self.cfg = None
        self.db = None
        self.root = Tk()
        self.URL1L = StringVar(master=self.root)
        self.URL2L = StringVar(master=self.root)
        self.URL3L = StringVar(master=self.root)
        self.URL4L = StringVar(master=self.root)
        self.URL5L = StringVar(master=self.root)
        self.files = {}
        self.start()

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

    def start(self):

        """Start the Player"""

        print("*** Starting the Player ***")
        # Configuration
        self.cfg = Config()
        while not self.cfg.readConf() or not self.cfg.checkConf():
            self.displayConfig()
        if self.cfg.readConf() and self.cfg.checkConf():
            # Database
            self.db = Db(self.cfg)
            if self.db.openDb():
                self.display()
                return(True)
            else:
                error("Database not open")
                return(False)
        else:
            error("Cannot read configuration file")
            return(False)

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

    def stop(self):

        """Stop the Player"""

        msg = "Do you want to quit RasPyPlayer ?"
        if messagebox.askokcancel("RasPyPlayer", msg):
            print("*** Stopping the Player ***")
            self.db.closeDb()
            self.root.destroy()

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

    def scanDB(self):

        """Add movies in DB"""

        print("*** Adding movies in database")
        self.db.initDb()
        scanFiles(self.db, self.cfg, self.cfg.PATH)
        self.db.commitDb()
        return(True)

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

    def loadAllMovies(self):

        """Load movies from DB"""

        self.files = self.db.getAllMovies()
        return(True)

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

    def loadSrcMovies(self, src):

        """Load movies matching search pattern"""

        self.files = self.db.getSrcMovies(src)
        return(True)

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

    def play(self, url, file):

        """Play a movie"""

        print("Playing {}".format(file))
        if self.cfg.useOmx():
            if not url:
                sub = file[0:-3] + "srt"
                if isfile(sub):
                    cmd = self.cfg.OMXCMD2.format(self.cfg.OUT, sub, file)
                else:
                    cmd = self.cfg.OMXCMD1.format(self.cfg.OUT, file)
            else:
                cmd = self.cfg.OMXCMD1.format(self.cfg.OUT, file)
        else:
            cmd = self.cfg.MPLRCMD.format(file)
        if DEBUG:
            print(cmd)
        cmdnew = "sudo ./a.out "+file
        system(cmdnew)
        print(cmdnew)
        return(True)

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

    def displayHelp(self):

        """Display help"""

        messagebox.showinfo("Help...", getHelp())
        return(True)

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

    def displayConfig(self):

        """Display Config Window"""

        self.cfg.display(self)
        self.askToRefreshDataBase()
        return(True)

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

    def playSelection(self):

        """Play selected files"""

        sel = self.ui_files.curselection()
        ps = playScreen()
        for i in sel:
            f = self.ui_files.get(i)
            self.play(False, self.files[f])
        ps.destroy()
        return(True)

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

    def playUrl(self, url):

        """Play selected url"""

        ps = playScreen()
        self.play(True, url)
        ps.destroy()
        return(True)

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

    def display(self):

        """Display the player"""

        self.createGui()
        self.cfg.toggleUrl(self)
        self.askToRefreshDataBase()
        self.root.mainloop()

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

    def askToRefreshDataBase(self):

        """Ask to refresh database"""

        msg = "Do you want to refresh the movies database ?"
        if messagebox.askokcancel("RasPyPlayer", msg):
            self.refreshDataBase()
        else:
            self.refreshFilesList()
        return(True)

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

    def refreshDataBase(self):

        """Refresh the movies database"""

        if isdir(self.cfg.PATH):
            self.scanDB()
            self.refreshFilesList()
            return(True)

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

    def refreshFilesList(self):

        """Refresh the list of files"""

        src = self.ui_srcentry.get()
        # Empty variables :
        self.files = {}
        if self.ui_files.size() > 0:
            self.ui_files.delete(0, END)
        # Get files in DB :
        if src == "" or src == "*":
            if DEBUG:
                print("Get ALL")
            self.loadAllMovies()
        else:
            if DEBUG:
                print("Get '{}'".format(src))
            self.loadSrcMovies(('%'+src+'%',))
        # Sort results :
        liste = list()
        for f, p in self.files.items():
            liste.append(f)
        liste.sort(key=str.lower)
        # Display result :
        for file in liste:
            self.ui_files.insert(END, file)
        return(True)

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

    def playUrl1(self):

        """Play URL 1"""

        self.playUrl(self.cfg.URL1)

    def playUrl2(self):

        """Play URL 2"""

        self.playUrl(self.cfg.URL2)

    def playUrl3(self):

        """Play URL 3"""

        self.playUrl(self.cfg.URL3)

    def playUrl4(self):

        """Play URL 4"""

        self.playUrl(self.cfg.URL4)

    def playUrl5(self):

        """Play URL 5"""

        self.playUrl(self.cfg.URL5)

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

    def evtPlay(self, evt):
        self.playSelection()

    def evtRefresh(self, evt):
        self.refreshFilesList()

    def evtScan(self, evt):
        self.askToRefreshDataBase()

    def evtCfg(self, cfg):
        self.displayConfig()

    def evtHelp(self, evt):
        self.displayHelp()

    def evtQuit(self, evt):
        self.stop()

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

    def createGui(self):

        """Create the GUI for Player"""

        print("*** Creating GUI ***")
        self.root.title("RasPyPlayer v{}".format(VERSION))
        font = Font(self.root, size=20, family='Sans')
        self.root.attributes('-fullscreen', True)

        # Top Frame (search group)
        self.ui_topframe = Frame(self.root, borderwidth=2)
        self.ui_topframe.pack({"side": "top"})
        # Label search
        self.ui_srclabel = Label(self.ui_topframe, text="Search:",
            font=font)
        self.ui_srclabel.grid(row=1, column=0, padx=2, pady=2)
        # Entry search
        self.ui_srcentry = Entry(self.ui_topframe, font=font)
        self.ui_srcentry.grid(row=1, column=1, padx=2, pady=2)
        self.ui_srcentry.bind("<Return>", self.evtRefresh)
        # Button search
        self.ui_srcexec = Button(self.ui_topframe, text="Search",
            command=self.refreshFilesList, font=font)
        self.ui_srcexec.grid(row=1, column=2, padx=2, pady=2)

        # Frame (contain Middle and Url frames)
        self.ui_frame = Frame(self.root, borderwidth=2)
        self.ui_frame.pack(fill=BOTH, expand=1)

        # Middle Frame (files group)
        self.ui_midframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_midframe.pack({"side": "left"}, fill=BOTH, expand=1)
        # Files liste and scrollbar
        self.ui_files = Listbox(self.ui_midframe,
            selectmode=EXTENDED, font=font)
        self.ui_files.pack(side=LEFT, fill=BOTH, expand=1)
        self.ui_files.bind("<Return>", self.evtPlay)
        self.ui_filesscroll = Scrollbar(self.ui_midframe,
            command=self.ui_files.yview)
        self.ui_files.configure(yscrollcommand=self.ui_filesscroll.set)
        self.ui_filesscroll.pack(side=RIGHT, fill=Y)

        # Url Frame (url group)
        self.ui_urlframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_urlframe.pack({"side": "right"})
        # Button Url 1
        self.ui_buturl1 = Button(self.ui_urlframe, textvariable=self.URL1L,
            command=self.playUrl1, font=font)
        self.ui_buturl1.grid(row=1, column=0, padx=2, pady=2)
        # Button Url 2
        self.ui_buturl2 = Button(self.ui_urlframe, textvariable=self.URL2L,
            command=self.playUrl2, font=font)
        self.ui_buturl2.grid(row=2, column=0, padx=2, pady=2)
        # Button Url 3
        self.ui_buturl3 = Button(self.ui_urlframe, textvariable=self.URL3L,
            command=self.playUrl3, font=font)
        self.ui_buturl3.grid(row=3, column=0, padx=2, pady=2)
        # Button Url 4
        self.ui_buturl4 = Button(self.ui_urlframe, textvariable=self.URL4L,
            command=self.playUrl4, font=font)
        self.ui_buturl4.grid(row=4, column=0, padx=2, pady=2)
        # Button Url 5
        self.ui_buturl5 = Button(self.ui_urlframe, textvariable=self.URL5L,
            command=self.playUrl5, font=font)
        self.ui_buturl5.grid(row=5, column=0, padx=2, pady=2)

        # Bottom Frame (buttons group)
        self.ui_botframe = Frame(self.root, borderwidth=2)
        self.ui_botframe.pack({"side": "left"})
        # Button Play
        self.ui_butplay = Button(self.ui_botframe, text="Play",
            command=self.playSelection, font=font)
        self.ui_butplay.grid(row=1, column=0, padx=2, pady=2)
        # Button Refresh
        self.ui_butscan = Button(self.ui_botframe, text="Scan",
            command=self.askToRefreshDataBase, font=font)
        self.ui_butscan.grid(row=1, column=1, padx=2, pady=2)
        # Button Config
        self.ui_butconf = Button(self.ui_botframe, text="Config",
            command=lambda : self.cfg.display(self), font=font)
        self.ui_butconf.grid(row=1, column=2, padx=2, pady=2)
        # Button Help
        self.ui_buthelp = Button(self.ui_botframe, text="Help",
            command=self.displayHelp, font=font)
        self.ui_buthelp.grid(row=1, column=3, padx=2, pady=2)
        # Button Quit
        self.ui_butquit = Button(self.ui_botframe, text="Quit",
            command=self.stop, font=font)
        self.ui_butquit.grid(row=1, column=4, padx=2, pady=2)

        # General bindings
        self.root.bind("<F1>", self.evtHelp)
        self.root.bind("<F2>", self.evtCfg)
        self.root.bind("<F3>", self.evtRefresh)
        self.root.bind("<F5>", self.evtScan)
        self.root.bind("<F12>", self.evtQuit)
        return(True)
Ejemplo n.º 43
0
#[M2PCS] GCode Tool
from tkinter import Tk, Label, Button, Entry
from tkinter.ttk import Combobox
from tkinter.filedialog import askopenfilename
import m2py_old as mp
import serial.tools.list_ports
import os

window = Tk()
window.title('[M2PCS] GCode Tool')
window.geometry('400x110')

#COMPORT
lbl_com = Label(window,
                text='COMPORT: ****',
                font=("Courier New", 8),
                fg='red')
lbl_com.grid(column=0, row=0, sticky='W')
comm_data = serial.tools.list_ports.comports()
comm_list = []
for i in range(len(comm_data)):
    comm_list.append(comm_data[i].device)
comm_tuple = tuple(comm_list)
combo_com = Combobox(window, font=("Courier New", 8))
combo_com.grid(column=1, row=0)
combo_com['values'] = comm_tuple
btn_com_set = Button(window,
                     text='SET',
                     font=("Courier New", 8),
                     bg='lightgray')
btn_com_set.grid(column=2, row=0)
Ejemplo n.º 44
0
class Config(object):

    """Configuration class"""

    def __init__(self):

        """Initialisation of the config object"""

        self.CONF = "{0}/.raspyplayer.conf".format(expanduser('~'))
        # Values loaded from CONF file
        self.clearConf()
        # Values hard coded
        self.MPLRCMD = 'xterm -e mplayer -fs \"{0}\"'
        self.OMXCMD1 = 'xterm -e omxplayer -o {0} \"{1}\"'
        self.OMXCMD2 = 'xterm -e omxplayer -o {0} --subtitles \"{1}\" \"{2}\"'
        # DB*** - SQL requests
        self.DBADD = self.initDbAdd()
        self.DBALL = self.initDbAll()
        self.DBSRC = self.initDbSrc()
        self.DBDRP = self.initDbDrp()
        self.DBCRT = self.initDbCrt()

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

    def clearConf(self):

        """Clear conf settings"""

        self.PATH = None
        self.EXC = []
        self.EXT = []
        self.DB = None
        self.URL1 = None
        self.URL2 = None
        self.URL3 = None
        self.URL4 = None
        self.URL5 = None
        self.URL1L = 'URL1'
        self.URL2L = 'URL2'
        self.URL3L = 'URL3'
        self.URL4L = 'URL4'
        self.URL5L = 'URL5'
        self.OUT = 'local'

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

    def readConf(self):

        """Read the CONF file"""

        if isfile(self.CONF):
            self.clearConf()
            f = open(self.CONF, 'r')
            for l in f.readlines():
                l = l.replace("\n", "")
                if len(l) >= 3 and l[0:3] == "DB=":
                    self.DB = l[3:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 4 and l[0:4] == "EXC=":
                    self.EXC.append(l[4:len(l)])
                    if DEBUG:
                        print(l)
                elif len(l) >= 4 and l[0:4] == "EXT=":
                    self.EXT.append(l[4:len(l)])
                    if DEBUG:
                        print(l)
                elif len(l) >= 5 and l[0:5] == "PATH=":
                    self.PATH = l[5:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 5 and l[0:5] == "URL1=":
                    self.URL1 = l[5:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 5 and l[0:5] == "URL2=":
                    self.URL2 = l[5:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 5 and l[0:5] == "URL3=":
                    self.URL3 = l[5:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 5 and l[0:5] == "URL4=":
                    self.URL4 = l[5:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 5 and l[0:5] == "URL5=":
                    self.URL5 = l[5:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 6 and l[0:6] == "URL1L=":
                    self.URL1L = l[6:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 6 and l[0:6] == "URL2L=":
                    self.URL2L = l[6:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 6 and l[0:6] == "URL3L=":
                    self.URL3L = l[6:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 6 and l[0:6] == "URL4L=":
                    self.URL4L = l[6:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 6 and l[0:6] == "URL5L=":
                    self.URL5L = l[6:len(l)]
                    if DEBUG:
                        print(l)
                elif len(l) >= 4 and l[0:4] == "OUT=":
                    self.OUT = l[4:len(l)]
                    if DEBUG:
                        print(l)
            f.close()
            return(True)
        else:
            return(False)

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

    def checkConf(self):

        """Check the CONF"""

        res = True
        if not self.DB:
            self.errorVar("Database name", "n/a")
            res = False
        if not self.PATH:
            self.errorVar("Root directory", "n/a")
            res = False
        return(res)

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

    def errorVar(self, var, val):

        """Ask user to set correct setting"""

        msg = "{0} is not correct :\n'{1}'\nPlease set it in Config"
        messagebox.showerror("WARNING !", msg.format(var, str(val)))
        return(True)

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

    def useOmx(self):

        """We use OMXPLAYER ?"""

        if isfile('/usr/bin/omxplayer'):
            return(True)
        else:
            return(False)

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

    def initDbAdd(self):

        """Initialisation of the DBADD request"""

        res = "INSERT INTO files VALUES (?, ?)"
        return(res)

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

    def initDbSrc(self):

        """Initialisation of the DBSRC request"""

        res = "SELECT * FROM files WHERE file LIKE ? ORDER BY file"
        return(res)

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

    def initDbAll(self):

        """Initialisation of the DBALL request"""

        res = "SELECT * FROM files ORDER BY file"
        return(res)

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

    def initDbDrp(self):

        """Initialisation of the DBDRP request"""

        res = "DROP TABLE files"
        return(res)

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

    def initDbCrt(self):

        """Initialisation of the DBCRT request"""

        res = "CREATE TABLE files (file, path)"
        return(res)

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

    def display(self, root):

        """Display the setting window"""

        if self.createGui():
            self.player = root
            self.fill()
            self.root.mainloop()
        return(True)

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

    def fill(self):

        """Fill the setting window"""

        if self.PATH:
            self.ui_path.insert(0, self.PATH)
        self.ui_exc.insert(0, lst2str(self.EXC))
        self.ui_ext.insert(0, lst2str(self.EXT))
        if self.DB:
            self.ui_db.insert(0, self.DB)
        if self.URL1:
            self.ui_url1.insert(0, self.URL1)
        if self.URL2:
            self.ui_url2.insert(0, self.URL2)
        if self.URL3:
            self.ui_url3.insert(0, self.URL3)
        if self.URL4:
            self.ui_url4.insert(0, self.URL4)
        if self.URL5:
            self.ui_url5.insert(0, self.URL5)
        self.ui_url1l.insert(0, self.URL1L)
        self.ui_url2l.insert(0, self.URL2L)
        self.ui_url3l.insert(0, self.URL3L)
        self.ui_url4l.insert(0, self.URL4L)
        self.ui_url5l.insert(0, self.URL5L)
        self.ui_out.insert(0, self.OUT)

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

    def reload(self):

        """Load the conf from the setting window"""

        self.PATH = self.ui_path.get()
        self.EXC = str2lst(self.ui_exc.get())
        self.EXT = str2lst(self.ui_ext.get())
        self.DB = self.ui_db.get()
        self.URL1 = self.ui_url1.get()
        self.URL2 = self.ui_url2.get()
        self.URL3 = self.ui_url3.get()
        self.URL4 = self.ui_url4.get()
        self.URL5 = self.ui_url5.get()
        self.URL1L = self.ui_url1l.get()
        self.URL2L = self.ui_url2l.get()
        self.URL3L = self.ui_url3l.get()
        self.URL4L = self.ui_url4l.get()
        self.URL5L = self.ui_url5l.get()
        self.OUT = self.ui_out.get()

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

    def save(self):

        """Save the config"""

        print("*** Saving the configuration ***")
        self.reload()
        f = open(self.CONF, 'w')
        line = "DB=" + self.DB
        f.write(line+"\n")
        for i in self.EXC:
            line = "EXC=" + i
            f.write(line+"\n")
        for i in self.EXT:
            line = "EXT=" + i
            f.write(line+"\n")
        line = "PATH=" + self.PATH
        f.write(line+"\n")
        line = "URL1=" + self.URL1
        f.write(line+"\n")
        line = "URL2=" + self.URL2
        f.write(line+"\n")
        line = "URL3=" + self.URL3
        f.write(line+"\n")
        line = "URL4=" + self.URL4
        f.write(line+"\n")
        line = "URL5=" + self.URL5
        f.write(line+"\n")
        line = "URL1L=" + self.URL1L
        f.write(line+"\n")
        line = "URL2L=" + self.URL2L
        f.write(line+"\n")
        line = "URL3L=" + self.URL3L
        f.write(line+"\n")
        line = "URL4L=" + self.URL4L
        f.write(line+"\n")
        line = "URL5L=" + self.URL5L
        f.write(line+"\n")
        line = "OUT=" + self.OUT
        f.write(line+"\n")
        f.close()
        if self.checkConf():
            self.toggleUrl(self.player)
            self.root.destroy()
    #---------------------------------------------------------------------#

    def toggleUrl(self, player):

        """Enable / disable url buttons"""

        if self.URL1:
            s = NORMAL
            player.URL1L.set(self.URL1L)
        else:
            s = DISABLED
            player.URL1L.set("N/A")
        player.ui_buturl1.configure(state=s)
        player.ui_buturl1.update_idletasks()
        if self.URL2:
            s = NORMAL
            player.URL2L.set(self.URL2L)
        else:
            s = DISABLED
            player.URL2L.set("N/A")
        player.ui_buturl2.configure(state=s)
        player.ui_buturl2.update_idletasks()
        if self.URL3:
            s = NORMAL
            player.URL3L.set(self.URL3L)
        else:
            s = DISABLED
            player.URL3L.set("N/A")
        player.ui_buturl3.configure(state=s)
        player.ui_buturl3.update_idletasks()
        if self.URL4:
            s = NORMAL
            player.URL4L.set(self.URL4L)
        else:
            s = DISABLED
            player.URL4L.set("N/A")
        player.ui_buturl4.configure(state=s)
        player.ui_buturl4.update_idletasks()
        if self.URL5:
            s = NORMAL
            player.URL5L.set(self.URL5L)
        else:
            s = DISABLED
            player.URL5L.set("N/A")
        player.ui_buturl5.configure(state=s)
        player.ui_buturl5.update_idletasks()
        # Refresh
        player.root.update_idletasks()

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

    def createGui(self):

        """Create the GUI for Config"""

        print("*** Creating Configuration GUI ***")
        self.root = Tk()
        self.root.title("Configuration")
        self.root.attributes('-topmost', True)
        font = Font(self.root, size=20, family='Sans')
        # Middle Frame (config group)
        self.ui_midframe = Frame(self.root, borderwidth=2)
        self.ui_midframe.pack(fill=BOTH, expand=1)
        # PATH
        self.ui_pathlbl = Label(self.ui_midframe, text="Movies root folder",
            justify=LEFT, anchor=W, font=font)
        self.ui_pathlbl.grid(row=1, column=0, padx=2, pady=2)
        self.ui_path = Entry(self.ui_midframe, font=font)
        self.ui_path.grid(row=1, column=1, padx=2, pady=2)
        # EXC
        self.ui_exclbl = Label(self.ui_midframe, text="Directories to exclude",
            justify=LEFT, anchor=W, font=font)
        self.ui_exclbl.grid(row=2, column=0, padx=2, pady=2)
        self.ui_exc = Entry(self.ui_midframe, font=font)
        self.ui_exc.grid(row=2, column=1, padx=2, pady=2)
        # EXT
        self.ui_extlbl = Label(self.ui_midframe, text="Movies extensions",
            justify=LEFT, anchor=W, font=font )
        self.ui_extlbl.grid(row=3, column=0, padx=2, pady=2)
        self.ui_ext = Entry(self.ui_midframe, font=font)
        self.ui_ext.grid(row=3, column=1, padx=2, pady=2)
        # DB
        self.ui_dblbl = Label(self.ui_midframe, text="Database name",
            justify=LEFT, anchor=W, font=font )
        self.ui_dblbl.grid(row=4, column=0, padx=2, pady=2)
        self.ui_db = Entry(self.ui_midframe, font=font)
        self.ui_db.grid(row=4, column=1, padx=2, pady=2)
        # OUT
        self.ui_outlbl = Label(self.ui_midframe, text="Audio output (local/hdmi)",
            justify=LEFT, anchor=W, font=font )
        self.ui_outlbl.grid(row=5, column=0, padx=2, pady=2)
        self.ui_out = Entry(self.ui_midframe, font=font)
        self.ui_out.grid(row=5, column=1, padx=2, pady=2)
        # URL1L
        self.ui_url1llbl = Label(self.ui_midframe, text="Url 1 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url1llbl.grid(row=6, column=0, padx=2, pady=2)
        self.ui_url1l = Entry(self.ui_midframe, font=font)
        self.ui_url1l.grid(row=6, column=1, padx=2, pady=2)
        # URL1
        self.ui_url1lbl = Label(self.ui_midframe, text="Url 1",
            justify=LEFT, anchor=W, font=font )
        self.ui_url1lbl.grid(row=7, column=0, padx=2, pady=2)
        self.ui_url1 = Entry(self.ui_midframe, font=font)
        self.ui_url1.grid(row=7, column=1, padx=2, pady=2)
        # URL2L
        self.ui_url2llbl = Label(self.ui_midframe, text="Url 2 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url2llbl.grid(row=8, column=0, padx=2, pady=2)
        self.ui_url2l = Entry(self.ui_midframe, font=font)
        self.ui_url2l.grid(row=8, column=1, padx=2, pady=2)
        # URL2
        self.ui_url2lbl = Label(self.ui_midframe, text="Url 2",
            justify=LEFT, anchor=W, font=font )
        self.ui_url2lbl.grid(row=9, column=0, padx=2, pady=2)
        self.ui_url2 = Entry(self.ui_midframe, font=font)
        self.ui_url2.grid(row=9, column=1, padx=2, pady=2)
        # URL3L
        self.ui_url3llbl = Label(self.ui_midframe, text="Url 3 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url3llbl.grid(row=10, column=0, padx=2, pady=2)
        self.ui_url3l = Entry(self.ui_midframe, font=font)
        self.ui_url3l.grid(row=10, column=1, padx=2, pady=2)
        # URL3
        self.ui_url3lbl = Label(self.ui_midframe, text="Url 3",
            justify=LEFT, anchor=W, font=font )
        self.ui_url3lbl.grid(row=11, column=0, padx=2, pady=2)
        self.ui_url3 = Entry(self.ui_midframe, font=font)
        self.ui_url3.grid(row=11, column=1, padx=2, pady=2)
        # URL4L
        self.ui_url4llbl = Label(self.ui_midframe, text="Url 4 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url4llbl.grid(row=12, column=0, padx=2, pady=2)
        self.ui_url4l = Entry(self.ui_midframe, font=font)
        self.ui_url4l.grid(row=12, column=1, padx=2, pady=2)
        # URL4
        self.ui_url4lbl = Label(self.ui_midframe, text="Url 4",
            justify=LEFT, anchor=W, font=font )
        self.ui_url4lbl.grid(row=13, column=0, padx=2, pady=2)
        self.ui_url4 = Entry(self.ui_midframe, font=font)
        self.ui_url4.grid(row=13, column=1, padx=2, pady=2)
        # URL5L
        self.ui_url5llbl = Label(self.ui_midframe, text="Url 5 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url5llbl.grid(row=14, column=0, padx=2, pady=2)
        self.ui_url5l = Entry(self.ui_midframe, font=font)
        self.ui_url5l.grid(row=14, column=1, padx=2, pady=2)
        # URL5
        self.ui_url5lbl = Label(self.ui_midframe, text="Url 5",
            justify=LEFT, anchor=W, font=font )
        self.ui_url5lbl.grid(row=15, column=0, padx=2, pady=2)
        self.ui_url5 = Entry(self.ui_midframe, font=font)
        self.ui_url5.grid(row=15, column=1, padx=2, pady=2)
        # Bottom Frame (buttons group)
        self.ui_botframe = Frame(self.root, borderwidth=2)
        self.ui_botframe.pack({"side": "left"})
        # Button Save
        self.ui_butsave = Button(self.ui_botframe, text="Save",
            command=self.save, font=font)
        self.ui_butsave.grid(row=1, column=0, padx=2, pady=2)
        # Button Close
        self.ui_butquit = Button(self.ui_botframe, text="Close",
            command=self.root.destroy, font=font)
        self.ui_butquit.grid(row=1, column=1, padx=2, pady=2)
        return(True)
Ejemplo n.º 45
0
    def createGui(self):

        """Create the GUI for Config"""

        print("*** Creating Configuration GUI ***")
        self.root = Tk()
        self.root.title("Configuration")
        self.root.attributes('-topmost', True)
        font = Font(self.root, size=20, family='Sans')
        # Middle Frame (config group)
        self.ui_midframe = Frame(self.root, borderwidth=2)
        self.ui_midframe.pack(fill=BOTH, expand=1)
        # PATH
        self.ui_pathlbl = Label(self.ui_midframe, text="Movies root folder",
            justify=LEFT, anchor=W, font=font)
        self.ui_pathlbl.grid(row=1, column=0, padx=2, pady=2)
        self.ui_path = Entry(self.ui_midframe, font=font)
        self.ui_path.grid(row=1, column=1, padx=2, pady=2)
        # EXC
        self.ui_exclbl = Label(self.ui_midframe, text="Directories to exclude",
            justify=LEFT, anchor=W, font=font)
        self.ui_exclbl.grid(row=2, column=0, padx=2, pady=2)
        self.ui_exc = Entry(self.ui_midframe, font=font)
        self.ui_exc.grid(row=2, column=1, padx=2, pady=2)
        # EXT
        self.ui_extlbl = Label(self.ui_midframe, text="Movies extensions",
            justify=LEFT, anchor=W, font=font )
        self.ui_extlbl.grid(row=3, column=0, padx=2, pady=2)
        self.ui_ext = Entry(self.ui_midframe, font=font)
        self.ui_ext.grid(row=3, column=1, padx=2, pady=2)
        # DB
        self.ui_dblbl = Label(self.ui_midframe, text="Database name",
            justify=LEFT, anchor=W, font=font )
        self.ui_dblbl.grid(row=4, column=0, padx=2, pady=2)
        self.ui_db = Entry(self.ui_midframe, font=font)
        self.ui_db.grid(row=4, column=1, padx=2, pady=2)
        # OUT
        self.ui_outlbl = Label(self.ui_midframe, text="Audio output (local/hdmi)",
            justify=LEFT, anchor=W, font=font )
        self.ui_outlbl.grid(row=5, column=0, padx=2, pady=2)
        self.ui_out = Entry(self.ui_midframe, font=font)
        self.ui_out.grid(row=5, column=1, padx=2, pady=2)
        # URL1L
        self.ui_url1llbl = Label(self.ui_midframe, text="Url 1 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url1llbl.grid(row=6, column=0, padx=2, pady=2)
        self.ui_url1l = Entry(self.ui_midframe, font=font)
        self.ui_url1l.grid(row=6, column=1, padx=2, pady=2)
        # URL1
        self.ui_url1lbl = Label(self.ui_midframe, text="Url 1",
            justify=LEFT, anchor=W, font=font )
        self.ui_url1lbl.grid(row=7, column=0, padx=2, pady=2)
        self.ui_url1 = Entry(self.ui_midframe, font=font)
        self.ui_url1.grid(row=7, column=1, padx=2, pady=2)
        # URL2L
        self.ui_url2llbl = Label(self.ui_midframe, text="Url 2 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url2llbl.grid(row=8, column=0, padx=2, pady=2)
        self.ui_url2l = Entry(self.ui_midframe, font=font)
        self.ui_url2l.grid(row=8, column=1, padx=2, pady=2)
        # URL2
        self.ui_url2lbl = Label(self.ui_midframe, text="Url 2",
            justify=LEFT, anchor=W, font=font )
        self.ui_url2lbl.grid(row=9, column=0, padx=2, pady=2)
        self.ui_url2 = Entry(self.ui_midframe, font=font)
        self.ui_url2.grid(row=9, column=1, padx=2, pady=2)
        # URL3L
        self.ui_url3llbl = Label(self.ui_midframe, text="Url 3 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url3llbl.grid(row=10, column=0, padx=2, pady=2)
        self.ui_url3l = Entry(self.ui_midframe, font=font)
        self.ui_url3l.grid(row=10, column=1, padx=2, pady=2)
        # URL3
        self.ui_url3lbl = Label(self.ui_midframe, text="Url 3",
            justify=LEFT, anchor=W, font=font )
        self.ui_url3lbl.grid(row=11, column=0, padx=2, pady=2)
        self.ui_url3 = Entry(self.ui_midframe, font=font)
        self.ui_url3.grid(row=11, column=1, padx=2, pady=2)
        # URL4L
        self.ui_url4llbl = Label(self.ui_midframe, text="Url 4 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url4llbl.grid(row=12, column=0, padx=2, pady=2)
        self.ui_url4l = Entry(self.ui_midframe, font=font)
        self.ui_url4l.grid(row=12, column=1, padx=2, pady=2)
        # URL4
        self.ui_url4lbl = Label(self.ui_midframe, text="Url 4",
            justify=LEFT, anchor=W, font=font )
        self.ui_url4lbl.grid(row=13, column=0, padx=2, pady=2)
        self.ui_url4 = Entry(self.ui_midframe, font=font)
        self.ui_url4.grid(row=13, column=1, padx=2, pady=2)
        # URL5L
        self.ui_url5llbl = Label(self.ui_midframe, text="Url 5 name",
            justify=LEFT, anchor=W, font=font )
        self.ui_url5llbl.grid(row=14, column=0, padx=2, pady=2)
        self.ui_url5l = Entry(self.ui_midframe, font=font)
        self.ui_url5l.grid(row=14, column=1, padx=2, pady=2)
        # URL5
        self.ui_url5lbl = Label(self.ui_midframe, text="Url 5",
            justify=LEFT, anchor=W, font=font )
        self.ui_url5lbl.grid(row=15, column=0, padx=2, pady=2)
        self.ui_url5 = Entry(self.ui_midframe, font=font)
        self.ui_url5.grid(row=15, column=1, padx=2, pady=2)
        # Bottom Frame (buttons group)
        self.ui_botframe = Frame(self.root, borderwidth=2)
        self.ui_botframe.pack({"side": "left"})
        # Button Save
        self.ui_butsave = Button(self.ui_botframe, text="Save",
            command=self.save, font=font)
        self.ui_butsave.grid(row=1, column=0, padx=2, pady=2)
        # Button Close
        self.ui_butquit = Button(self.ui_botframe, text="Close",
            command=self.root.destroy, font=font)
        self.ui_butquit.grid(row=1, column=1, padx=2, pady=2)
        return(True)
Ejemplo n.º 46
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.

        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = list(range(columns))
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)

        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
Ejemplo n.º 47
0
    def createGui(self):

        """Create the GUI for Player"""

        print("*** Creating GUI ***")
        self.root.title("RasPyPlayer v{}".format(VERSION))
        font = Font(self.root, size=20, family='Sans')
        self.root.attributes('-fullscreen', True)

        # Top Frame (search group)
        self.ui_topframe = Frame(self.root, borderwidth=2)
        self.ui_topframe.pack({"side": "top"})
        # Label search
        self.ui_srclabel = Label(self.ui_topframe, text="Search:",
            font=font)
        self.ui_srclabel.grid(row=1, column=0, padx=2, pady=2)
        # Entry search
        self.ui_srcentry = Entry(self.ui_topframe, font=font)
        self.ui_srcentry.grid(row=1, column=1, padx=2, pady=2)
        self.ui_srcentry.bind("<Return>", self.evtRefresh)
        # Button search
        self.ui_srcexec = Button(self.ui_topframe, text="Search",
            command=self.refreshFilesList, font=font)
        self.ui_srcexec.grid(row=1, column=2, padx=2, pady=2)

        # Frame (contain Middle and Url frames)
        self.ui_frame = Frame(self.root, borderwidth=2)
        self.ui_frame.pack(fill=BOTH, expand=1)

        # Middle Frame (files group)
        self.ui_midframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_midframe.pack({"side": "left"}, fill=BOTH, expand=1)
        # Files liste and scrollbar
        self.ui_files = Listbox(self.ui_midframe,
            selectmode=EXTENDED, font=font)
        self.ui_files.pack(side=LEFT, fill=BOTH, expand=1)
        self.ui_files.bind("<Return>", self.evtPlay)
        self.ui_filesscroll = Scrollbar(self.ui_midframe,
            command=self.ui_files.yview)
        self.ui_files.configure(yscrollcommand=self.ui_filesscroll.set)
        self.ui_filesscroll.pack(side=RIGHT, fill=Y)

        # Url Frame (url group)
        self.ui_urlframe = Frame(self.ui_frame, borderwidth=2)
        self.ui_urlframe.pack({"side": "right"})
        # Button Url 1
        self.ui_buturl1 = Button(self.ui_urlframe, textvariable=self.URL1L,
            command=self.playUrl1, font=font)
        self.ui_buturl1.grid(row=1, column=0, padx=2, pady=2)
        # Button Url 2
        self.ui_buturl2 = Button(self.ui_urlframe, textvariable=self.URL2L,
            command=self.playUrl2, font=font)
        self.ui_buturl2.grid(row=2, column=0, padx=2, pady=2)
        # Button Url 3
        self.ui_buturl3 = Button(self.ui_urlframe, textvariable=self.URL3L,
            command=self.playUrl3, font=font)
        self.ui_buturl3.grid(row=3, column=0, padx=2, pady=2)
        # Button Url 4
        self.ui_buturl4 = Button(self.ui_urlframe, textvariable=self.URL4L,
            command=self.playUrl4, font=font)
        self.ui_buturl4.grid(row=4, column=0, padx=2, pady=2)
        # Button Url 5
        self.ui_buturl5 = Button(self.ui_urlframe, textvariable=self.URL5L,
            command=self.playUrl5, font=font)
        self.ui_buturl5.grid(row=5, column=0, padx=2, pady=2)

        # Bottom Frame (buttons group)
        self.ui_botframe = Frame(self.root, borderwidth=2)
        self.ui_botframe.pack({"side": "left"})
        # Button Play
        self.ui_butplay = Button(self.ui_botframe, text="Play",
            command=self.playSelection, font=font)
        self.ui_butplay.grid(row=1, column=0, padx=2, pady=2)
        # Button Refresh
        self.ui_butscan = Button(self.ui_botframe, text="Scan",
            command=self.askToRefreshDataBase, font=font)
        self.ui_butscan.grid(row=1, column=1, padx=2, pady=2)
        # Button Config
        self.ui_butconf = Button(self.ui_botframe, text="Config",
            command=lambda : self.cfg.display(self), font=font)
        self.ui_butconf.grid(row=1, column=2, padx=2, pady=2)
        # Button Help
        self.ui_buthelp = Button(self.ui_botframe, text="Help",
            command=self.displayHelp, font=font)
        self.ui_buthelp.grid(row=1, column=3, padx=2, pady=2)
        # Button Quit
        self.ui_butquit = Button(self.ui_botframe, text="Quit",
            command=self.stop, font=font)
        self.ui_butquit.grid(row=1, column=4, padx=2, pady=2)

        # General bindings
        self.root.bind("<F1>", self.evtHelp)
        self.root.bind("<F2>", self.evtCfg)
        self.root.bind("<F3>", self.evtRefresh)
        self.root.bind("<F5>", self.evtScan)
        self.root.bind("<F12>", self.evtQuit)
        return(True)
Ejemplo n.º 48
0
from tkinter import Tk, Label, Button, Entry, END, Text, Spinbox, Scale, IntVar, Radiobutton, Listbox, Checkbutton

# Creating a new window and configurations
window = Tk()
window.title("Widget Examples")
window.minsize(width=500, height=500)

# Labels
label = Label(text="This is old text")
label.config(text="This is new text")
label.pack()


# Buttons
def action():
    print("Do something")


# calls action() when pressed
button = Button(text="Click Me", command=action)
button.pack()

# Entries
entry = Entry(width=30)
# Add some text to begin with
entry.insert(END, string="Some text to begin with.")
# Gets text in entry
print(entry.get())
entry.pack()

# Text
Ejemplo n.º 49
0

# Function to execute when the button is pressed
def decrement():
    global label_value
    if label_value == 1:
        the_label['text'] = 'Go!'
    else:
        label_value = label_value - 1
        the_label['text'] = str(label_value)


# Create a button widget whose parent container is the
# window
the_button = Button(countdown_window,
                    text=' Push ',
                    font=('Arial', 24),
                    command=decrement)

# Create a label
the_label = Label(countdown_window, text=str(label_value), font=('Arial', 34))

# Call the geometry manager to "pack" the widgets onto
# the window (with a blank margin around the widgets)
margin_size = 5
the_button.pack(padx=margin_size, pady=margin_size)
the_label.pack(pady=margin_size)

# Start the event loop to react to user inputs
countdown_window.mainloop()
Ejemplo n.º 50
0
 def update_labels(self):
     self.l_save.destroy()
     self.l_save = Label(self.window, text=self.save_location)
     self.l_source.destroy()
     self.l_source = Label(self.window, text=self.source_location)
     self.setup_label_layouts()
Ejemplo n.º 51
0
class MyGui:
    def __init__(self):

        self.window = Tk()
        self.window.title('Extract Spotlight Images')

        # setting default values for variables
        self.home = Path.home()
        self.source_location = Path.joinpath(
            self.home,
            Path(
                'AppData/Local/Packages/Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy/LocalState/Assets'
            ))
        self.save_location = Path.joinpath(self.home, Path('Desktop'))
        self.split = True
        self.min_res = 1920

        # setting up buttons and their actions
        self.b_save = Button(self.window,
                             text="Save Location",
                             command=self.set_save_location)
        self.b_source = Button(self.window,
                               text="Spotlights source",
                               command=self.set_source_location)
        self.b_reset = Button(self.window,
                              text="Set Defaults",
                              command=self.reset)
        self.b_split = Checkbutton(self.window,
                                   text="Don't split",
                                   command=self.toggle_split)
        self.b_min_res = Entry(self.window, textvariable=self.min_res)
        self.b_main = Button(self.window,
                             text="Get Spotlights",
                             command=self.copy_spotlights,
                             fg="white",
                             bg="green",
                             bd=4)

        # setting up labels to represent button actions
        self.l_save = Label(self.window, text=self.save_location)
        self.l_source = Label(self.window, text=self.source_location)
        self.l_settings = Label(self.window, text="Advanced Settings below :")
        self.l_split = Label(
            self.window,
            text=
            "If checked, landscape and portrait image will not be separated")
        self.l_min_res = Label(
            self.window,
            text=
            "Only include images with width or height greater than or equal to this value"
        )

        self.setup_button_layouts()
        self.setup_label_layouts()

        self.window.mainloop()

    def setup_button_layouts(self):
        self.b_save.grid(row=0, column=0, padx=px, pady=py)
        self.b_source.grid(row=3, column=0, padx=px, pady=py)
        self.b_min_res.grid(row=5, column=0, padx=px, pady=py)
        self.b_min_res.insert(0, self.min_res)
        self.b_reset.grid(row=6, column=0, padx=px, pady=py)
        self.b_split.grid(row=4, column=0, padx=px, pady=py)
        self.b_main.grid(row=1, columnspan=2, padx=2 * px, pady=2 * py)

    def setup_label_layouts(self):
        self.l_save.grid(row=0, column=1, padx=px, pady=py)
        self.l_source.grid(row=3, column=1, padx=px, pady=py)
        self.l_split.grid(row=4, column=1, padx=px, pady=py)
        self.l_settings.grid(row=2, column=0, padx=px, pady=py)
        self.l_source.grid(row=3, column=1, padx=px, pady=py)
        self.l_min_res.grid(row=5, column=1, padx=px, pady=py)

    def update_labels(self):
        self.l_save.destroy()
        self.l_save = Label(self.window, text=self.save_location)
        self.l_source.destroy()
        self.l_source = Label(self.window, text=self.source_location)
        self.setup_label_layouts()

    def set_source_location(self):
        source_location = filedialog.askdirectory()
        if source_location:
            self.source_location = source_location
        self.update_labels()

    def set_save_location(self):
        save_location = filedialog.askdirectory()
        if save_location:
            self.save_location = save_location
        self.update_labels()

    def toggle_split(self):
        self.split = False if self.split else True

    def copy_spotlights(self):
        min_res = self.b_min_res.get()
        if min_res:
            self.min_res = min_res
        copy_spotlights_images(self.source_location, self.save_location,
                               self.split, self.min_res)
        self.popup_finished()

    @staticmethod
    def popup_finished():
        done = Tk()
        Label(done, text="Finished!").grid(row=0,
                                           columnspan=3,
                                           padx=2 * px,
                                           pady=py)
        Button(done, text="Ok", command=done.destroy).grid(row=1,
                                                           column=1,
                                                           padx=px)

    def reset(self):
        self.window.destroy()
        self.__init__()
Ejemplo n.º 52
0
    df = DataFrame(perms,columns=['name','protection'])                
    f.close()
    button_extract_perms["state"]="normal"  
    button_export["state"]="normal"
def exportCSV ():
    global df
    
    export_file_path = filedialog.asksaveasfilename(defaultextension='.csv',
                                                    filetypes=[("Comma Separated Value File", '*.csv')])
    df.to_csv (export_file_path, index = False, header=True)

window = Tk() 
window.title('APK Permissions Analysis')

label_file_explorer = Label(window,  
                            text = "Select an APK File", 
                            height = 2,  
                            fg = "black") 
label_file_explorer.grid(row=0,
                         column=0,
                         columnspan=3)

label_permissions = Label(window,
                          text = "", 
                          height = 2, 
                          fg="blue")
label_permissions.grid(row=2,
                       column=0)                          

label_permissions_legend = Label(window,
                          text = "", 
                          height = 2, 
Ejemplo n.º 53
0
def myClick():
    greet = "Hello! " + entry.get()
    myLabel = Label(root, text=greet)
    myLabel.pack()
Ejemplo n.º 54
0
def main():
    CohenSutherland = RecLineArea()
    # Cоздаём главное окно
    root = Tk()
    # Ширина экрана
    w = root.winfo_screenwidth()
    # Высота экрана
    h = root.winfo_screenheight()
    w = w // 2 - 300
    h = h // 2 - 200
    root.geometry('+{}+{}'.format(w, h))

    root.title("Алгоритм Коэна — Сазерленда")
    line_infoLabel = Label(root,
                           text="Введите количество линий: ",
                           font=("Consolas", 10, "bold"))
    line_entry = Entry(root, width=10)
    line12_infoLabel = Label(root,
                             text="Введите диапозон генерации линий по X,Y: ",
                             font=("Consolas", 10, "bold"))
    line1_entry = Entry(root, width=10)
    line1_but = Button(
        root,
        text="Ввести",
        command=lambda: CohenSutherland.get_amountX(line1_entry, fig, canvas))
    line2_entry = Entry(root, width=10)
    line2_but = Button(
        root,
        text="Ввести",
        command=lambda: CohenSutherland.get_amountY(line2_entry, fig, canvas))
    rec12_infoLabel = Label(
        root,
        text=
        "Введите ширину сдвига прямоугольника по горизонтали и вертикали: ",
        font=("Consolas", 10, "bold"))
    width_entry = Entry(root, width=10)
    height_entry = Entry(root, width=10)
    rec34_infoLabel = Label(
        root,
        text="Введите X, Y- координату нижней левой точки: ",
        font=("Consolas", 10, "bold"))
    X_entry = Entry(root, width=10)
    Y_entry = Entry(root, width=10)
    line_but = Button(
        root,
        text="Ввести и сгенерировать",
        command=lambda: CohenSutherland.get_amount(line_entry, fig, canvas))
    rec_but = Button(
        root,
        text="Ввести и сгенерировать",
        command=lambda: CohenSutherland.gen_rec(width_entry, height_entry,
                                                X_entry, Y_entry, fig, canvas))

    cut_but = Button(root,
                     text="Выделить отрезки внутри",
                     command=lambda: CohenSutherland.drawCutCS(fig, canvas))

    line_infoLabel.pack(side=tkinter.TOP)
    line_entry.pack(side=tkinter.TOP)
    line_but.pack(side=tkinter.TOP)

    line12_infoLabel.pack(side=tkinter.TOP)
    line1_entry.pack(side=tkinter.TOP)
    line1_but.pack(side=tkinter.TOP)

    line2_entry.pack(side=tkinter.TOP)
    line2_but.pack(side=tkinter.TOP)

    rec12_infoLabel.pack(side=tkinter.TOP)
    width_entry.pack(side=tkinter.TOP)
    height_entry.pack(side=tkinter.TOP)

    # Формиурем фигуру кривой и "холст" + панель
    fig = plt.figure()
    canvas = FigureCanvasTkAgg(fig, master=root)
    toolbar = NavigationToolbar2Tk(canvas, root)

    exButton = tkinter.Button(master=root,
                              text="Выход",
                              command=lambda: quit(root))

    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
    toolbar.pack()

    rec34_infoLabel.pack(side=tkinter.LEFT)
    X_entry.pack(side=tkinter.LEFT)
    Y_entry.pack(side=tkinter.LEFT)

    exButton.pack(side=tkinter.BOTTOM)
    rec_but.pack(side=tkinter.BOTTOM)
    cut_but.pack(side=tkinter.BOTTOM)

    CohenSutherland.drawCS(fig, canvas)
    # Собираем мусор и обновляем окно
    gc.collect()
    root.update()
    root.mainloop()
Ejemplo n.º 55
0
        cursor.execute(
            'CREATE TABLE IF NOT EXISTS Student (fullName TEXT, Gender TEXT, dateOfBirth DOB, address TEXT, city TEXT, pincode NUMBER, state TEXT, country TEXT, email TEXT, category TEXT, nationality TEXT);'
        )
        cursor.execute(
            'INSERT INTO Student (fullName, Gender, dateOfBirth, address, city, pincode, state, country, email, category, nationality) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
            (name, Gender, dob, completeAddress, City, Pincode, State, Country,
             Email, Category, Nationality))
        conn.commit()
        Label(
            root,
            text="Submitted Successfully                                     "
        ).place(x=20, y=450)


Label(root,
      text="               NIMCET 2020 Registration form",
      font=("bold", 15)).place(x=100, y=10)
Label(root, text="1. Name in full (As per X Board)",
      font=("Ubuntu", 13)).place(x=10, y=60)

# First name
Label(root, text="First Name").place(x=30, y=82)
fName = Entry(root, bd=1, textvar=firstN)
fName.place(x=120, y=82)
# Last Name
Label(root, text="Last Name").place(x=30, y=102)
lName = Entry(root, bd=1, textvar=lastN)
lName.place(x=120, y=102)

# print(type(fullName))
# Gender
Ejemplo n.º 56
0
class Window:
    def __init__(self, root):

        self.root = root
        self.root.title("rx-gimme  v0.1")
        self.root.grid_anchor(anchor="c")

        self.first_row = 0
        self.first_column = 0
        self.max_plot = 10

        frame = Frame(root)

        self.label_url = Label(frame, text="Enter URL: ")
        self.label_url.grid(row=self.first_row,
                            column=self.first_column,
                            sticky="w",
                            padx=4,
                            pady=4)

        self.entry_url = Entry(frame, width=50)
        self.entry_url.grid(row=self.first_row, column=self.first_column + 1)
        self.entry_url.insert(0, "http://www.google.com/")

        self.button_url = Button(frame,
                                 text="Gimme!",
                                 width=10,
                                 command=self.gimme)
        self.button_url.grid(row=self.first_row, column=self.first_column + 2)

        self.button_save = Button(frame,
                                  text="Save buffer...",
                                  width=10,
                                  command=self.file_save_as)
        self.button_save.grid(row=self.first_row, column=self.first_column + 3)

        self.lines = 40
        self.scrollbar = Scrollbar(frame, orient="vertical")
        self.text = Text(frame,
                         height=self.lines,
                         yscrollcommand=self.scrollbar.set)
        self.text.grid(
            row=self.first_row + 1,
            column=self.first_column,
            columnspan=4,
            sticky="EW",
            padx=4,
            pady=4,
        )
        self.scrollbar.grid(row=self.first_row + 1,
                            column=self.first_column + 4,
                            sticky="NS")
        self.scrollbar.config(command=self.text.yview)

        frame.grid()

    def gimme(self):
        self.text.delete("1.0", END)
        self.text.insert(
            END, "\nGetting links from: " + self.entry_url.get() + "\n\n")
        self.text.see("end")

        try:
            url = self.entry_url.get()
            page = requests.get(url)
            data = page.text
            soup = BeautifulSoup(data, "html.parser")

            for link in soup.find_all("a"):
                if link.get("href") is not None:
                    if link.get("href")[0] == "/":
                        self.text.insert(END, url + link.get("href") + "\n")
                    elif link.get("href")[0] == "#":
                        self.text.insert(END,
                                         url + "/" + link.get("href") + "\n")
                    else:
                        self.text.insert(END, link.get("href") + "\n")

                self.text.see("end")

        except Exception:
            self.error("Not valid URL:" + url)

    def file_save_as(self, event=None, filepath=None):
        if filepath is None:
            filepath = filedialog.asksaveasfilename(filetypes=(
                ("Text files", "*.txt"),
                ("Python files", "*.py *.pyw"),
                ("All files", "*.*"),
            ), )
        try:
            with open(filepath, "wb") as f:
                textt = self.text.get(1.0, "end-1c")
                f.write(bytes(textt, "UTF-8"))
                self.editor.edit_modified(False)
                self.file_path = filepath
                self.set_title()
                self.error("File saved!")
        except FileNotFoundError:
            self.error("File not saved!")

    def error(self, message):
        messagebox.showerror("Error", message)

    def main(self):
        pass
Ejemplo n.º 57
0
def retrieveWindow():
    retrieveWin = Toplevel(root)
    retrieveWin.geometry('400x400')
    cur = conn.cursor()
    Em = email.get()
    if (Em == ""):
        Label(retrieveWin, text="Email WRONG/NOT FOUND").place(x=40, y=40)
    else:
        cur.execute("SELECT *FROM Student WHERE email=?", (email.get(), ))
        rows = cur.fetchall()
        Label(retrieveWin, text="Your Details:").place(x=30, y=10)
        Label(retrieveWin, text="Name:    " + rows[0][0]).place(x=20, y=25)
        if rows[0][1] == "M":
            gen = "Male"
        else:
            gen = "Female"
        Label(retrieveWin, text="Gender:      " + gen).place(x=20, y=40)
        # Label(retrieveWin, text = "Gender:      " + gen).place(x = 20, y = 40)
        Label(retrieveWin, text="DOB:     " + rows[0][2]).place(x=20, y=55)
        Label(retrieveWin, text="Address  :  ").place(x=20, y=79)
        Label(retrieveWin, text=rows[0][3]).place(x=30, y=94)
        Label(retrieveWin, text=rows[0][4]).place(x=30, y=110)
        Label(retrieveWin, text=rows[0][5]).place(x=70, y=110)
        Label(retrieveWin, text=rows[0][6]).place(x=30, y=125)
        Label(retrieveWin, text=rows[0][7]).place(x=70, y=125)
        Label(retrieveWin, text="Email:       " + rows[0][8]).place(x=30,
                                                                    y=140)
        Label(retrieveWin, text="Category:        " + rows[0][9]).place(x=30,
                                                                        y=155)
        if rows[0][10] == "IN":
            cat = "India"
        else:
            cat = "Foriegn Country"
        Label(retrieveWin, text="Nationality:     " + cat).place(x=30, y=172)
Ejemplo n.º 58
0
        root.destroy()


root = Tk()
root.resizable(0, 0)
root.title("LogR")
#Username
ent = u = Entry(root, fg='black', bg='green', relief='flat', bd=1)
ent.place(x=150, y=10)
#password
ent2 = p = Entry(root, show='*', fg='black', bg='green', relief='flat', bd=1)
ent2.place(x=150, y=40)
#labels
lbl = Label(root,
            text="Username",
            bg='black',
            fg='green',
            font=('Arial 10 bold')).place(x=10, y=10)
lbl2 = Label(root,
             text="Password",
             bg='black',
             fg='green',
             font=('Arial 10 bold')).place(x=10, y=40)
bttn = Button(root,
              relief='flat',
              bd=1,
              text="Log In",
              fg="green",
              bg='black',
              activebackground='green',
              activeforeground='black',
Ejemplo n.º 59
0
    #webbrowser.open(r.url)
    try:  #带上错误处理
        for i in rlist:
            browseropen(get(i).url)
    except Exception as error:
        #print('exception:',e)
        messagebox.showerror(title='错误', message='网页无法解析!\n错误类型:' + str(error))
    finally:
        print('...')


window = Tk()
window.title('日常任务一键开启')
window.geometry('400x300')

l = Label(window, text='今天的日常好像还没做呢', font=('Arial', 10), width=20,
          height=3)  #width,height的长度都是根据字符的大小来定的


def hit_b1():
    wopen()


b1 = Button(window, text='开启', width=10, height=1, command=hit_b1)

e = Entry(window, show=None)


def hit_b2():
    with open('D:\python3.6.1\Zprogram3\day_done.txt', 'a') as f:
        if e.get() != '':
            f.write(e.get() + '\n')
class Remove_Machine_Modal(Modal):
	def __init__(self, parent=None, title="Remove Machine"):
		Modal.__init__(self, parent, title, geometry="500x85" if system() == "Windows" else "395x70")

	def initialize(self):
		self.label = Label(self, font=("TkTextFont", 13), width=36)
		self.label.grid(row=0, column=0, padx=10, columnspan=2)

		cancel_button = Button(self, text="Cancel", width=20, command=self.cancel)
		self.bind("<Escape>", self.cancel)
		cancel_button.grid(row=1, column=0, pady=10, padx=5, sticky="W")

		ok_button = Button(self, text="OK", width=20, command=self.ok)
		self.bind("<Return>", self.ok)
		ok_button.grid(row=1, column=1, pady=10, sticky="E")

	def ok(self, event=None):
		self.remove = True
		self.destroy()

	def cancel(self, event=None):
		self.remove = False
		self.destroy()

	def show(self, machine_name):
		self.label.config(text="Remove " + machine_name + "?")
		Modal.show(self)
		return self.remove