Beispiel #1
0
def login_screen():
    """creates the first screen where the user logs in to the game"""
    screen = ThemedTk(theme="arc")  # creating a window themed "arc"
    screen.geometry('880x540')
    screen.title("© Battleship by Shani Daniel ©")
    screen.configure(background='light blue')
    style_log = ttk.Style()

    ttk.Label(text='Welcome to Battleship', font=("Broadway", 50), foreground='black', background='light blue')\
        .pack(pady=40)
    ttk.Label(text='Login:'******'black',
              background='light blue').pack(pady=20)
    # writes the main game title and the "login" label

    username_login = tk.StringVar()
    password_login = tk.StringVar()
    ttk.Label(screen,
              text="Username:"******"Cooper black", 14),
              foreground='black',
              background='light blue').pack()
    tk.Entry(screen, textvariable=username_login).pack()
    ttk.Label(screen,
              text="Password:"******"Cooper black", 14),
              foreground='black',
              background='light blue').pack()
    tk.Entry(screen, textvariable=password_login, show='*').pack()

    # creates the username and password fields

    def login_click():
        login_button_click(screen, username_login, password_login)

    def register_click():
        register(screen)

    style_log.configure('log.TButton',
                        font=('Cooper Black', 16),
                        foreground='black')
    style_log.configure('reg.TButton',
                        font=('Cooper Black', 13),
                        foreground='black')
    ttk.Button(screen,
               text="Sign in",
               style='log.TButton',
               command=login_click).pack(pady=15)
    ttk.Button(screen,
               text="Register",
               style='reg.TButton',
               command=register_click).pack()
    # styles and creates the "sign in" and "register" buttons

    screen.mainloop()
class GUI:
    """This handles the GUI for ESMB"""
    def __init__(self):
        logging.debug("\tBuilding GUI...")

        # Build the application window
        self.gui = ThemedTk(theme="plastik")
        self.gui.title("ESMissionBuilder")
        self.gui.configure(bg="orange")

        # enable window resizing
        self.gui.columnconfigure(2, weight=1)
        self.gui.rowconfigure(0, weight=1)

        # set disabled styles
        self.disabledEntryStyle = ttk.Style()
        self.disabledEntryStyle.configure('D.TEntry', background='#D3D3D3')
        self.disabledComboboxStyle = ttk.Style()
        self.disabledComboboxStyle.configure('D.TCombobox',
                                             background='#D3D3D3')

        # Declare the frames
        self.option_pane = editor.OptionPane(self.gui)
        self.option_pane.grid(row=0, column=0, sticky="ns")

        self.center_pane = editor.MissionEditorPane(self.gui)
        self.center_pane.grid(row=0, column=1, sticky="ns")

        self.item_text_pane = editor.ItemTextPane(self.gui)
        self.item_text_pane.grid(row=0, column=2, sticky="nsew")

        config.gui = self
        self.gui.mainloop()

    #end init

    def update_option_pane(self):
        self.option_pane.update_pane()

    #end update_option_pane

    def update_center_pane(self):
        self.center_pane.update_pane()

    #end update_center_pane

    def update_item_text_pane(self):
        self.item_text_pane.update_pane()
Beispiel #3
0
# pickle.dump(encodings, pickle_out)
# pickle_out.close()





# ======================================Defining Main Window=====================================================

root = ThemedTk(theme='awdark')
root.title('Attendance System')
#root.iconbitmap('icon.ico')
root.geometry('1280x620')
# style = ThemedStyle(root)
# style.set_theme('smog')
root.configure(background='light grey')

style= ttk.Style()
style.theme_use('clam')
# adding picture
# img = ImageTk.PhotoImage(Image.open("C:\\Users\\addbi\\Desktop\\a"))

# panel = Label(root, image = img)
# panel.pack(side = "bottom", fill = "both", expand = "yes")


# defining frames

titleFrame = Frame(root, width='900', height='100')
titleFrame.pack(side=TOP)
top_style =ThemedStyle(titleFrame)
Beispiel #4
0
class GUI:
    e1 = ''
    e2 = ''
    e3 = ''
    thread_list = []
    MAX = 50

    def __init__(self):
        self.window = ThemedTk(theme="arc")  # arc breeze
        self.window.title("Web Scraping")
        self.window.configure(background="white")
        self.setInputs()
        self.setButtons()
        self.name = ''
        self.min1 = ''
        self.max1 = ''
        self.ans = []

    def start(self):
        self.window.mainloop()

    def setInputs(self):
        Label(self.window,
              text="Enter Category ",
              font=("Arial", 15),
              background="white",
              foreground="black").grid(row=2, padx=20, pady=10)
        Label(self.window,
              text="Enter Min Price ",
              font=("Arial", 15),
              background="white",
              foreground="black").grid(row=4, padx=20, pady=10)
        Label(self.window,
              text="Enter Max Price ",
              font=("Arial", 15),
              background="white",
              foreground="black").grid(row=6, padx=20, pady=10)
        Label(self.window, text="", font=("Arial", 15),
              background="white").grid(row=0)

        self.e1 = tk.Entry(self.window)
        self.e1.grid(row=2, column=1)
        self.e2 = tk.Entry(self.window)
        self.e2.grid(row=4, column=1)
        self.e3 = tk.Entry(self.window)
        self.e3.grid(row=6, column=1)

    def setButtons(self):
        tk.Button(self.window,
                  text=' Search ',
                  bg="#e0e0d1",
                  command=self.running).grid(row=8,
                                             column=1,
                                             sticky=tk.W,
                                             padx=20,
                                             pady=20)
        tk.Button(self.window, text=' Exit ', bg="#e0e0d1",
                  command=quit).grid(row=8,
                                     column=2,
                                     sticky=tk.W,
                                     padx=20,
                                     pady=20)
        # running()

    @staticmethod
    def callback(url):
        print(url)
        webbrowser.open_new(url)

    def on_change(self, e):
        print(e.widget.get())

    @staticmethod
    def readAnsFromCSV(name_of_file):
        data0 = []
        with open(name_of_file, 'r') as f:
            data1 = csv.reader(f)
            for row in data1:
                data0.append(row)
        return data0[1:]

    def do(self):
        obj = merged_code.result(self.name.strip(), self.min1, self.max1)
        self.ansfile = obj.getResult()
        print("answer file " + self.ansfile)
        self.ans = self.readAnsFromCSV(self.ansfile)
        print('result ' + str(len(self.ans)))
        time.sleep(0.01)
        print(self.ans)
        self.loading.quit()
        self.MAX = 0

    def loading(self):
        self.loading = ThemedTk(theme="arc")  # arc breeze
        self.loading.title("Loading")
        self.loading.configure(background="white")
        self.loading.geometry("260x140")
        self.loading_labe = Label(self.loading, text="",
                                  background="white").grid(row=0)
        self.loading_label = Label(self.loading,
                                   text="Please Wait ...",
                                   font=("Arial", 15),
                                   background="white",
                                   foreground="blue").grid(row=1,
                                                           pady=10,
                                                           padx=30)
        self.progress = Progressbar(self.loading,
                                    orient=HORIZONTAL,
                                    length=200,
                                    mode='indeterminate')
        self.progress.grid(row=2, pady=10, padx=30)
        k = 10
        while self.MAX != 0:
            self.progress['value'] = k
            k += 1
            time.sleep(0.01)
            self.loading.update()

        #self.progress.stop()
        #self.progress.grid_forget()
        self.loading.destroy()
        self.loading.mainloop()

    class Splash(tk.Toplevel):
        def __init__(self, parent):
            tk.Toplevel.__init__(self, parent)
            self.title("Splash")

    def running(self):
        self.name = self.e1.get()
        self.min1 = float(self.e2.get())
        self.max1 = float(self.e3.get())

        thread = threading.Thread(target=self.do)
        thread1 = threading.Thread(target=self.loading)
        thread1.start()
        thread.start()
        #        thread1.start()

        self.thread_list.append(thread)
        self.thread_list.append(thread1)

        for th in self.thread_list:
            th.join()
        self.show_entry_fields()

    def show_entry_fields(self):
        print(self.ans)
        self.flag = 0
        for i in range(len(self.ans)):
            if self.flag == 0:
                Label(self.window,
                      text="Model",
                      font=("Arial", 15),
                      background="white",
                      foreground="#000099").grid(row=10 + i,
                                                 column=0,
                                                 padx=25,
                                                 pady=10)
                Label(self.window,
                      text="Original Price",
                      font=("Arial", 15),
                      background="white",
                      foreground="#000099").grid(row=10 + i,
                                                 column=1,
                                                 padx=25,
                                                 pady=10)
                Label(self.window,
                      text="Flipkart Price",
                      font=("Arial", 15),
                      background="white",
                      foreground="#000099").grid(row=10 + i,
                                                 column=2,
                                                 padx=25,
                                                 pady=10)
                Label(self.window,
                      text="Rating",
                      font=("Arial", 15),
                      background="white",
                      foreground="#000099").grid(row=10 + i,
                                                 column=3,
                                                 padx=25,
                                                 pady=10)
                Label(self.window,
                      text="Number of Reviews",
                      font=("Arial", 15),
                      background="white",
                      foreground="#000099").grid(row=10 + i,
                                                 column=4,
                                                 padx=25,
                                                 pady=10)
                Label(self.window,
                      text="Link",
                      font=("Arial", 15),
                      background="white",
                      foreground="#000099").grid(row=10 + i,
                                                 column=5,
                                                 padx=25,
                                                 pady=10)
                self.flag = 111

            if len(self.ans[i][0]) > 40:
                titletemp = self.ans[i][0][:40] + '...'
            else:
                titletemp = self.ans[i][0]

            b1 = Label(self.window,
                       text=titletemp,
                       font=("Arial", 12),
                       background="white",
                       foreground="black")  # assign price 1
            b1.grid(row=12 + i, column=0, padx=25, pady=7.5)
            b2 = Label(self.window,
                       text=self.ans[i][1],
                       font=("Arial", 12),
                       background="white",
                       foreground="black")  # assign price 1
            b2.grid(row=12 + i, column=1, padx=25, pady=7.5)
            b3 = Label(self.window,
                       text=self.ans[i][2],
                       font=("Arial", 12),
                       background="white",
                       foreground="black")  # assign price 2
            b3.grid(row=12 + i, column=2, padx=25, pady=7.5)
            b4 = ttk.Label(self.window,
                           text=self.ans[i][3],
                           font=("Arial", 12),
                           background="white",
                           foreground="black")  # assign ratings
            b4.grid(row=12 + i, column=3, padx=25, pady=7.5)
            b5 = ttk.Label(self.window,
                           text=self.ans[i][4],
                           font=("Arial", 12),
                           background="white",
                           foreground="black")  # assign reviews
            b5.grid(row=12 + i, column=4, padx=25, pady=7.5)
            b6 = tk.Button(
                self.window,
                text="Click Here to know more",
                bg="white",
                fg="blue",
                command=lambda aurl=self.ans[i][5]: self.callback(aurl))
            b6.grid(row=12 + i, column=5, padx=25, pady=7.5)
        self.window.state("zoomed")
        self.w = self.window.winfo_screenwidth()
        self.h = self.window.winfo_screenheight()
        self.window.geometry("%dx%d+0+0" % (self.w, self.h))
Beispiel #5
0
    def __init__(self, playlists: list[Playlist], defaults: dict):

        root = ThemedTk(theme='black')
        root.option_add('*tearOff', tk.FALSE)
        root.wm_title("btecify")
        root.wm_iconbitmap('assets\\btecify.ico')
        root.resizable(width=False, height=False)
        root.wm_iconify()
        root.wm_deiconify()

        for namefont in tkfont.names(root):
            rootfont = tkfont.nametofont(namefont)
            rootfont.config(family="Lucida Console")

        def _onclose():
            self.output = ["EXIT"]
            root.destroy()

        root.protocol("WM_DELETE_WINDOW", _onclose)

        self.selectedplaylist = tk.StringVar()
        self.playlists = playlists
        self._generateplaylistnames()
        self.songqueuevar = tk.StringVar(value=[])
        self.volume = tk.IntVar(value=50)
        self.seek = tk.DoubleVar(value=0)
        self.songlistvar = tk.StringVar(value=[])
        self.playlistsongsvar = tk.StringVar(value=[])
        self.progressbarvar = tk.IntVar(value=0)
        self.songsearchqueryvar = tk.StringVar(value="")
        self.extrainfoplaylistsvar = tk.StringVar(value=[])
        self.searchfunc = searchsongname
        self.discordpresencevar = tk.BooleanVar(value=defaults['discord'])

        self.keybinds: list[tuple[str, str]] = []

        # CONSOLE
        consolewindow = tk.Toplevel(root)
        consolewindow.wm_title("Console Logs")
        consolewindow.wm_protocol("WM_DELETE_WINDOW",
                                  lambda: consolewindow.wm_withdraw())
        consolewindow.wm_withdraw()
        consolewindow.wm_resizable(False, False)

        consolewindowframe = ttk.Frame(consolewindow,
                                       padding=5,
                                       relief="groove")
        consolewindowframe.grid()

        consolewindowtext = tk.Text(consolewindowframe,
                                    foreground='white',
                                    background='black',
                                    state='disabled',
                                    width=100,
                                    height=40)
        consolewindowtext.grid(row=0, column=0)

        consolewindowtextscrollbar = ttk.Scrollbar(
            consolewindowframe,
            orient=tk.VERTICAL,
            command=consolewindowtext.yview)
        consolewindowtext['yscrollcommand'] = consolewindowtextscrollbar.set
        consolewindowtextscrollbar.grid(row=0, column=1, sticky='ns')

        def resetconsolewindow(*args):
            consolewindowtext.yview_moveto(1.0)

        consolewindowtext.bind('<Visibility>', resetconsolewindow)
        consolewindowtext.bind('<FocusIn>', resetconsolewindow)

        # KEYBINDS
        keybindwindow = tk.Toplevel(root)
        keybindwindow.wm_title("Keybindings")
        keybindwindow.wm_protocol("WM_DELETE_WINDOW",
                                  lambda: keybindwindow.wm_withdraw())
        keybindwindow.wm_resizable(False, False)
        keybindwindow.wm_withdraw()

        keybindwindowframe = ttk.Frame(keybindwindow,
                                       padding=5,
                                       relief='groove')
        keybindwindowframe.grid()

        keybindlistframe = ttk.Frame(keybindwindowframe,
                                     padding=3,
                                     relief='groove')
        keybindlistframe.grid(row=0, column=0)

        keybindings = [i for i in defaults['keybinds']]
        keybindlist = []
        for x in range(len(keybindings)):
            kbname = str(keybindings[x])
            newframe = ttk.Frame(keybindlistframe)
            newframe.grid(column=0, row=x)

            newlabel = ttk.Label(
                newframe,
                text=kbname + ": ",
                width=max(map(lambda a: len(a), keybindings)) + 2)
            newlabel.grid(row=0, column=0)

            keybindtextvariable = tk.StringVar("")
            newentry = ttk.Entry(newframe, textvariable=keybindtextvariable)
            newentry.grid(row=0, column=1)
            newentry.bind('<FocusIn>',
                          lambda *args: self._addchange('keybinds'))

            keybindlist.append((kbname, keybindtextvariable))

        keybindbuttonsframe = ttk.Frame(keybindwindowframe,
                                        padding=3,
                                        relief='groove')
        keybindbuttonsframe.grid(row=1, column=0)

        keybindbuttondefault = ttk.Button(
            keybindbuttonsframe,
            text="RESET TO DEFAULTS",
            command=lambda: self._setoutput("defaultkeybinds"))
        keybindbuttondefault.grid(row=0, column=0)

        keybindbuttonconfirm = ttk.Button(
            keybindbuttonsframe,
            text="CONFIRM KEYBINDINGS",
            command=lambda: self._setoutput(
                "updatekeybinds", [(i[0], i[1].get()) for i in keybindlist]))
        keybindbuttonconfirm.grid(row=0, column=1)

        # MENU
        menubar = tk.Menu(root)
        root.configure(menu=menubar)

        menuplaylist = tk.Menu(menubar)
        menusong = tk.Menu(menubar)
        menufile = tk.Menu(menubar)

        menubar.add_cascade(menu=menuplaylist, label="Playlist")
        menubar.add_cascade(menu=menusong, label="Song")
        menubar.add_cascade(menu=menufile, label="File")

        menubar.add_separator()

        menubar.add_command(label="Playlist: None", state="disabled")
        menubarplaylistlabelindex = len(menubar.winfo_children()) + 1

        menuplaylist.add_command(label="New...", command=self._newplaylist)
        menuplaylist.add_command(label="Delete", command=self._deleteplaylist)
        menuplaylist.add_command(label="Rename...",
                                 command=self._renameplaylist)
        menuplaylist.add_command(label="Copy...", command=self._copyplaylist)
        menuplaylist.add_separator()
        menuplaylist.add_command(label="Reset watched",
                                 command=self._unwatchplaylist)
        menuplaylist.add_command(label="Requeue", command=self._requeue)
        menuplaylist.add_separator()
        menuplaylist.add_command(label="Reset from Youtube",
                                 command=self._resetfromyoutube)

        menusong.add_command(label="New...", command=self._newsong)
        menusong.add_command(label="Delete",
                             command=lambda: self._setoutput(
                                 "deletesongs", *self._getselectedsongs()))
        menusong.add_separator()
        menusong.add_command(label="Add selected songs to selected playlist",
                             command=self._addsongtoplaylist)
        menusong.add_command(
            label="Remove selected songs from selected playlist",
            command=lambda: self._setoutput("removesongsfromplaylist",
                                            self._getselectedplaylist(),
                                            self._getselectedsongs()))
        menusong.add_separator()
        menusong.add_command(label="Play selected song",
                             command=self._playselectedsong)
        menusong.add_command(label="Play random song",
                             command=lambda: self._setoutput("randomsong"))

        menufile.add_command(label="View console logs...",
                             command=consolewindow.wm_deiconify)
        menufile.add_command(
            label="Open data directory...",
            command=lambda: self._setoutput("opendatadirectory"))
        menufile.add_separator()
        menufile.add_command(label="Change keybinds...",
                             command=keybindwindow.wm_deiconify)
        menufile.add_separator()
        menufile.add_checkbutton(
            label="Discord Presence",
            command=lambda: self._setoutput('discordpresence',
                                            self.discordpresencevar.get()),
            variable=self.discordpresencevar)
        menufile.add_separator()
        menufile.add_command(label="Change API key...",
                             command=lambda: self._setoutput("newapikey"))
        menufile.add_separator()
        menufile.add_command(label="Login Details...",
                             command=self._logindetails)
        menufile.add_command(label="Sync playlist to btecify servers",
                             command=lambda: self._setoutput("syncwithserver"))

        # PRIMARY FRAME

        primaryframe = ttk.Frame(root)
        primaryframe.grid()

        # QUEUE
        queuelabelframe = ttk.Labelframe(primaryframe,
                                         text="Song queue",
                                         relief='groove',
                                         borderwidth=5)
        queuelabelframe.grid(column=0,
                             row=0,
                             columnspan=2,
                             rowspan=2,
                             sticky='nswe')

        queuelist = mylistbox(queuelabelframe,
                              height=15,
                              listvariable=self.songqueuevar,
                              width=50,
                              exportselection=False,
                              selectmode=tk.MULTIPLE)
        queuelistscrollbar = ttk.Scrollbar(queuelabelframe,
                                           orient=tk.VERTICAL,
                                           command=queuelist.yview)

        queuelist.grid(column=0, row=0, sticky='nswe')
        queuelistscrollbar.grid(column=1, row=0, sticky='ns')

        queuelist['yscrollcommand'] = queuelistscrollbar.set

        # PLAYER INFORMATION
        playingframe = ttk.Labelframe(primaryframe,
                                      text="Playing Song",
                                      relief='groove',
                                      padding=5)
        playingframe.grid(column=2, row=0, sticky='new')

        songinfo = ttk.Label(
            playingframe,
            text=
            f"No playlist\nNo song playing\nNo song author\nNo duration\n{PLAYINGINFOPLACEHOLDER}",
            justify=tk.CENTER,
            anchor=tk.CENTER)
        songinfo.grid(column=0, row=0, sticky='ew')

        songdesc = ttk.Label(playingframe,
                             text="",
                             justify=tk.CENTER,
                             anchor=tk.CENTER)
        songdesc.grid(column=0, row=1)

        songprogress = ttk.Progressbar(playingframe,
                                       orient=tk.HORIZONTAL,
                                       mode='determinate',
                                       variable=self.progressbarvar)
        songprogress.grid(column=0, row=3, sticky='wes')

        songseeker = ttk.Scale(playingframe, from_=0, to=1, variable=self.seek)
        songseeker.grid(column=0, row=4, sticky='wes')
        songseeker.bind("<ButtonPress-1>",
                        lambda *args: self.changes.update({'seeking': True}))
        songseeker.bind("<ButtonRelease-1>",
                        lambda *args: self.changes.update({'seeking': False}))

        playingframe.grid_rowconfigure((0, 1, 2, 3), weight=1)

        # SONG SELECTION AND SONG VIEWING
        songselectionandviewingframe = ttk.Frame(primaryframe)
        songselectionandviewingframe.grid(column=3,
                                          row=0,
                                          columnspan=2,
                                          rowspan=2)

        songlistnotebook = ttk.Notebook(songselectionandviewingframe)
        songlistnotebook.grid(column=0, row=0)

        songlistframe = ttk.Frame(songlistnotebook, padding=1)

        songlist = mylistbox(songlistframe,
                             height=15,
                             listvariable=self.songlistvar,
                             selectmode=tk.MULTIPLE,
                             bg="#282828",
                             disabledforeground="gray80",
                             fg="white",
                             activestyle='dotbox',
                             selectbackground="#282828",
                             selectforeground="red2",
                             width=50,
                             exportselection=False)
        songlistscrollbar = ttk.Scrollbar(songlistframe,
                                          orient=tk.VERTICAL,
                                          command=songlist.yview)
        ################################################################################################################

        playlistsongsframe = ttk.Frame(songlistnotebook, padding=1)

        playlistsongslist = mylistbox(playlistsongsframe,
                                      height=15,
                                      listvariable=self.playlistsongsvar,
                                      selectmode=tk.MULTIPLE,
                                      bg="#282828",
                                      disabledforeground="gray80",
                                      fg="white",
                                      activestyle='dotbox',
                                      selectbackground="#282828",
                                      selectforeground="red2",
                                      width=50,
                                      exportselection=False)
        playlistsongslistscrollbar = ttk.Scrollbar(
            playlistsongsframe,
            orient=tk.VERTICAL,
            command=playlistsongslist.yview)
        ################################################################################################################

        _songlistsearchchangedcommand = root._register(
            self._songlistsearchchanged)
        songsearchentry = ttk.Entry(
            songselectionandviewingframe,
            validate="all",
            validatecommand=(_songlistsearchchangedcommand, '%V'),
            textvariable=self.songsearchqueryvar,
        )

        self.completeselectedsongs: list[Song] = []

        resetsonglistselectionbutton = ttk.Button(
            songselectionandviewingframe,
            text="RESET SELECTION|SELECTED: 0",
            command=lambda: self._addchange("resetselectedsongs"))

        songlist.grid(row=0, column=0, columnspan=2)
        songlistscrollbar.grid(row=0, column=2, sticky='wns')

        playlistsongslist.grid(row=0, column=0, columnspan=2)
        playlistsongslistscrollbar.grid(row=0, column=2, sticky='wns')

        songsearchentry.grid(row=1, column=0, sticky='ews')
        resetsonglistselectionbutton.grid(row=2, column=0, sticky='nw')

        songlist['yscrollcommand'] = songlistscrollbar.set
        playlistsongslist['yscrollcommand'] = playlistsongslistscrollbar.set

        songlistnotebook.add(songlistframe, text="Song list")
        songlistnotebook.add(playlistsongsframe, text="empty")

        # BOTTOM LEFT LOGO
        btecifyiconimage = tk.PhotoImage(file="assets/btecify64.png")
        btecifyiconlabel = ttk.Label(primaryframe, image=btecifyiconimage)
        btecifyiconlabel.grid(column=0, row=2, sticky='ws')

        # PLAYLIST SELECT
        playlistselectframe = ttk.LabelFrame(primaryframe,
                                             text="Playlist select",
                                             relief='groove',
                                             padding=3)
        playlistselectframe.grid(row=2, column=3, sticky='wn')

        playlistselectcombobox = ttk.Combobox(
            playlistselectframe,
            values=self.playlistnames,
            textvariable=self.selectedplaylist,
            width=26,
            state='readonly')
        self.selectedplaylist.trace_add(
            mode="write", callback=self._playlistcomboboxvalueupdated)
        playlistselectcombobox.set(playlists[0].name)
        playlistselectcombobox.grid(sticky='ewn')

        playlistselectbutton = ttk.Button(playlistselectframe,
                                          text="SWITCH TO PLAYLIST",
                                          command=self._chooseplaylist)
        playlistselectbutton.grid(row=1, sticky='s')

        # PLAYER BUTTONS
        bottommiddleframe = ttk.LabelFrame(primaryframe,
                                           text="Player controls",
                                           relief='groove',
                                           padding=5)
        bottommiddleframe.grid(column=2, row=1, sticky='wnse')

        pausebutton = ttk.Button(bottommiddleframe,
                                 text="PAUSE",
                                 command=self._pause)
        pausebutton.grid(row=0, column=0, columnspan=3, sticky='ew')

        skipbutton = ttk.Button(bottommiddleframe,
                                text="SKIP",
                                command=self._skip)
        skipbutton.grid(row=1, sticky='w')

        loopbutton = ttk.Button(bottommiddleframe,
                                text="LOOP: DISABLED",
                                command=lambda: self._setoutput("loop"))
        loopbutton.grid(row=1, column=1, padx=120)

        removesongbutton = ttk.Button(bottommiddleframe,
                                      text="REMOVE SONG",
                                      command=self._playerremovesongbutton)
        removesongbutton.grid(row=1, column=2, sticky='e')

        volumeslider = ttk.LabeledScale(bottommiddleframe,
                                        from_=0,
                                        to=100,
                                        variable=self.volume,
                                        compound='bottom')
        volumeslider.scale.set(defaults['volume'])
        volumeslider.scale.configure(command=self._volchange)
        volumeslider.label.update()
        volumeslider.grid(row=2, columnspan=3, sticky='ew')

        bottommiddleframe.grid_rowconfigure((0, 1, 2), weight=1)
        bottommiddleframe.grid_columnconfigure((0, 1), weight=1)

        # EXTRA SONG INFORMATION
        extrasonginfoframe = ttk.Labelframe(primaryframe,
                                            text="Song Info",
                                            relief="sunken",
                                            padding=3)
        extrasonginfoframe.grid(row=2, column=1, columnspan=2, sticky="nesw")

        extrasonginfoname = ttk.Label(extrasonginfoframe,
                                      text="NO SONG",
                                      justify=tk.LEFT,
                                      anchor="w")
        extrasonginfoname.grid(row=0, column=0, sticky="nesw")

        extrasonginfoplaylistlabelframe = ttk.Labelframe(extrasonginfoframe,
                                                         text="In Playlists",
                                                         relief="groove",
                                                         padding=5)
        extrasonginfoplaylistlabelframe.grid(row=1, column=0, sticky="w")

        extrasonginfoplaylists = mylistbox(
            extrasonginfoplaylistlabelframe,
            height=5,
            selectmode="browse",
            listvariable=self.extrainfoplaylistsvar,
            exportselection=False)
        extrasonginfoplaylists.grid(row=0, column=0, sticky="")

        extrasonginfoplaylistsresetbutton = ttk.Button(
            extrasonginfoplaylistlabelframe,
            text="RESET",
            command=lambda: extrasonginfoplaylists.selection_clear(
                0, 100000) or self.extraplaylistselection.clear(
                ))  # Executes two statements in one lambda.

        extrasonginfoplaylistsresetbutton.grid(row=1, column=0, sticky='nesw')

        extrasonginfobuttonsframe = ttk.Frame(extrasonginfoplaylistlabelframe,
                                              padding=2)
        extrasonginfobuttonsframe.grid(row=0, column=1, sticky='nesw')

        extrasonginforemovebutton = ttk.Button(
            extrasonginfobuttonsframe,
            text="REMOVE SONG FROM PLAYLISTS",
            command=self._extrasonginforemovebuttonfunc)
        extrasonginforemovebutton.grid(row=0, column=0, sticky='')

        extrasonginfoopensong = ttk.Button(
            extrasonginfobuttonsframe,
            text="OPEN IN YOUTUBE",
            command=lambda: self._setoutput("openinyoutube", [
                *self.completeselectedsongs
            ] or [self._getselectedsong()]))
        extrasonginfoopensong.grid(row=1, column=0, sticky='')

        def _updatebasedonvalues():
            extrasongselectedplaylistvalues = self._getextrasongselectedplaylists(
                extrasonginfoplaylists)
            if self.changes[
                    'songinfo'] or extrasongselectedplaylistvalues != self.extraplaylistselection:
                if self.playingsong is not None:
                    self.progressbarvar.set(value=self.progressbar)
                    playlistofthissong = self.playlistwhichsongisfrom
                    if playlistofthissong is None:
                        playlistofthissong = "Played manually"
                        removesongbutton.configure(state='disabled')
                    else:
                        playlistofthissong = playlistofthissong.name
                        removesongbutton.configure(state='active')
                    songinfo['text'] = (
                        f"{playlistofthissong}\n{self.playingsong.name[:len(PLAYINGINFOPLACEHOLDER)]}\n{self.playingsong.author}\n{self.playingsong.duration}\n"
                        + PLAYINGINFOPLACEHOLDER)
                    if self.paused:
                        songdesc['text'] = "PAUSED"
                        pausebutton['text'] = "PLAY"
                    else:
                        songdesc['text'] = "PLAYING"
                        pausebutton['text'] = "PAUSE"

                if self.loop:
                    loopbutton['text'] = "LOOP: ENABLED"
                else:
                    loopbutton['text'] = "LOOP: DISABLED"

                targetsong = self._getselectedsong()
                if targetsong is not None:
                    extrasonginfoname['text'] = targetsong.name[:(
                        queuelist.cget("width") //
                        3) + len(PLAYINGINFOPLACEHOLDER)]
                    self.playlistswithtargetsong = list(
                        filter(lambda a: targetsong in a.getsongs(),
                               self.playlists))
                    self.extrainfoplaylistsvar.set(
                        [i.name for i in self.playlistswithtargetsong])
                    extrasonginfoplaylists.selection_clear(0, 1000000)
                    self.extraplaylistselection.extend([
                        i for i in extrasongselectedplaylistvalues
                        if i not in self.extraplaylistselection
                    ])

                    for i, v in enumerate(self.extraplaylistselection):
                        if v in self.playlistswithtargetsong:
                            extrasonginfoplaylists.selection_set(
                                self.playlistswithtargetsong.index(v))
                        else:
                            self.extraplaylistselection.remove(v)
                else:
                    extrasonginfoname['text'] = "NO SONG"
                    self.extrainfoplaylistsvar.set([])
                    extrasonginfoplaylists.selection_clear(0, 10000)

                self._addchange('songinfo', False)

            if self.changes['resetselectedsongs']:
                songlist.selection_clear(0, 100000000)
                queuelist.selection_clear(0, 100000)
                playlistsongslist.selection_clear(0, 100000)

                self.completeselectedsongs = []
                resetsonglistselectionbutton.configure(
                    text=f"RESET SELECTION   |   SELECTED: 0")
                self._addchange('songinfo')
                self._addchange('resetselectedsongs', False)

            currentlyselectedsonglistvalues = self._getselectedvalues(
                songlist, self.displaysonglist)
            currentlyselectedqueuevalues = self._getselectedvalues(
                queuelist, self.songqueue)
            currentlyselectedplaylistsongsvalues = self._getselectedvalues(
                playlistsongslist, self.displayplaylistsongs)
            displayablesongsinsonglist = set([
                i for i in self.displaysonglistnew
                if i in self.completeselectedsongs
            ])
            displayablesongsinqueuelist = set([
                i for i in self.songqueuenew if i in self.completeselectedsongs
            ])
            displayablesongsinplaylistsongslist = set([
                i for i in self.displayplaylistsongsnew
                if i in self.completeselectedsongs
            ])

            if self.changes['songlist'] or (
                    currentlyselectedsonglistvalues !=
                    displayablesongsinsonglist
            ) or (displayablesongsinqueuelist != currentlyselectedqueuevalues
                  ) or (displayablesongsinplaylistsongslist !=
                        currentlyselectedplaylistsongsvalues):
                if self.changes['songlist']:
                    self._songlistsearchchanged()
                    self.songlistvar.set(
                        value=[i.name for i in self.displaysonglistnew])
                    self.playlistsongsvar.set(
                        value=[i.name for i in self.displayplaylistsongsnew])
                    self.displaysonglist = self.displaysonglistnew
                    self.displayplaylistsongs = self.displayplaylistsongsnew

                    songlist.selection_clear(0, 1000000)
                    queuelist.selection_clear(0, 1000000)
                    playlistsongslist.selection_clear(0, 10000)

                    self._addchange('songinfo')
                    self._addchange('songlist', False)
                else:
                    self.completeselectedsongs.extend([
                        i for i in currentlyselectedsonglistvalues
                        if i not in self.completeselectedsongs
                    ])
                    self.completeselectedsongs.extend([
                        i for i in currentlyselectedqueuevalues
                        if i not in self.completeselectedsongs
                    ])
                    self.completeselectedsongs.extend([
                        i for i in currentlyselectedplaylistsongsvalues
                        if i not in self.completeselectedsongs
                    ])
                    for song in self.completeselectedsongs:
                        if song:
                            if song in self.displaysonglistnew:
                                songlist.selection_set(
                                    self.displaysonglistnew.index(song))
                            if song in self.songqueuenew:
                                queuelist.selection_set(
                                    self.songqueuenew.index(song))
                            if song in self.displayplaylistsongsnew:
                                playlistsongslist.selection_set(
                                    self.displayplaylistsongsnew.index(song))
                    self._addchange('songinfo')
                    resetsonglistselectionbutton.configure(
                        text=
                        f"RESET SELECTION   |   SELECTED: {len(self.completeselectedsongs)}"
                    )

            if self.changes['songqueue']:
                queuelist.selection_clear(0, 100000)
                self.songqueue = self.songqueuenew
                self.songqueuevar.set(value=[
                    f"{i+1:>3}: {v.name}" for i, v in enumerate(self.songqueue)
                ])
                self._addchange('songqueue', False)

            if self.changes['playlistoptions']:
                self._generateplaylistnames()
                playlistselectcombobox['values'] = self.playlistnames
                self._addchange('songinfo')
                self._addchange('playlistoptions', False)

            if self.changes['progressbar']:
                self.progressbarvar.set(value=self.progressbar)
                self._addchange('progressbar', False)

            if self.changes['playlistcomboboxupdate']:
                playlist = self._getselectedplaylist()
                label = "Playlist: "
                if playlist:
                    label += playlist.name
                else:
                    label += "None"
                menubar.entryconfigure(menubarplaylistlabelindex, label=label)

                songlistnotebook.tab(1, text=self._getselectedplaylist().name)
                self._addchange("songlist")
                self._addchange('playlistcomboboxupdate', False)

            if self.changes['updatelogs']:
                logstoadd = self.newlogs[len(self.logs):]
                consolewindowtext['state'] = 'normal'
                for log in logstoadd:
                    logstr = ""
                    timevalues = log[0]
                    logstr += f"{timevalues.tm_hour:0>2}:{timevalues.tm_min:0>2}:{timevalues.tm_sec:0>2}: "
                    for obj in log[1]:
                        objstring = str(obj).replace("\n", "\n\t  ")
                        logstr += objstring + " "
                    consolewindowtext.insert('end', logstr + "\n\n")
                consolewindowtext['state'] = 'disabled'

                self.logs = self.newlogs
                self._addchange('updatelogs', False)

            if self.changes['seeking']:
                val = self.seek.get()
                if 0 < val < 1:
                    self._setoutput('seek', self.seek.get())

            if self.changes['keybinds']:
                for kbset in keybindlist:
                    for j in self.keybinds:
                        if j[0] == kbset[0]:
                            kbset[1].set(j[1])
                self._addchange("keybinds", False)

            root.after(10, _updatebasedonvalues)

        _updatebasedonvalues()

        G.musicgui = self
        root.mainloop()
Beispiel #6
0
def chf(value):
    variable.set(value)
    view()


def populate_menu(w, **cmds):
    menu = w['menu']
    menu.delete(0, "end")
    for name, func in cmds.items():
        menu.add_command(label=name,
                         command=lambda name=name, func=func: func(name))


window = ThemedTk(theme="equilux")
window.geometry("260x220")
window.configure(bg='#424141')
window.title("Curs Valutar")

variable = StringVar(window)
variable.set("EUR")

w = ttk.OptionMenu(window, variable, ())
w.grid(row=1, column=1)

populate_menu(w, EUR=eur, USD=usd, GBP=gbp, CHF=chf)

tree = ttk.Treeview(window,
                    height=6,
                    column=(
                        "column1",
                        "column2",
Beispiel #7
0
class TestThemedTk(unittest.TestCase):
    def setUp(self):
        self.tk = ThemedTk()

    def tearDown(self):
        self.tk.destroy()

    def test_themes_available(self):
        available_themes = self.tk.get_themes()
        for theme in THEMES:
            if theme not in available_themes:
                raise AssertionError("Theme {} not available".format(theme))

    def test_theme_setting(self):
        button = ttk.Button(self.tk)
        label = ttk.Label(self.tk)
        button.pack()
        label.pack()
        self.tk.update()
        for theme in self.tk.get_themes():
            self.tk.set_theme(theme)
            self.tk.update()

    def test_custom_theme(self):
        if not self.tk.png_support:
            return
        for theme in self.tk.pixmap_themes:
            tk = ThemedTk()
            tk.set_theme_advanced(theme,
                                  brightness=0.2,
                                  saturation=1.4,
                                  hue=1.8)
            tk.destroy()
        return

    def test_toplevel_hook(self):
        __init__toplevel = tk.Toplevel.__init__
        self.tk.set_theme("black", True, False)
        self.assertNotEqual(__init__toplevel, tk.Toplevel.__init__)
        top = tk.Toplevel(self.tk)
        color = ttk.Style(self.tk).lookup("TFrame", "background")
        self.assertIsNotNone(color)
        self.assertEqual(top.cget("background"), color)
        top.destroy()

    def test_tk_background(self):
        self.tk.config(background="white")
        self.tk.set_theme("black", False, True)
        self.assertNotEqual(self.tk.cget("background"), "white")

    def test_config_cget(self):
        self.tk.config(theme="equilux")
        self.assertEqual(self.tk.cget("theme"), self.tk.current_theme)
        self.assertEqual(self.tk.cget("theme"), "equilux")

        self.tk.config(themebg=True)
        self.assertTrue(self.tk.cget("themebg"))
        before = self.tk.cget("bg")
        self.tk.config(themebg=False)
        self.assertFalse(self.tk.cget("themebg"))
        after = self.tk["bg"]
        self.assertNotEqual(before, after)

        self.tk.config(toplevel=False)
        self.assertFalse(self.tk.cget("toplevel"))
        orig = tk.Toplevel.__init__
        self.tk["toplevel"] = True
        self.assertTrue(self.tk.cget("toplevel"))
        self.assertNotEqual(orig, tk.Toplevel.__init__)

        self.tk.configure(toplevel=False)
        self.assertEqual(tk.Toplevel.__init__, orig)
from tkinter import *
from PIL import ImageTk, Image
import requests
from io import BytesIO
import json
import config

from tkinter import ttk  # Normal Tkinter.* widgets are not themed!
from ttkthemes import ThemedTk

# ttk.Button(window, text="Quit", command=window.destroy).pack()

root = ThemedTk(theme="adapta")
root.configure(bg="white", padx=20, pady=20)
root.iconbitmap("./src/weather.ico")
root.title("Weather App")

ttk.Label(root, text="Enter City Name : ").grid(row=0, column=0)
city = ttk.Entry(root, width=20, justify=CENTER)
city.grid(row=0, column=1)

ttk.Label(root, text="Enter State Name : ").grid(row=1, column=0)
state = ttk.Entry(root, width=20, justify=CENTER)
state.grid(row=1, column=1)

ttk.Label(root, text="Enter Country Name : ").grid(row=2, column=0)
country = ttk.Entry(root, width=20, justify=CENTER)
country.grid(row=2, column=1)
data_frame = LabelFrame(root, text="Current Weather")
img_frame = LabelFrame(root, text="Weather Icon")
Beispiel #9
0
#The creation of the main window
if __name__ == '__main__':
    if Config.RPCEnable:
        RPC = Presence(Config.ClientId)
        RPC.connect()
        DefaultPresence()
    ConfigLoad()
    MainWindow = ThemedTk(theme=Config.Theme)
    Update()
    #Styles
    s = ttk.Style()
    s.configure('TButton', background=Config.FG_Colour, fieldbackground=Config.FG_Colour)
    s.configure('TCheckbutton', background=Config.BG_Colour, foreground="white")
    s.configure('TEntry', fieldbackground=Config.FG_Colour, background=Config.FG_Colour)

    MainWindow.configure(background=Config.BG_Colour) # sets bg colour
    MainWindow.title("PyMyMC") # sets window title
    if System == "Windows":
        #other systems dont use ico
        MainWindow.iconbitmap(Path.Logo_Icon) # sets window icon
    MainWindow.resizable(False, False) #makes the window not resizable
    MainWindow.protocol("WM_DELETE_WINDOW", ExitHandler) #runs the function when the user presses the X button

    #Logo Image
    PyMyMC_Logo = PhotoImage(file=Path.Logo_Small)
    PyMyMC_Logo_Label = Label(MainWindow, image=PyMyMC_Logo)
    PyMyMC_Logo_Label['bg'] = PyMyMC_Logo_Label.master['bg']
    PyMyMC_Logo_Label.grid(row=0, column=0) 

    #Info Label
    PInfo_Label = Label(MainWindow, text=f"PyMyMC {Config.Version}", bg=Config.BG_Colour, fg = 'white', font = "Arial 15 bold")
Beispiel #10
0
import threading
from pygame import mixer
from tkinter import messagebox
from tkinter import filedialog
from tkinter import *
from tkinter import ttk
from ttkthemes import ThemedTk
from mutagen.mp3 import MP3

# from back import *

root = ThemedTk(theme="black")

root.title("AfroBit")
root.iconbitmap(r"icons/afrobit.ico")
root.configure(background="brown")

# initialize mixer
mixer.init()

paused = False  # for pausing and unpause song
filename_path = None
play_list = []
# contains song full path plus the song,path required to load the music in play function
# playlist contains only the filename
# browse file to play


def browse_file():
    """opens a music file
    """
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
#import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import ttk  # Normal Tkinter.* widgets are not themed!
from ttkthemes import ThemedTk
import requests
import json

r = ThemedTk(theme="equilux")  # breeze,arc,equilux
r.geometry("1200x600")
r.configure(bg="#464646")
figure2 = plt.Figure(figsize=(12, 6), dpi=100)
ax2 = figure2.add_subplot(111)
figure2.patch.set_facecolor('#464646')

rightframe = ttk.Frame(r)


def get_country():

    country_name = e1.get()
    #print(country_name)
    request = requests.get(
        "https://pomber.github.io/covid19/timeseries.json").text
    data = json.loads(request)

    covid_date = []
    covid_cases = []
    covid_deaths = []
Beispiel #12
0
def menu_screen():
    window = ThemedTk(
        theme="arc")  # creating the menu window with the theme "arc"
    window.title("© Battleship by Shani Daniel ©")
    window.configure(background='light blue')
    ttk.Label(window,
              text="Welcome to Battleship",
              font=("Broadway", 50),
              foreground='black',
              background='light blue').pack(pady=50)
    window.geometry('880x540')

    style = ttk.Style(window)
    style.configure('Option.TButton',
                    font=('Cooper Black', 24),
                    foreground='black')

    def play_against_comp(
    ):  # pressing this button on the menu will close the menu window and start this game window
        window.withdraw()
        GameUI.play_against_comp()
        window.update()
        window.deiconify()

    def play_against_player(
    ):  # pressing this button on the menu will close the menu window and start this game window
        window.withdraw()
        GameUI.play_against_player()
        window.update()
        window.deiconify()

    def stats():
        stats_screen()

    def del_user():
        delete_user(window)

    def change_user_name():
        change_username(window)

    ttk.Button(window,
               text="Play Against Computer",
               style='Option.TButton',
               command=play_against_comp).pack(pady=10)
    ttk.Button(window, text="Play Against Another Player", style='Option.TButton', command=play_against_player)\
        .pack(pady=10)
    ttk.Button(window,
               text="Statistics",
               style='Option.TButton',
               command=stats).pack(pady=10)
    tk.Label(window, text="", background='light blue').pack()
    tk.Button(window,
              text="Change Username",
              font=("Cooper Black", 12),
              background="white",
              foreground='black',
              command=change_user_name).pack(pady=5)
    tk.Button(window,
              text="Delete User",
              font=("Cooper Black", 12),
              background="white",
              foreground='black',
              command=del_user).pack(pady=5)
    # creating the different buttons on the menu screen

    window.mainloop()
Beispiel #13
0
    'elegance',
    'equilux',
    'itft1',
    'keramik',
    'kroc',
    'plastik',
    'radiance',
    'scid themes',
    'smog',
    'winxpblue',
    'yaru'
]
# Window color
window = ThemedTk(theme=Themes[-1])
window.wm_minsize(500, 500)
window.configure(background='pink')

s = ttk.Style()
# Create style.css used by default for all Frames
s.configure('TFrame', background='green')
# Create style.css for the first frame
s.configure('Frame1.TFrame', background='red')
# Create style.css for the second frame
s.configure('Frame2.TFrame', background='blue')

# …………………………

F1 = ttk.Frame(window, style='Frame1.TFrame', height=100, width=100).pack()

# 标签框是一个简单的容器小部件。它的主要目的是充当复杂窗口布局的间隔物或容器
lfr = ttk.Labelframe(window, text='This is a A').pack(fill=BOTH, expand=True)
Beispiel #14
0
    'Центр-инвест': 'Сочи, ул. Роз, 37',
    'Кубань Кредит': 'Сочи, ул. Горького, 43',
    'ББР Банк': 'Сочи, ул. Конституции СССР, 20',
    'Банк Интеза': 'Сочи, ул. Несебрская, 6',
    'БКС Банк': 'Сочи, ул. Московская, 3к4'
}

banks_adress = banks.copy()

PATH_1 = "https://ru.myfin.by/currency/sochi"
PATH_2 = "https://ru.myfin.by/currency/sochi?page=2"
info = []

root = ThemedTk()
root.title('Currency rates info [Sochi]')
root.configure(background='#67C95D')
root.geometry('1600x880+150+50')
root.resizable(False, False)


def parsing(p):
    try:
        file = requests.get(p)
        f = file.text
        soup = BeautifulSoup(f, 'html.parser')
        my_text = soup.find_all('td')

        for i in my_text:
            item = i.text
            info.append(item)
    except:
Beispiel #15
0
height = splashscreen.winfo_screenheight()

x_start = (width / 2) - 216
y_start = (height / 2) - 216
splashscreen.geometry('%dx%d+%d+%d' % (432, 432, x_start, y_start))
canvas = Canvas(splashscreen, height=432, width=432, bg="yellow")
canvas.pack()
image = PhotoImage(file="BombermanSigil.gif")

canvas.create_image(216, 216, image=image)

splashscreen.after(2500, splashscreen.destroy)
splashscreen.mainloop()

main_win = ThemedTk(theme="black")
main_win.configure(background='#626262')
main_win.minsize(width=800, height=300)
main_win.title("Bolibompa3")

ttk.Style().configure("black.Treeview", borderwidth=15)

main_win.finale_file = ''
gff_file = ''
create_order = 0

pyrocues = []
dmxques = []
shortcutFile = open('shortcuts.csv', 'r')

plocka_eget = []
plocka_gff = []
Beispiel #16
0
    first_frame.grid_forget()
    third_frame.grid(column=0,
                     row=0,
                     padx=20,
                     pady=5,
                     sticky=(tkinter.W, tkinter.N, tkinter.E))


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

# GUI Code

root = ThemedTk(theme="arc")
root.title("Magic Motion Maker")
root.columnconfigure(0, weight=1)
root.configure(bg="#f5f6f7")

# Define window size
window_width = 800
window_height = 600

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

x = (screen_width / 2) - (window_width / 2)
y = (screen_height / 2) - (window_height / 2)

root.geometry(f'{window_width}x{window_height}+{int(x)}+{int(y)}')

# Create frames inside the root window to hold other GUI elements.
# All frames must be created in the main program, otherwise they are not accessible in functions.
import requests
import urllib.parse
import io
import time
from tkinter import filedialog
import os
import threading


root = ThemedTk(theme="radiance")
root.title("Youtbe video downloader")
root.geometry('670x340')
root.maxsize(670, 340)
root.minsize(670, 340)
root.iconbitmap('images/youtube-downloader.ico')
root.configure(bg='#100E17')

text = tk.Label(root, text="Download Video and Audio from YouTube",
                font='Helvetica 15 bold', bg="#100E17", fg="white")
text.pack()

status = tk.Label(root, text="Status bar", font='Helvetica 10',
                  relief='sunken', anchor="w",bg="#312D3C",fg="white")
status.pack(side="bottom", fill='x')

# Creating threads


def threadButtonOne():
    threading.Thread(target=download_yt_file).start()
Beispiel #18
0
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

#------------
#Erzeugung der GUI
#------------

#Erstellt das Fenster mit dem gewünschten Aussehen
window = ThemedTk(theme='arc')
window.resizable(0,0)
window.title("Gruppenfoto 2.0")
window.configure(bg='white')

#Läd das Programmicon
window.iconbitmap(resource_path('logo.ico')) 

#Definiert die gewünschten Schriftarten und Stile der Benutzeroberfläche
fontStyle = tkFont.Font(size=12, family= "Calibri")
fontStyle_label = tkFont.Font(size=15, family='Calibri Light')
ttk.Style().configure(".", padding=6, relief="flat",
   foreground="black", background="white", font=fontStyle)
ttk.Style().configure("TLabel", font=fontStyle_label)
ttk.Style().configure("TEntry", font=fontStyle)
fontStyle_2 = tkFont.Font(size=25, family='Calibri Light')

#-----------
#Definieren und setzen der Elemente
def buildGUI():
    #Creating the user interface with a function
    # Application Name
    window = ThemedTk(theme='equilux')
    bgColor = '#333231'
    window.configure(bg=bgColor)
    window.title("Video Vis")  # Label
    window.geometry('800x850')
    lbl = ttk.Label(
        window,
        text=
        "Please search for a YouTube video category to display visual analysis: ",
        font=("Lato Bold", 15)).pack()  # Click event

    def CategoryClick(event):
        selected = categoryDropDown.current()
        option = categories[selected]
        graphMaker(option)

    file = pandas.read_csv("stats/avgComments.csv")
    categoryDF = file['Category']
    categories = categoryDF.values.tolist()

    clicked = tk.StringVar()
    clicked.set(categories[0])

    categoryDropDown = ttk.Combobox(window,
                                    values=categories,
                                    width=53,
                                    font=("Lato 15"))
    categoryDropDown.current(0)
    categoryDropDown.bind('<<ComboboxSelected>>', CategoryClick)
    categoryDropDown.pack()

    #Creating dropdown menu for stats analysis

    options = ('Average number of comments per category',
               'Average number of views per category',
               'Average number of likes and dislikes per category',
               'Measuring audience reaction per category',
               'Number of videos per category',
               'Measuring reaction by views and comments per category')

    def comReaction():
        data = pandas.read_csv("stats/comReaction.csv")
        vectorX = data['Video Reaction']
        vectorY = data['Video Comments']
        pyplot.scatter(vectorX, vectorY, alpha=0.5)
        pyplot.title("Like/Dislike Ratio to Comment Ratio")
        pyplot.show()

    def avgViews():
        data = pandas.read_csv("stats/avgViews.csv")
        vectorX = data['Category']
        vectorY = data['Average Views']
        pyplot.bar(x=vectorX, height=vectorY)
        pyplot.xticks(rotation=90)
        pyplot.title("Average Views per Category")
        pyplot.show()

    def avgComments():
        data = pandas.read_csv("stats/avgComments.csv")
        vectorX = data['Category']
        vectorY = data['Average Comments']
        pyplot.bar(x=vectorX, height=vectorY)
        pyplot.xticks(rotation=90)
        pyplot.title("Average Comments per Category")
        pyplot.show()

    def avgReaction():
        data = pandas.read_csv("stats/avgReaction.csv")
        vectorX = data['Category']
        vectorY = data[' Percent Liked']
        vectorZ = data[' Percent Disliked']
        r1 = np.arange(len(vectorX))

        p1 = pyplot.bar(x=vectorX, height=vectorY)
        pl = pyplot.bar(x=vectorX, height=vectorZ)
        pyplot.xticks(rotation=90)
        pyplot.title("Likes and Dislikes per Category")
        pyplot.show()

    def numVideos():
        data = pandas.read_csv("stats/numVideos.csv")
        vectorX = data['Category']
        vectorY = data['Number of Videos']
        vectorZ = data['Percent of Total']
        vectorZ *= 100
        pyplot.bar(x=vectorX, height=vectorY)
        pyplot.xticks(rotation=90)
        pyplot.title("Number of Videos per Category")
        pyplot.show()
        pyplot.pie(vectorZ, labels=vectorX)
        pyplot.axis('equal')
        pyplot.title("Percentage of Total Videos")
        pyplot.show()

    def viewReaction():
        data = pandas.read_csv("stats/viewReaction.csv")
        vectorX = data['Category']
        vectorY = data['Percent Viewers Who Like']
        vectorY *= 100
        pyplot.bar(x=vectorX, height=vectorY)
        pyplot.xticks(rotation=90)
        pyplot.title("Likes per View by Category")
        pyplot.show()

    lbl2 = ttk.Label(window,
                     text="Select an icon to display graphical analysis: ",
                     font=("Lato Bold", 15)).place(x=200, y=100)
    avgViewsImage = tk.PhotoImage(file='png/004-vision.png')
    avgLikeImage = tk.PhotoImage(file="png/001-like.png")
    avgCommentImage = tk.PhotoImage(file="png/003-list.png")
    numVideosImage = tk.PhotoImage(file="png/006-number.png")
    viewReactionImage = tk.PhotoImage(file="png/002-eye.png")
    comReactionImage = tk.PhotoImage(file="png/005-watching-tv.png")

    avgViewsButton = ttk.Button(window,
                                text='Average number of views per category',
                                command=avgViews,
                                image=avgViewsImage).place(x=25, y=200)
    avgLikeButton = ttk.Button(
        window,
        text='Average number of likes and dislikes per category',
        command=avgReaction,
        image=avgLikeImage).place(x=331, y=200)
    avgCommentButton = ttk.Button(
        window,
        text='Average number of comments per category',
        command=avgComments,
        image=avgCommentImage).place(x=617, y=200)
    numVideosButton = ttk.Button(window,
                                 text='Number of videos per category',
                                 command=numVideos,
                                 image=numVideosImage).place(x=25, y=400)
    viewReactionButton = ttk.Button(
        window,
        text='Comparing likes and dislikes to views per category',
        command=viewReaction,
        image=viewReactionImage).place(x=331, y=400)
    comReactionButton = ttk.Button(
        window,
        text='Compating likes and dislikes to comments per category',
        command=comReaction,
        image=comReactionImage).place(x=617, y=400)

    avgViewLabel = ttk.Label(window,
                             text="Average Views",
                             font=("Lato Bold", 15)).place(x=33, y=350)
    avgLikeLabel = ttk.Label(window,
                             text="Average Likes",
                             font=("Lato Bold", 15)).place(x=345, y=350)
    avgCommentLabel = ttk.Label(window,
                                text="Average Comments",
                                font=("Lato Bold", 15)).place(x=607, y=350)
    numViewLabel = ttk.Label(window,
                             text="Number of Videos",
                             font=("Lato Bold", 15)).place(x=23, y=550)
    viewReactionLabel2 = ttk.Label(window,
                                   text="vs Views",
                                   font=("Lato Bold", 15)).place(x=365, y=570)
    viewReactionLabel = ttk.Label(window,
                                  text="Likes and Dislikes",
                                  font=("Lato Bold", 15)).place(x=327, y=550)
    comReactionLabel2 = ttk.Label(window,
                                  text="vs Comments",
                                  font=("Lato Bold", 15)).place(x=637, y=570)
    comReactionLabel = ttk.Label(window,
                                 text="Likes and Dislikes",
                                 font=("Lato Bold", 15)).place(x=615, y=550)

    speedFile = pandas.read_csv("stats/performance.txt")
    quickTime = "Quick Sort Time: " + str(
        speedFile["Time"][0]) + " milliseconds"
    mergeTime = "Shell Sort Time: " + str(
        speedFile["Time"][1]) + " milliseconds"
    quickLabel = ttk.Label(window, text=quickTime,
                           font=("Lato Bold", 15)).place(x=33, y=630)
    mergeLabel = ttk.Label(window, text=mergeTime,
                           font=("Lato Bold", 15)).place(x=33, y=670)

    window.mainloop()
Beispiel #20
0
class MainGUI:
    def __init__(self):
        self.view_bool = False
        self.get_data(False)
        self.main_init()

    def main_init(self):
        self.gui_main()

    def main_refresh(self, all=False):
        self.get_data(all)
        if self.order_details == {}:
            self.listbox.delete(*self.listbox.get_children())
            self.listbox.insert("",
                                "end",
                                text="--",
                                values=("All orders cleared!", ))
        else:
            simple_details = []
            for id in self.order_ids:
                string = ""
                for item in self.order_details.get(id):
                    string += f"{item[1]} {item[0]}, "
                simple_details.append([
                    id, string[:40] +
                    "..." if len(string) > 40 else string[:len(string) - 2]
                ])

            self.listbox.delete(*self.listbox.get_children())
            for simple_detail in simple_details:
                self.listbox.insert("",
                                    "end",
                                    text=simple_detail[0],
                                    values=(simple_detail[1], ))

    def gui_main(self):
        # Root Window Init
        self.window = ThemedTk(theme="radiance")
        self.window.geometry("435x340")
        self.window.title("Restaurant Management System")
        self.window.configure(background="#F6F4F2")
        self.window.resizable(0, 0)

        self.view_var = BooleanVar()

        # Heading
        ttk.Label(self.window,
                  font=("default", 19, "bold"),
                  text="Kitchen Manager").grid(row=0,
                                               column=0,
                                               sticky="w",
                                               padx=15)
        ttk.Separator(self.window, orient="horizontal").grid(row=1,
                                                             columnspan=2,
                                                             sticky="ew")

        # Tree View
        self.listbox = ttk.Treeview(self.window)
        self.listbox["columns"] = ("Details")
        self.listbox.heading("#0", text="Order No")
        self.listbox.heading("#1", text="Details")
        self.listbox.column("#0", minwidth=0, width=100)
        self.listbox.column("#1", minwidth=0, width=300)
        self.listbox.bind('<Double-1>', self.selectItem)
        ttk.Style().configure("Treeview",
                              fieldbackground="#FEFEFE",
                              background="#FEFEFE")

        self.main_refresh(self.view_bool)
        self.listbox.grid(row=2, column=0, sticky="nse", padx=15, pady=10)

        self.view_all = ttk.Checkbutton(self.window,
                                        text="View all orders",
                                        variable=self.view_var,
                                        command=self.cb).grid(row=3,
                                                              column=0,
                                                              sticky="w",
                                                              padx=15)
        ttk.Button(self.window, text="Quit",
                   command=self.window.destroy).grid(row=3,
                                                     column=0,
                                                     sticky="e",
                                                     padx=15)
        self.window.mainloop()

    def cb(self):
        if self.view_var.get() == True:
            self.view_bool = True
        else:
            self.view_bool = False
        self.main_refresh(self.view_bool)

    def gui_details(self, id):
        # Open Details Window
        self.detail = ThemedTk(theme="radiance")
        self.detail.geometry("335x410")
        self.detail.title("Details")
        self.detail.configure(background="#F6F4F2")
        self.detail.resizable(0, 0)
        self.id = id

        # Heading
        ttk.Label(self.detail, font=("default", 19, "bold"),
                  text="Orders").grid(row=0, column=0, sticky="w", padx=15)
        ttk.Separator(self.detail, orient="horizontal").grid(row=1,
                                                             columnspan=2,
                                                             sticky="ew",
                                                             pady=(0, 5))

        # Create Default Lables
        ttk.Label(self.detail,
                  font=("default", 10, "bold"),
                  anchor="e",
                  width=18,
                  text="Order ID             : ").grid(row=2, column=0)
        ttk.Label(self.detail,
                  font=("default", 10, "bold"),
                  anchor="e",
                  width=18,
                  text="Customer Name : ").grid(row=3, column=0)

        # Create Buttons
        ttk.Button(self.detail,
                   text="Mark Done",
                   command=lambda: self.mark_done(self.id),
                   width=33).grid(row=5, column=0, columnspan=2)
        ttk.Button(
            self.detail,
            text="Previous",
            command=lambda: self.refresh(self.detail, "prev", self.id)).grid(
                row=6, column=0, sticky="w", padx=15)
        ttk.Button(
            self.detail,
            text="Next",
            command=lambda: self.refresh(self.detail, "next", self.id)).grid(
                row=6, column=1, sticky="e", padx=15)

        self.tree = ttk.Treeview(self.detail)
        self.tree["columns"] = ("Quantity")
        self.tree.heading("#0", text="Name")
        self.tree.heading("#1", text="Quantity")
        self.tree.column("#0", minwidth=0, width=230)
        self.tree.column("#1", minwidth=0, width=70)

    def mark_done(self, id):
        conn = sqlite3.connect("login_db.db")
        query = f"UPDATE orders SET delivered=1 WHERE order_no={id};"
        conn.execute(query)
        conn.commit()
        self.detail.destroy()
        self.main_refresh(self.view_bool)

    def selectItem(self, a):
        curItem = self.listbox.focus()
        id = self.listbox.item(curItem).get("text")
        if id == "--":
            pass
        else:
            self.gui_details(id)
            self.refresh(self.detail, None, id)

    def refresh(self, detail, fun, id):
        # Determine Function of Refresh else do nothing
        orders = self.order_ids
        if fun == "next":
            # When at end, loop back to start
            if orders.index(id) + 1 == len(orders):
                id = orders[0]
            else:
                id = orders[orders.index(id) + 1]

        elif fun == "prev":
            id = orders[orders.index(id) - 1]
        self.id = id

        # Create Changing Value Lables
        conn = sqlite3.connect("login_db.db")
        query = f"SELECT * FROM orders WHERE order_no={id}"
        items = conn.execute(query)
        converted_item = tuple(items)[0]
        ttk.Label(self.detail,
                  anchor="w",
                  width=18,
                  text=f"{converted_item[0]}").grid(row=2, column=1, padx=3)
        ttk.Label(self.detail,
                  anchor="w",
                  width=18,
                  text=f"{converted_item[1]}").grid(row=3, column=1, padx=3)

        self.tree.delete(*self.tree.get_children())
        for item in self.order_details.get(id):
            self.tree.insert("", "end", text=item[0], values=(item[1], ))

        for i in range(10):
            self.tree.insert("", "end", text="", values=("", ))

        self.tree.grid(row=4, column=0, columnspan=2, padx=15, pady=10)
        self.detail.mainloop()

    def get_data(self, all):
        self.order_details = km.db_retrieve(all)
        self.order_ids = km.order_ids(all)
Beispiel #21
0
def stats_screen():
    """in this screen the user can see the top 5 players in the game and watch his game statistics """
    cursor = User.db_connect()  # connecting to the database
    cursor.execute(
        "SELECT TOP(5) [Username], [NumberofWinnings] FROM [Users] WHERE [ID]!=0 ORDER BY [NumberofWinnings]"
        " DESC"
    )  # selects the top 5 players with the highest number of winnings
    rows = cursor.fetchall()  # gets the values that were selected
    stats_win = ThemedTk(
        theme="Smog")  # created the statistics window themed "smog"
    style = ttk.Style(stats_win)
    style.configure("Treeview.Heading",
                    font=("Calibri Bold", 14))  # styles the tables headings
    style.configure("Treeview",
                    font=("Calibri", 12))  # styles the tables fields

    ttk.Label(stats_win, text='Top Players', font=("Cooper black", 32), foreground='black', background='light blue')\
        .pack(pady=30)
    frame = ttk.Frame(stats_win)  # frames the top players table
    frame.pack(padx=20, pady=20)

    table = ttk.Treeview(frame, columns=(1, 2), show="headings",
                         height='5')  # creates the table

    table.column(1, anchor="c")
    table.column(2, anchor="c")
    table.pack(fill="both", expand=True)
    # centers the table columns and adds the table to the window

    table.heading(1, text="Player")
    table.heading(2, text="Number of Winnings")
    # writes the table headings

    for row in rows:
        table.insert(
            "", "end", values=list(row)
        )  # inserts the values that were given by the database to the table

    stats_win.geometry('540x540')
    stats_win.title("© Battleship by Shani Daniel ©")
    stats_win.configure(background='light blue')

    num_games = GameUI.logged_in_user.num_of_games  # gets the number of games the current user has played from the db
    num_wins = GameUI.logged_in_user.num_of_wins  # gets the number of games the current user has won from the db
    if num_games != 0:
        win_per = int(
            100 * (num_wins / num_games))  # calculates the winnings percentage
    else:  # if the user's number of games is zero, return 0
        win_per = 0
    ttk.Label(stats_win,
              text='Your Statistics:',
              font=("Cooper Black", 20),
              foreground='black',
              background='light blue').pack(pady=20)
    ttk.Label(stats_win,
              text='Number of games you played: %s' % num_games,
              font=("Calibri Bold", 16),
              foreground='black',
              background='light blue').pack(pady=5)
    ttk.Label(stats_win,
              text='Number of games you won: %s' % num_wins,
              font=("Calibri Bold", 16),
              foreground='black',
              background='light blue').pack(pady=5)
    ttk.Label(stats_win,
              text='Winning percentage: %s%%' % win_per,
              font=("Calibri Bold", 16),
              foreground='black',
              background='light blue').pack(pady=5)
    # creates the labels and adds the statistics we got for the current user

    stats_win.mainloop()
Beispiel #22
0
# create the main frame of the program and the sub frame
content = ttk.Frame(root)
subframe = ttk.Frame(content, borderwidth=5, relief='sunken')

# create a menu
menubar = Menu(root)
sub1 = Menu(root)

menubar.add_cascade(label="test1", menu=sub1)

sub1.add_command(label='a')
sub1.add_command(label='b')
sub1.add_command(label='c')

root.configure(menu=menubar)

# make the checks to go in the subframe
c1 = ttk.Checkbutton(subframe, text="One")
c2 = ttk.Checkbutton(subframe, text="Two")
c3 = ttk.Checkbutton(subframe, text="Three")
ok = ttk.Button(subframe, text="Click Me!", command=updateFeather)

# put the image in another box
imageframe = ttk.Labelframe(content, text="Feather:")
feather = PhotoImage(file="feather.png")
pic = ttk.Label(imageframe)
pic['image'] = feather

# make the text box to enter stuff into and name feather
name = StringVar()
Beispiel #23
0
class GUI:
    """
    The GUI class
    """
    def __init__(self):
        """
        Creates the main window and sets themes, style, and size
        """

        self._root = ThemedTk(theme="arc")
        self._root.title("MemeMoney")
        self._root.iconbitmap("iconimg\mememoney.ico")
        self._root.configure(bg="#f5f6f7")
        self._root.grid_columnconfigure(0, weight=1)
        self._root.geometry("800x600")

    def create_welcome_frame(self):
        """
        Creates the frame in which the title, subtitle, keyword request, and data will be displayed.
        """

        # sets font
        welcome_font = tk.font.Font(size=24, weight="bold")
        welcome_desc_font = tk.font.Font(size=12)
        sub_welcome_font = tk.font.Font(size=10)
        sub_welcome_font_bold = tk.font.Font(size=10,
                                             weight="bold",
                                             underline=True)

        # creates the frame w/ style, size, position
        welcome_frame = ttk.Frame(self._root)
        welcome_frame.grid(column=0, row=0, padx=20, pady=5, sticky="ew")
        welcome_frame.grid_columnconfigure(0, weight=1)

        # title and subtitle text
        welcome = ttk.Label(welcome_frame,
                            text="MemeMoney",
                            font=welcome_font,
                            foreground="#000000")
        welcome.grid(column=0)

        welcome_desc = ttk.Label(welcome_frame,
                                 text="Providing you with hyped stock data.",
                                 font=welcome_desc_font)
        welcome_desc.grid(column=0, pady=10)

        # instruction text
        instr = ttk.Label(welcome_frame,
                          text="Instructions:",
                          font=sub_welcome_font_bold,
                          wraplength=600,
                          anchor="w")
        instr.grid(column=0, sticky="w", padx=86)

        instr_desc = "Enter a stock symbol and the program will display a table with " \
                     "the number of Reddit and Twitter mentions, the stock's closing price, " \
                     "and the price differential from one day to the next, for the previous " \
                     "three days, excluding weekends."

        instructions = ttk.Label(welcome_frame,
                                 text=instr_desc,
                                 font=sub_welcome_font,
                                 wraplength=600)
        instructions.grid(column=0, pady=5)

        # gets user input for keyword search for stock symbol
        input_request = ttk.Label(
            welcome_frame,
            text="Please enter a stock symbol (letters only):",
            font=welcome_desc_font)
        input_request.grid(column=0, pady=10)

        # creates entry field for user to type in input
        stock_entry = ttk.Entry(welcome_frame,
                                width=30,
                                font=welcome_desc_font)
        stock_entry.grid(column=0, pady=10)

        def get_entry():
            """
            Inner function that retrieves the user entered term to provide keyword to search
            """

            attempted_keyword = stock_entry.get()

            # checks to see if term is valid, based on US stock exchanges
            # only letters and less than 5 letters
            if attempted_keyword.isalpha() and len(attempted_keyword) <= 5:
                keyword = "$" + str(attempted_keyword.upper())
                return keyword

            # else messagebox pops up and provides an error
            else:
                messagebox.showinfo("Invalid Entry",
                                    "You did not enter a valid search term.")
                stock_entry.delete(
                    0, "end")  # clears the entry box if invalid entry

        def get_data(platform):
            '''
            Inner function that gets the data from Reddit, Twitter, and Stock API's.

            Takes the platform as a parameter and returns a list of the data.
            '''

            keyword = get_entry()

            data_source = None

            # determines which function to call
            if platform == "twitter":
                data_source = twitter_scrape(keyword)
            if platform == "reddit":
                data_source = reddit_scrape(keyword)
            if platform == "stock_price":
                keyword = get_entry().strip("$")
                data_source = get_stock_prices(keyword)

            # if stock does not exist return nothing
            if data_source == "no such ticker":
                messagebox.showinfo("Invalid Entry", "Stock does not exist.")
                stock_entry.delete(
                    0, "end")  # clears the entry box if invalid entry
                return

            day_delta = datetime.timedelta(days=1)
            today = datetime.date.today()

            data_list = []

            # creates list of [dates, mentions]
            for things in range(7):
                the_day = today - (things * day_delta)

                if the_day.isoweekday() != 6 and the_day.isoweekday(
                ) != 7 and the_day != today:
                    the_date = the_day
                    mentions = data_source[the_date]

                    data_list.append([the_date, mentions])

            return data_list

        def create_table():
            """
            Creates display table for twitter and reddit mentions, and stock price
            """

            # calls functions to get data to display
            twitter_data = get_data("twitter")
            reddit_data = get_data("reddit")
            stock_price_data = get_data("stock_price")

            # if stock does not exist return nothing
            if stock_price_data is None:
                return

            # creates table frame
            table_frame = ttk.Frame(self._root)
            table_frame.grid(column=0, row=1, padx=20, pady=5, sticky="ew")
            table_frame.grid_columnconfigure(0, weight=1)

            # creates table foundation - tkinter treeview
            table = ttk.Treeview(table_frame)
            style = ttk.Style()
            style.configure('Treeview', rowheight=20)

            table['columns'] = ('Date', 'Close Price', 'Reddit Mentions',
                                'Twitter Mentions', 'Total Mentions',
                                'Price Diff from Prev Day',
                                'Mention Diff from Prev Day')
            table.column('#0', width=0, stretch=NO)
            table.column('Date', anchor=CENTER, width=75)
            table.column('Close Price', anchor=CENTER, width=75)

            table.column('Reddit Mentions', anchor=CENTER, width=100)
            table.column('Twitter Mentions', anchor=CENTER, width=100)
            table.column('Total Mentions', anchor=CENTER, width=100)
            table.column('Price Diff from Prev Day', anchor=CENTER, width=150)
            table.column('Mention Diff from Prev Day',
                         anchor=CENTER,
                         width=150)

            table.heading('#0', text='', anchor=W)
            table.heading('Date', text='Date', anchor=CENTER)
            table.heading('Close Price', text='Close Price', anchor=CENTER)

            table.heading('Reddit Mentions',
                          text='Reddit Mentions',
                          anchor=CENTER)
            table.heading('Twitter Mentions',
                          text='Twitter Mentions',
                          anchor=CENTER)
            table.heading('Total Mentions',
                          text='Total Mentions',
                          anchor=CENTER)
            table.heading('Price Diff from Prev Day',
                          text='Price Diff from Prev Day',
                          anchor=CENTER)
            table.heading('Mention Diff from Prev Day',
                          text='Mention Diff from Prev Day',
                          anchor=CENTER)

            # creates the table
            id = 0
            first_index = 0

            for items in range(3):

                # makes sure the dates are all the same one
                if twitter_data[first_index][0] == reddit_data[first_index][0] and \
                        twitter_data[first_index][0] == stock_price_data[first_index][0] and \
                        reddit_data[first_index][0] == stock_price_data[first_index][0]:

                    total = reddit_data[first_index][1] + twitter_data[
                        first_index][1]

                    # calculates mention and price differentials
                    try:
                        prev_total = reddit_data[
                            first_index + 1][1] + twitter_data[first_index +
                                                               1][1]
                        prev_price = float(stock_price_data[first_index +
                                                            1][1])

                        if first_index < 2:
                            mention_diff = total - prev_total
                            price_diff = round(
                                float(stock_price_data[first_index][1]) -
                                prev_price, 3)
                        else:
                            mention_diff = "N/A"
                            price_diff = "N/A"
                    except IndexError:
                        mention_diff = "N/A"
                        price_diff = "N/A"

                    # creates the data rows for the table
                    table.insert(parent='',
                                 index='end',
                                 iid=id,
                                 text='',
                                 values=(twitter_data[first_index][0],
                                         stock_price_data[first_index][1],
                                         reddit_data[first_index][1],
                                         twitter_data[first_index][1], total,
                                         price_diff, mention_diff))

                    id += 1
                    first_index += 1

            table.pack(pady=20)

        # button that when pushed retrieves the user entered keyword
        search_button = ttk.Button(welcome_frame,
                                   text="Get Results",
                                   command=lambda: [create_table()])
        search_button.grid(column=0, pady=5)

    def end(self):
        """
        Closes out the root for the GUI
        """

        return self._root.mainloop()
class GUI(object):
    """This handles the GUI for ESMB"""
    def __init__(self, debug_mode):
        logging.debug("\tBuilding GUI...")
        self.debugging = debug_mode

        #TODO: Look into changing this to not need the dictionary
        self.missionList = []
        self.missionNameToObjectDict = {}
        self.missionNames = []

        if self.debugging:
            self.missionList = [Mission("Debugging", default=True)]
            self.missionNameToObjectDict = {
                self.missionList[0].missionName: self.missionList[0]
            }
            self.missionNames.append(self.missionList[0].missionName)
        #end if

        # Build the application window
        self.gui = ThemedTk(theme="plastik")
        self.gui.title("ESMissionBuilder")
        self.gui.configure(bg="orange")

        # enable window resizing
        self.gui.columnconfigure(0, weight=1)
        self.gui.rowconfigure(0, weight=1)

        self.disabledEntryStyle = ttk.Style()
        self.disabledEntryStyle.configure('D.TEntry', background='#D3D3D3')
        self.disabledComboboxStyle = ttk.Style()
        self.disabledComboboxStyle.configure('D.TCombobox',
                                             background='#D3D3D3')

        self.ofWidth = None
        self.cfWidth = None
        self.mfWidth = None

        # Declare the frames
        self.optionFrame = None
        self.centerFrame = None
        self.missionFrame = None

        # declare optionFrame components
        self.missionComboBox = None
        self.activeMission = None

        # declare centerFrame components
        self.displayNameComponent = None
        self.descriptionComponent = None
        self.blockedComponent = None
        self.deadlineComponent = None
        self.cargoComponent = None
        self.passengersComponent = None
        self.illegalComponent = None
        self.stealthComponent = None
        self.invisibleComponent = None
        self.priorityLevelComponent = None
        self.whereShownComponent = None
        self.repeatComponent = None
        self.clearanceComponent = None
        self.infiltratingComponent = None
        self.waypointComponent = None
        self.stopoverComponent = None
        self.sourceComponent = None
        self.destinationComponent = None

        # Triggers
        self.triggersFrame = None
        self.activeTrigger = None

        # declare missionFrame components
        self.missionTextBox = None

        # Build the different parts of the main window
        #self.buildMenu(self.gui)
        self.build_main_view(self.gui)

        self.activeMission = None
        if self.debugging:
            self.activeMission = self.missionList[0]
        # Run the program
        self.gui.mainloop()

    #end init

    # This may be used later, after shortcuts are introduced
    '''
    def buildMenu(self, window):
        #TODO: IMPLEMENT THIS
        # creating a menu instance
        menu = Menu()
        window.config(menu=menu)

        # create the file object
        file = Menu(menu)
        edit = Menu(menu)

        # adds a command to the menu option, names it, and set the command to run
        file.add_command(label="New", command=lambda: newFile(self))
        file.add_command(label="Open", command=lambda: open_file(self))
        file.add_command(label="Save", command=lambda: save_file(self))
        file.add_command(label="Exit", command=exit)

        # added "File" to our menu
        menu.add_cascade(label="File", menu=file)

        # adds a command to the menu option, names it, and set the command to run
        edit.add_command(label="Undo", command=lambda: undoAction(self))

        # added "Edit" to our menu
        menu.add_cascade(label="Edit", menu=edit)
    #end buildMenu
    '''

    def build_main_view(self, window):
        """
        Instantiate the three major frames, and call methods to build the respective GUI areas

        :param window: The ThemedTK object that the rest of the GUI is built off of
        """
        option_frame = ttk.Frame(window)
        center_frame = ScrollingCenterFrame(self, window)
        mission_frame = ttk.Frame(window)

        self.optionFrame = option_frame
        self.centerFrame = center_frame
        self.missionFrame = mission_frame

        # set up each of the frames
        self.build_option_frame()
        self.build_center_frame()
        self.build_mission_frame()

        logging.debug("\tGUI built")

    #end build_main_view

    ### BUILDING FRAMES ###

    def build_option_frame(self):
        """Add widgets to the optionFrame"""
        logging.debug("\tBuilding optionFrame...")
        self.optionFrame.grid(row=0, column=0, sticky="ns")

        of_title = ttk.Label(self.optionFrame, text="Mission")
        of_title.pack()

        # declare the combobox here, fill with missionNames
        self.missionComboBox = ttk.Combobox(self.optionFrame,
                                            state="readonly",
                                            values=self.missionNames)
        self.missionComboBox.bind("<<ComboboxSelected>>",
                                  self.mission_selected)
        self.missionComboBox.pack()

        if self.debugging:
            self.missionComboBox.current(0)

        # add function buttons
        new_mission_button = ttk.Button(self.optionFrame,
                                        text="New Mission",
                                        command=lambda: new_mission(self))
        new_mission_button.pack(fill='x')

        save_mission_file_button = ttk.Button(self.optionFrame,
                                              text="Save Mission File",
                                              command=lambda: save_file(self))
        save_mission_file_button.pack(fill='x')

        open_mission_file_button = ttk.Button(self.optionFrame,
                                              text="Open Mission File",
                                              command=lambda: open_file(self))
        open_mission_file_button.pack(fill='x')

        compile_mission_file_button = ttk.Button(
            self.optionFrame,
            text="Compile Mission",
            command=lambda: compile_mission(self))
        compile_mission_file_button.pack(fill='x')

        help_button = ttk.Button(self.optionFrame,
                                 text="Help",
                                 command=help_user)
        help_button.pack(fill='x')

        #TODO: Add functionality to change missionName and delete mission. Also, update button grouping to reflect

    #end build_option_frame

    def build_center_frame(self):
        """Add widgets to the centerFrame"""
        logging.debug("\tBuilding centerFrame...")

        self.centerFrame.grid(row=0, column=1, sticky="ns")

        cf = self.centerFrame.inner

        # Display name
        self.displayNameComponent = build_component_frame(
            cf, "Mission Display Name", 1, 0, ["<text>"])
        self.displayNameComponent.grid(row=0, column=0, sticky="ew")

        # Description
        self.descriptionComponent = build_component_frame(
            cf, "Description", 1, 0, ["<description>"])
        self.descriptionComponent.grid(row=1, column=0, sticky="ew")

        # isBlocked
        self.blockedComponent = build_component_frame(cf, "Blocked", 1, 0,
                                                      ["<message>"])
        self.blockedComponent.grid(row=2, column=0, sticky="ew")

        # Deadline
        self.deadlineComponent = build_component_frame(
            cf, "Deadline", 0, 2, ["[<days#>]", "[<multiplier#>]"])
        self.deadlineComponent.grid(row=3, column=0, sticky="ew")

        # Cargo
        self.cargoComponent = build_component_frame(cf, "Cargo", 2, 2, [
            "(random | <name>)", "<number#>", "[<number#>]", "[<probability#>]"
        ])
        self.cargoComponent.grid(row=4, column=0, sticky="ew")

        # Passengers
        self.passengersComponent = build_component_frame(
            cf, "Passengers", 1, 2,
            ["<number#>", "[<number#>]", "[<probability#>]"])
        self.passengersComponent.grid(row=5, column=0, sticky="ew")

        # Illegal
        self.illegalComponent = build_component_frame(
            cf, "Illegal", 1, 1, ["<fine#>", "[<message>]"])
        self.illegalComponent.grid(row=6, column=0, sticky="ew")

        # Stealth
        self.stealthComponent = build_component_frame(cf, "Stealth", 0, 0, [])
        self.stealthComponent.grid(row=7, column=0, sticky="ew")

        # Invisible
        self.invisibleComponent = build_component_frame(
            cf, "Invisible", 0, 0, [])
        self.invisibleComponent.grid(row=8, column=0, sticky="ew")

        # priorityLevel
        self.priorityLevelComponent = build_combo_component_frame(
            cf, "Priority Level", ["Priority", "Minor"])
        self.priorityLevelComponent.grid(row=9, column=0, sticky="ew")

        # whereShown
        self.whereShownComponent = build_combo_component_frame(
            cf, "Where Shown", ["Job", "Landing", "Assisting", "Boarding"])
        self.whereShownComponent.grid(row=10, column=0, sticky="ew")

        # Repeat
        self.repeatComponent = build_component_frame(cf, "Repeat", 0, 1,
                                                     ["[<times#>]"])
        self.repeatComponent.grid(row=11, column=0, sticky="ew")

        # Clearance
        self.clearanceComponent = build_component_frame(
            cf, "Clearance", 0, 1, ["[<message>]"])
        self.clearanceComponent.grid(row=12, column=0, sticky="ew")

        # Infiltrating
        self.infiltratingComponent = build_component_frame(
            cf, "Infiltrating", 0, 0, [])
        self.infiltratingComponent.grid(row=13, column=0, sticky="ew")

        # Waypoint
        self.waypointComponent = build_component_frame(cf, "Waypoint", 1, 0,
                                                       ["[<system>]"])
        self.waypointComponent.grid(row=14, column=0, sticky="ew")

        # Stopover
        self.stopoverComponent = build_component_frame(cf, "Stopover", 1, 0,
                                                       ["[<planet>]"])
        self.stopoverComponent.grid(row=15, column=0, sticky="ew")

        # Source
        self.sourceComponent = build_component_frame(cf, "Source", 1, 0,
                                                     ["[<planet>]"])
        self.sourceComponent.grid(row=16, column=0, sticky="ew")

        # Destination
        self.destinationComponent = build_component_frame(
            cf, "Destination", 1, 0, ["[<planet>]"])
        self.destinationComponent.grid(row=17, column=0, sticky="ew")

        # triggers
        self.triggersFrame = AggregatedTriggerFrame(self, cf)
        self.triggersFrame.grid(row=18, column=0, sticky="ew")

        # add a blank label to pad the bottom of the frame
        bl1 = ttk.Label(cf, textvariable=" ")
        bl1.grid(row=19, column=0, sticky="ew")

    #end build_center_frame

    def build_mission_frame(self):
        """Add widgets to the missionFrame"""
        logging.debug("\tBuilding missionFrame...")

        #Display a default mission template on launch
        self.missionFrame.grid(row=0, column=2, sticky="nsew")
        mf_title = ttk.Label(self.missionFrame, text="Mission Text")
        mf_title.pack()

        # Populate the Text with a mission template
        self.missionTextBox = Text(self.missionFrame,
                                   wrap=WORD,
                                   height=50,
                                   width=100)
        self.missionTextBox.pack(expand=1, fill='both')
        welcome_message = "\n"
        welcome_message += "\t\t\tWelcome to Endless Sky Mission Builder!\n"
        welcome_message += "\n\t - Click \"New Mission\" to get started\n"
        welcome_message += "\n\t - Click \"Save Mission File\" to save all the missions to a text file\n"
        welcome_message += "\n\t - Click \"Open Mission File\" to open a mission file for editing\n"
        welcome_message += "\n\t - Click \"Compile Mission\" to save save the current mission\n"
        welcome_message += "\n\t - Click \"Help\" to be directed to the Mission Creation wiki\n"
        self.missionTextBox.insert(END, welcome_message)
        self.missionTextBox.config(state=DISABLED)

    #end build_mission_frame

    ### UPDATING FRAMES ###

    def update_option_frame(self):
        """Update optionFrame to use the most recent data"""
        logging.debug("Updating optionFrame...")

        ### Start updating combobox
        ml = self.missionList
        self.missionNames = []
        for m in ml:
            self.missionNames.append(m.missionName)
        logging.debug("\tNew mission options: %s" % str(self.missionNames))

        # update options in the combobox
        self.missionComboBox['values'] = self.missionNames
        self.missionComboBox.current(0)
        ### Finish updating combobox

        # update the other two frames to reflect the current mission
        self.update_center_frame()
        self.update_mission_frame()

    #end update_option_frame

    def update_center_frame(self):
        """Update missionFrame to use the most recent data"""
        logging.debug("Updating centerFrame...")

        components = self.activeMission.components

        # missionDisplayName
        self.displayNameComponent.reset()
        if components.missionDisplayName is not None:
            self.displayNameComponent.set(0, 0, components.missionDisplayName)

        # description
        self.descriptionComponent.reset()
        if components.description is not None:
            description = components.description
            self.descriptionComponent.set(0, 0, description)
        #end if

        # blocked
        self.blockedComponent.reset()
        if components.blocked is not None:
            self.blockedComponent.set(0, 0, components.blocked)

        # deadline
        self.deadlineComponent.reset()
        if components.deadline.isDeadline is True:
            self.deadlineComponent.set(0, None, "isDeadlineCheckbutton")
            if components.deadline.deadline[0] is not None:
                self.deadlineComponent.set(1, 0,
                                           components.deadline.deadline[0])
                if components.deadline.deadline[1] is not None:
                    self.deadlineComponent.set(2, 1,
                                               components.deadline.deadline[1])
            #end if
        #end if

        # cargo
        self.cargoComponent.reset()
        if components.cargo.isCargo is True:
            self.cargoComponent.set(0, 0, components.cargo.cargo[0])
            self.cargoComponent.set(0, 1, components.cargo.cargo[1])
            if components.cargo.cargo[2] is not None:
                self.cargoComponent.set(1, 2, components.cargo.cargo[2])
                if components.cargo.cargo[2] is not None:
                    self.cargoComponent.set(2, 3, components.cargo.cargo[3])
            #end if
        #end if

        # passengers
        self.passengersComponent.reset()
        if components.passengers.isPassengers is True:
            self.passengersComponent.set(0, 0,
                                         components.passengers.passengers[0])
            if components.passengers.passengers[1] is not None:
                self.passengersComponent.set(
                    1, 1, components.passengers.passengers[1])
                if components.passengers.passengers[2] is not None:
                    self.passengersComponent.set(
                        2, 2, components.passengers.passengers[2])
            #end if
        #end if

        # illegal
        self.illegalComponent.reset()
        if components.illegal.isIllegal is True:
            self.illegalComponent.set(0, 0, components.illegal.illegal[0])
            if components.illegal.illegal[1] is not None:
                self.illegalComponent.set(1, 1, components.illegal.illegal[1])
            # end if
        # end if

        # stealth
        self.stealthComponent.reset()
        if components.isStealth is True:
            self.stealthComponent.set(0, None, "stealthCheckbutton")

        # invisible
        self.invisibleComponent.reset()
        if components.isInvisible is True:
            self.invisibleComponent.set(0, None, "isInvisibleCheckbutton")

        # priorityLevel
        self.priorityLevelComponent.reset()
        if components.priorityLevel is not None:
            self.priorityLevelComponent.set(components.priorityLevel)

        # whereShown
        self.whereShownComponent.reset()
        if components.whereShown is not None:
            self.whereShownComponent.set(components.whereShown)

        # repeat
        self.repeatComponent.reset()
        if components.isRepeat is True:
            self.repeatComponent.set(0, None, "isRepeatCheckbutton")
            if components.repeat is not None:
                self.repeatComponent.set(1, 0, components.repeat)
        #end if

        # clearance
        self.clearanceComponent.reset()
        if components.clearance.isClearance is True:
            self.clearanceComponent.set(0, None, "isClearanceCheckbutton")
            if components.clearance.clearance is not None:
                self.clearanceComponent.set(1, 0,
                                            components.clearance.clearance)
        #end if

        # infiltrating
        self.infiltratingComponent.reset()
        if components.isInfiltrating is True:
            self.infiltratingComponent.set(0, None,
                                           "isInfiltratingCheckbutton")

        # waypoint
        self.waypointComponent.reset()
        if components.waypoint is not None:
            self.waypointComponent.set(0, 0, components.waypoint)

        # stopover
        self.stopoverComponent.reset()
        if components.stopover.isStopover is True:
            self.stopoverComponent.set(0, 0, components.stopover.stopover)

        # source
        self.sourceComponent.reset()
        if components.source.isSource is True:
            self.sourceComponent.set(0, 0, components.source.source)

        # destination
        self.destinationComponent.reset()
        if components.destination.isDestination is True:
            self.destinationComponent.set(0, 0,
                                          components.destination.destination)

        # Clear out the AggregatedTriggerFrame
        self.triggersFrame.grid_forget()
        self.triggersFrame = AggregatedTriggerFrame(self,
                                                    self.centerFrame.inner)
        self.triggersFrame.grid(row=18, column=0, sticky="ew")

        # Triggers
        if components.triggerList:
            logging.debug("\tTriggers found")
            for trigger in components.triggerList:
                self.triggersFrame.populate_trigger(trigger)

    #end update_center_frame

    def update_mission_frame(self):
        """Update missionFrame to use the most recent data"""
        logging.debug("Updating missionFrame...")

        self.missionTextBox.forget()
        self.missionTextBox = Text(self.missionFrame,
                                   height=50,
                                   width=100,
                                   wrap=WORD)
        self.missionTextBox.pack()
        self.missionTextBox.insert(
            END, self.activeMission.print_mission_lines_to_text())
        self.missionTextBox.config(state=DISABLED)

    #end update_mission_frame

    ### MISC METHODS ###

    def mission_selected(self, event=None):
        """Set activeMission to the combobox option selected by the user"""
        selected_mission_name = self.missionComboBox.get()
        logging.debug("Opening mission \"%s\"" % selected_mission_name)
        self.activeMission = self.missionNameToObjectDict.get(
            selected_mission_name)
        self.update_center_frame()
        self.update_mission_frame()
Beispiel #25
0
class Application:
    """窗口主类"""
    def __init__(self):
        self.data = None  # UI界面数据,可以将这部分完全转移至Main
        self.thread = False  # 表示当前是否有线程在运行
        self.setroot()
        self.setui(self.root)

    # ——————————————————————————————————————————————————————————
    # 初始化函数
    def setroot(self):
        """创建主窗口"""
        self.root = ThemedTk(theme="arc", toplevel=True, themebg=True)
        self.root.update()
        x_max, y_max = self.root.maxsize()
        x, y = int(x_max / 2 - 300), int(y_max / 2 - 200)
        self.root.geometry("600x400+%s+%s" % (x, y))  # 居中显示
        self.root.title("Spyder")
        self.root.resizable(0, 0)  # 锁定长宽大小

        # 创建变量
        self.key = tk.StringVar()
        self.website = tk.StringVar()

    def setui(self, master):
        """创建窗口组件"""
        # ViewBox
        self.ViewBox = tk.LabelFrame(master,
                                     text="Result",
                                     width=420,
                                     height=360)
        self.ViewBox.place(x=20, y=20)
        self.view = ttk.Treeview(self.ViewBox,
                                 show='headings',
                                 column=('num', 'ct', 'zy', 'lj', 'rd'))
        self.view.place(x=0, y=0, width=400, relheight=1)

        # InfoBox
        self.InfoBox = tk.LabelFrame(master,
                                     text=u"Option",
                                     width=120,
                                     height=360)
        self.InfoBox.place(x=460, y=20)
        tk.Label(self.InfoBox, text="Website").place(x=10, y=20)
        self.Web = ttk.Combobox(
            self.InfoBox,
            textvariable=self.website,
            values=["WeiboSearch", "ZhihuSearch", "ZhihuBank", "BaiduNews"],
            width=11,
            state="readonly")
        self.Web.current(0)
        self.Web.place(x=10, y=50)
        tk.Label(self.InfoBox, text="Key").place(x=10, y=90)
        self.Key = tk.Entry(self.InfoBox,
                            highlightcolor="sky blue",
                            highlightthickness=1,
                            textvariable=self.key,
                            width=13)
        self.Key.place(x=10, y=120)
        self.Confirm = tk.Button(self.InfoBox,
                                 text="Update",
                                 width=9,
                                 height=1)
        self.Confirm.place(x=20, y=160)
        self.Clear = tk.Button(self.InfoBox,
                               text="Clear",
                               width=9,
                               command=self.clrview)
        self.Clear.place(x=20, y=200)
        self.Save = tk.Button(self.InfoBox, text="Save", width=9)
        self.Save.place(x=20, y=240)

        # TreeView
        self.view.heading(column="num", text="Num")
        self.view.heading(column="ct", text="Entry")
        self.view.heading(column="zy", text="Excerpt")
        self.view.heading(column="lj", text="Link")
        self.view.heading(column="rd", text="Hot")
        self.view.column("num", width=30, anchor=tk.W)
        self.view.column("ct", width=100, anchor=tk.W)
        self.view.column("zy", width=110, anchor=tk.W)
        self.view.column("lj", width=80, anchor=tk.W)
        self.view.column("rd", width=80, anchor=tk.W)

        # 信号槽(暂无必要)

    # ——————————————————————————————————————————————————————————
    # 功能函数

    def setdata(self, data):
        """设置当前数据表数据"""
        std_data = self.standardlize(data)
        self.data = std_data

    def clrdata(self):
        """清除数据"""
        self.data = None

    def standardlize(self, data):
        """将不同格式的数据统一格式"""
        table = pd.DataFrame({
            "序号": [],
            "词条": [],
            "摘要": [],
            "链接": [],
            "热度": []
        })
        table = table.merge(data, how="outer")
        table['序号'] = data.index.values + 1
        table.fillna("", inplace=True)
        table = table[["序号", "词条", "摘要", "链接", "热度"]]
        return table.values.tolist()

    def viewsort(col, reverse):
        """表格排序,暂未绑定"""
        l = [(self.view.set(k, col), k) for k in self.view.get_children('')]
        l.sort(reverse=reverse)

        # rearrange items in sorted positions
        for index, (val, k) in enumerate(l):
            self.view.move(k, '', index)

        # reverse sort next time
        self.view.heading(
            col,
            text=col,
            command=lambda _col=col: treeview_sort_column(_col, not reverse))

    def savefile(self):
        """选择保存文件的路径"""
        filename = filedialog.asksaveasfilename(initialdir=".",
                                                initialfile="Data.xlsx",
                                                defaultextension="xlsx",
                                                filetypes=[("数据表", ".xls"),
                                                           ("数据表", ".xlsx")])
        return filename

    def clrview(self):
        """清除数据表数据"""
        items = self.view.get_children()
        for item in items:
            self.view.delete(item)

    def update(self, func):
        """通过线程运行命令"""
        if not self.thread:
            self.thread = True
            t = threading.Thread(target=func)
            t.start()
        else:
            t = threading.Thread(target=lambda: msg.showinfo(
                title="Info", message="程序正在运行中,请稍后再试!"))

    def updatedata(self):
        """刷新数据表数据"""
        if self.data == None:
            msg.showwarning(title="Warning",
                            message="None Data!Please fetch first!")
        else:
            self.clrview()
            for d in self.data:
                self.view.insert('', tk.END, values=d)  # 添加数据到末尾
            self.thread = False

    def themechose(self, theme="arc"):
        """更换主题,包括'arc','adapta','aqua','breeze'"""
        self.root.configure(theme=theme)

    def mainloop(self):
        """窗口挂起"""
        self.root.mainloop()