Esempio n. 1
0
def main():
    global LARGE_FONT, realpositive, port
    LARGE_FONT = ("Verdana", 12)
    x, y = 648, 520
    #root = tk.Tk()
    root = ThemedTk(theme="adapta")
    realpositive = tk.IntVar()
    port = tk.StringVar()
    global startpage, synthesis, darlington, pageThree, transferFunction
    startpage = tk.Frame(root)
    synthesis = tk.Frame(root)
    darlington = tk.Frame(root)
    pageThree = tk.Frame(root)
    transferFunction = tk.Frame(root)
    for frame in (startpage, synthesis, darlington, pageThree,
                  transferFunction):
        frame.grid(row=0, column=0, sticky='news')
    StartPage()
    Synthesisframe()
    Darlingtonframe()
    PageThreeframe()
    TransferFunctionframe()
    root.update_idletasks()  # Update "requested size" from geometry manager
    a, a0 = str(x), x / 2
    b, b0 = str(y), y / 2
    root.geometry("+%d+%d" % ((root.winfo_screenwidth() / 2) - a0,
                              (root.winfo_screenheight() / 3) - b0))
    root.deiconify()
    root.resizable(width=False, height=False)
    menubar = tk.Menu(root)
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Tutorial", command=toturial)
    filemenu.add_command(label="About", command=About)
    filemenu.add_command(label="Exit", command=root.destroy)
    menubar.add_cascade(label="MENU", menu=filemenu)
    root.config(menu=menubar)
    root.title("LC & RC Filter")
    root.bind('<Escape>', lambda e: root.destroy())
    root.protocol("WM_DELETE_WINDOW", root.iconify)
    raise_frame(startpage)
    root.mainloop()
Esempio n. 2
0
class MainteGuiMain:
    def __init__(self):
        print("MainteGui Constructor")

    def thread(self, input_queue, output_queue):
        self.input_queue = input_queue
        self.output_queue = output_queue
        self.root = ThemedTk(theme='radiance')
        app = MainteGui(master=self.root,
                        num_arm=NUM_ARM,
                        num_joint_per_arm=NUM_JOINT,
                        input_queue=self.input_queue,
                        output_queue=self.output_queue)
        self.root.protocol("WM_DELETE_WINDOW", self.quit)
        self.root.mainloop()

    def quit(self):
        print("Call destroy")
        msg = MsgCmd(MsgType.MSG_ALL_TERMINATE)
        self.output_queue.put(msg)
        self.root.destroy()
Esempio n. 3
0
def change_theme():
    chosen_theme = theme_choice.get()
    color_tuple = color_dict.get(chosen_theme)
    fg_color, bg_color = color_tuple[0], color_tuple[1]
    text_editor.config(background=bg_color, fg=fg_color) 


count = 0
for i in color_dict:
    color_theme.add_radiobutton(label = i, image =color_icons[count], variable = theme_choice,compound = tk.LEFT,command = change_theme)
    count += 1

main_application.config(menu = main_menu)

main_application.protocol('WM_DELETE_WINDOW',exit_func)
#shortcuts
main_application.bind("<Control-n>",new_file)
main_application.bind("<Control-o>",open_file)
main_application.bind("<Control-s>",save_file)
main_application.bind("<Control-Alt-s>",save_as)
main_application.bind("<Control-q>",exit_func)
main_application.bind("<Control-f>",find_function)
main_application.bind("<Control-b>",change_bold)
main_application.bind("<Control-i>",change_italic)
main_application.bind("<Control-u>",underline_text)
main_application.bind("<Control-Alt-x>",clear_all)
main_application.bind("<Control-z>",undo)
main_application.bind("<Control-y>",redo)
main_application.mainloop()
Esempio n. 4
0
import os
import tkinter.messagebox


def x():
    question = messagebox.askquestion('Question', 'Are You Sure To Quit?')
    if question == 'yes':
        import sys
        sys.exit()
    else:
        None


r = ThemedTk(themebg=True)
r.set_theme('arc')
r.protocol('WM_DELETE_WINDOW', x)
saved_file_path = ttk.Label(r)
saved_file_path.place(x=1, y=150)
convert_button = ttk.Button(r, text='Convert To Audio', state=DISABLED)
convert_button.place(x=175 + 2, y=100)
open_file_path = ttk.Label(r)
open_file_path.place(x=1, y=175)


def video_to_audio():
    global asking_file_to_save
    global star__  # push this one!
    messagebox.showwarning(
        'Warning!',
        ' Remember Put In Small Letters File Extension At The End Of The File Name'
    )  # image converter,insertation of a mp3 to a mp4 # advance sppech recognization
Esempio n. 5
0
pauseBtn = ttk.Button(middleFrame, image=pause_photo, command=pause_music)
pauseBtn.grid(row=0, column=1, padx=20)

stopBtn = ttk.Button(middleFrame, image=stop_photo, command=stop_music)
stopBtn.grid(row=0, column=2, padx=20)

# Bottom Frame for rewind volume,mute etc

bottomFrame = Frame(rightFrame)
bottomFrame.pack()

rewindBtn = ttk.Button(bottomFrame, image=rewind_photo, command=rewind_music)
rewindBtn.grid(row=0, column=0, pady=20)

volumeBtn = ttk.Button(bottomFrame, image=volume_photo, command=mute_music)
volumeBtn.grid(row=0, column=1, pady=20, padx=10)

scale = ttk.Scale(bottomFrame, from_=0, to=100, orient=HORIZONTAL, command=set_vol)
scale.set(70)  # default value
mixer.music.set_volume(0.7)
scale.grid(row=0, column=2, pady=20, padx=30)


def on_closing():
    stop_music()         #stopping music first then closing the window
    root.destroy()


root.protocol("WM_DELETE_WINDOW", on_closing)  # overriding default functionality of close
root.mainloop()
Esempio n. 6
0
def render():
    root = ThemedTk(theme='arc')
    app = GUI(root)
    root.protocol('WM_DELETE_WINDOW', app.close)
    root.mainloop()
media_menu.add_command(label = 'Exit', image = exit_icon, compound = LEFT, accelerator = 'Ctrl + Q', command = exit_command)

audio_menu.add_command(label = 'Increase Volume', image = increase_volume_icon, compound = LEFT, command = increase_volume)
audio_menu.add_command(label = 'Decrease Volume', image = decrease_volume_icon, compound = LEFT, command = decrease_volume)
audio_menu.add_command(label = 'Mute', image = mute_icon, compound = LEFT, command = mute)

view_menu.add_checkbutton(label = 'Playlist', onvalue = True, offvalue = False, variable = playlist_var, image = playlist_icon, compound = LEFT, command = playlist)
view_menu.add_separator()
view_menu.add_checkbutton(label ='Status Bar', onvalue = True, offvalue = False, variable = status_bar_var, compound = LEFT, command = hide_status_bar)

help_menu.add_command(label ='About Us', image = about_us_icon, compound = LEFT, command = aboutus_func)

main_application.config(menu = main_menu)

#----------------------------- End Menu Bar Code -----------------------------

def on_closing():
    global stop_var
    stop_var = False
    stopmusic()
    main_application.destroy()

main_application.protocol("WM_DELETE_WINDOW", on_closing)

#Bind Shortcut keys
main_application.bind("<Control-o>", browse_file)
main_application.bind("<Control-Shift-o>", multiple_files)
main_application.bind("<Control-f>", open_folder)
main_application.bind("<Control-q>", exit_command)

main_application.mainloop()
Esempio n. 8
0
def main():
    global message
    message = ""
    if "alarm.mp3" not in os.listdir("."):
        print("alarm.mp3 not found please check it out")
        time.sleep(5)
        raise Exception("alarm.mp3 not found please check it out")
    LARGE_FONT = ("Verdana", 12)
    root = ThemedTk(theme="adapta")
    root.title('HOTSPOT')
    root.bind('<Escape>', lambda e: root.destroy())
    root.protocol("WM_DELETE_WINDOW", root.iconify)
    root.update_idletasks()
    try:
        root.iconbitmap('icon.ico')
    except:
        pass
    home = ttk.Frame(root)
    home.grid(row=0, column=0, sticky='news')
    home.rowconfigure([0], weight=1)
    home.columnconfigure([0, 1], weight=1)
    server = ttk.Frame(root)
    server.grid(row=0, column=0, sticky='news')
    server.rowconfigure([0, 1, 2, 3], weight=1)
    server.columnconfigure([0], weight=1)
    status5 = ttk.Label(server, text="", font=LARGE_FONT, anchor=tk.CENTER)
    status5.grid(row=2, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    status7 = ttk.Label(server, text="", font=LARGE_FONT, anchor=tk.CENTER)
    status7.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    progress2 = ttk.Progressbar(server,
                                orient="horizontal",
                                mode="determinate",
                                cursor='spider')
    progress2.grid(row=3, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    progress2["maximum"] = 100
    button3 = ttk.Button(server,
                         text="Start",
                         width=15,
                         command=lambda: Thread(target=lambda: makeserver(
                             status7, progress2, server)).start())
    button3.grid(row=1, column=2, sticky=tk.N + tk.S + tk.E + tk.W)
    button3 = ttk.Button(home,
                         text="Recieve",
                         width=15,
                         command=lambda: raise_frame(server, "R", status5))
    button3.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    button4 = ttk.Button(home,
                         text="Send",
                         width=15,
                         command=lambda: raise_frame(page, "S", status6))
    button4.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W)

    page = ttk.Frame(root)
    page.grid(row=0, column=0, sticky='news')
    page.rowconfigure([0, 1, 2], weight=1)
    page.columnconfigure([0], weight=1)
    progress = ttk.Progressbar(page,
                               orient="horizontal",
                               mode="determinate",
                               cursor='spider')
    progress.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    progress["maximum"] = 100
    status6 = ttk.Label(page, text="", font=LARGE_FONT, anchor=tk.CENTER)
    status6.grid(row=2, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    startpage = ttk.Frame(page)
    startpage.grid(row=0, column=0, sticky='news')
    startpage.rowconfigure([0, 1, 2], weight=1)
    startpage.columnconfigure([0, 1, 2], weight=1)
    HOST = ttk.Entry(startpage)
    HOST.grid(row=1, column=1, sticky=tk.N + tk.S + tk.E + tk.W)
    PORT = ttk.Entry(startpage)
    PORT.grid(row=2, column=1, sticky=tk.N + tk.S + tk.E + tk.W)
    PORT.insert(tk.END, '65432')
    button = ttk.Button(
        startpage,
        text="send",
        width=15,
        command=lambda: Thread(target=lambda: connect(page, progress, HOST.get(
        ), int(PORT.get()))).start())
    button.grid(row=2, column=2, sticky=tk.N + tk.S + tk.E + tk.W)
    status = ttk.Label(startpage,
                       text="click for connecting and sending",
                       font=LARGE_FONT,
                       anchor=tk.CENTER)
    status.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    status1 = ttk.Label(startpage, text="", font=LARGE_FONT, anchor=tk.CENTER)
    status1.grid(row=0, column=2, sticky=tk.N + tk.S + tk.E + tk.W)
    status2 = ttk.Label(startpage, text="", font=LARGE_FONT, anchor=tk.CENTER)
    status2.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W)
    status3 = ttk.Label(startpage,
                        text="IP ",
                        font=LARGE_FONT,
                        anchor=tk.CENTER)
    status3.grid(row=1, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    status4 = ttk.Label(startpage,
                        text="PORT",
                        font=LARGE_FONT,
                        anchor=tk.CENTER)
    status4.grid(row=2, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
    button2 = ttk.Button(startpage,
                         text="open file",
                         width=15,
                         command=lambda: Open(progress))
    button2.grid(row=1, column=2, sticky=tk.N + tk.S + tk.E + tk.W)
    center(root)
    menubar = tk.Menu(root)
    filemenu = tk.Menu(menubar, tearoff=False)
    filemenu.add_command(label="Home", command=lambda: raise_frame(home))
    filemenu.add_command(label="Exit", command=root.destroy)
    menubar.add_cascade(label="MENU", menu=filemenu)
    root.config(menu=menubar)
    root.deiconify()
    root.resizable(width=False, height=False)
    raise_frame(home)
    root.mainloop()
Esempio n. 9
0
    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")
    PInfo2_Label = Label(MainWindow, text="Made by RealistikDash", bg=Config.BG_Colour, fg = 'white', font = "none 13")
    PInfo_Label.grid(row=2, column=0, sticky=W)
    PInfo2_Label.grid(row=3, column=0, sticky=W)

    #Username Label
    Username_Label = Label(MainWindow, text="Email:", bg = Config.BG_Colour, fg = "white", font = "none 12")
Esempio n. 10
0
Entry(login_info, textvariable=user, width=35).pack(padx=4, pady=4, side=LEFT)

Label(login_info, text="Iposim password:"******"*").pack(padx=4,
                                                                  pady=4,
                                                                  side=LEFT)

sim_button = Button(login_info,
                    text="Simulate",
                    width=20,
                    command=threaded_button_simulation,
                    style="Bold.TButton")
sim_button.pack(fill="both", padx=4, pady=4, side=LEFT)

Button(input_select, text="Select input file", command=browse_data,
       width=20).pack(padx=4, pady=4, side=LEFT)
Entry(input_select, textvariable=filename, state="disabled",
      width=101).pack(padx=4, pady=4, side=LEFT)

Button(output_select,
       text="Select output folder",
       command=get_output_dir,
       width=20).pack(padx=4, pady=4, side=LEFT)
Entry(output_select, textvariable=output_dir, state="disabled",
      width=101).pack(padx=4, pady=4, side=LEFT)

ConsoleUi(console)

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
Esempio n. 11
0
# 'scidmint', 'scidgreen', 'default', 'scidpink',
# 'arc', 'scidgrey', 'scidpurple', 'clam', 'smog'
# 'kroc', 'black', 'clearlooks'
# 'radiance', 'blue' : https://wiki.tcl-lang.org/page/List+of+ttk+Themes
root = ThemedTk(theme="default")

# change working directory to path for this file
p = os.path.realpath(__file__)
os.chdir(os.path.dirname(p))

# UNCOMMENT THE FOLLOWING TO SAVE GEOMETRY INFO
if os.path.isfile("winfo"):
    with open("winfo") as f:
        lcoor = f.read()
    root.geometry(lcoor.strip())
else:
    root.geometry("350x200")  # WxH+left+top

root.title("simpledialog demo")
root.protocol("WM_DELETE_WINDOW",
              save_location)  # UNCOMMENT TO SAVE GEOMETRY INFO
# Sizegrip(root).place(rely=1.0, relx=1.0, x=0, y=0, anchor=SE)
# root.resizable(w, h) # no resize & removes maximize button
# root.minsize(w, h)  # width, height
# root.maxsize(w, h)
# root.overrideredirect(True) # removed window decorations
# root.iconphoto(False, PhotoImage(file='icon.png'))
# root.attributes("-topmost", True)  # Keep on top of other windows
app = Application(root)
app.mainloop()
Esempio n. 12
0
class ServerWindow:
    def __init__(self):
        self.mainwindow = ThemedTk(theme='breeze')
        self.mainwindow.protocol("WM_DELETE_WINDOW", self.close)
        self.address = tk.StringVar()
        self.port = tk.IntVar()
        self.room_name = tk.StringVar()
        self.address.set("127.0.0.1")
        self.port.set(5000)
        self.room_name.set("Chat Room")
        self.status = {
            'server': tk.StringVar(value="Incative"),
            'conn': tk.StringVar(value='0 Connection(s)'),
            'rooms': tk.StringVar(value='0 Room(s)'),
            'verbose': tk.BooleanVar()
        }
        self.rooms = []
        self.is_update = True
        self.__init()
        self.restore()

    def title(self):
        self.mainwindow.title(self.room_entry.get())

    def start(self):
        self.title()
        self.mainwindow.mainloop()

    def __init(self):
        # Frame widgets
        self.__frame = tk.ttk.LabelFrame(self.mainwindow, text='Server Info')
        self.__frame.pack(side="top", padx=5, pady=5, fill='both', expand=True)
        self.__room_frame = tk.ttk.LabelFrame(self.mainwindow,
                                              text='Room List')
        self.__room_frame.pack(side='top',
                               pady=(0, 5),
                               padx=5,
                               fill='both',
                               expand=True)
        self.__status_frame = tk.ttk.LabelFrame(self.mainwindow, text='Status')
        self.__status_frame.pack(side='top',
                                 fill='x',
                                 padx=5,
                                 pady=(0, 5),
                                 expand=True)
        self.__verbose_frame = tk.ttk.LabelFrame(self.mainwindow,
                                                 text='Verbose')
        # self.__verbose_frame.pack(side='top', padx=(
        #     0, 5), pady=5, fill='both', expand=True)
        # Chat Window
        self.verbose_window = tk.Text(self.__verbose_frame,
                                      width=60,
                                      height=10)
        self.scrollframe = ScrollFrame(self.__room_frame)
        # Status widgets
        tk.ttk.Label(self.__status_frame, text="Server").grid(row=0,
                                                              column=0,
                                                              sticky="W")
        tk.ttk.Label(self.__status_frame,
                     text="Active Connection").grid(row=1,
                                                    column=0,
                                                    sticky="W")
        tk.ttk.Label(self.__status_frame, text="Rooms").grid(row=2,
                                                             column=0,
                                                             sticky="W")
        self.__status_label_server = tk.ttk.Label(
            self.__status_frame, textvariable=self.status['server'])
        self.__status_label_conn = tk.ttk.Label(
            self.__status_frame, textvariable=self.status['conn'])
        self.__status_label_rooms = tk.ttk.Label(
            self.__status_frame, textvariable=self.status['rooms'])
        self.__verbose_toggle = tk.ttk.Checkbutton(
            self.__status_frame,
            text='Verbose',
            variable=self.status['verbose'],
            command=self.toggle_verbose)
        # Connection Form widgets
        self.addr_label = tk.ttk.Label(self.__frame, text="Bind Address")
        self.addr_entry = tk.ttk.Entry(self.__frame, textvariable=self.address)
        self.port_label = tk.ttk.Label(self.__frame, text="Port")
        self.port_entry = tk.ttk.Entry(self.__frame, textvariable=self.port)
        self.room_label = tk.ttk.Label(self.__frame, text="Room Name")
        self.room_entry = tk.ttk.Entry(self.__frame,
                                       textvariable=self.room_name)
        self.listen_button = tk.ttk.Button(self.__frame,
                                           text="\u23f5 Listen",
                                           command=self.listen)
        self.stop_button = tk.ttk.Button(self.__frame,
                                         text="\u23f9 Stop",
                                         command=self.stop)
        self.room_button = tk.ttk.Button(self.__frame,
                                         text="Create",
                                         command=self.create_room)
        # Packing & grid widgets
        self.addr_label.grid(row=0, column=0, sticky="w")
        self.addr_entry.grid(row=0, column=1)
        self.port_label.grid(row=1, column=0, sticky="w")
        self.port_entry.grid(row=1, column=1)
        self.listen_button.grid(row=0,
                                column=2,
                                rowspan=2,
                                sticky="NSEW",
                                padx=2,
                                pady=2)
        self.stop_button.grid(row=0,
                              column=3,
                              rowspan=2,
                              sticky="NSEW",
                              padx=2,
                              pady=2)
        self.room_label.grid(row=2, column=0)
        self.room_entry.grid(row=2, column=1)
        self.room_button.grid(row=2,
                              column=2,
                              columnspan=2,
                              padx=2,
                              pady=5,
                              sticky="NSEW")
        self.scrollframe.pack()
        self.__status_label_server.grid(row=0, column=1, padx=5, sticky="w")
        self.__status_label_conn.grid(row=1, column=1, padx=5, sticky="w")
        self.__status_label_rooms.grid(row=2,
                                       column=1,
                                       padx=5,
                                       sticky="w",
                                       pady=(0, 5))
        self.__verbose_toggle.grid(row=0, column=2, rowspan=3, sticky='e')
        # self.verbose_window.pack(fill='both', expand=True)

    def insert(self, text):
        if self.verbose_window:
            self.verbose_window.insert("end", text + "\n")
            self.verbose_window.see('end')

    def save_room(self):
        self.title()

    def create_room(self, room=None):
        room_name = room if room is not None else self.room_entry.get()
        if any(room['name'] == room_name for room in self.rooms):
            messagebox.showwarning("Warning", "Room already exist.")
        elif len(room_name) not in range(3, 11, 1):
            messagebox.showwarning("Warning",
                                   "Room name must 3 to 10 character.")
        else:
            row = len(self.rooms)
            self.rooms.append({
                'name':
                room_name,
                'connections_var':
                tk.StringVar(value='Connection(s) : 0'),
                #    'connections': 0,
                #    'clients': [],
                'frame': [
                    tk.Frame(self.scrollframe.viewPort,
                             highlightbackground='black',
                             highlightthickness=1)
                ],
                'data': []
            })
            self.rooms[row]['frame'].append(
                tk.ttk.Frame(self.rooms[row]['frame'][0]))
            self.rooms[row]['frame'].append(
                tk.ttk.Frame(self.rooms[row]['frame'][0]))

            for i, frame in enumerate(self.rooms[row]['frame']):
                if i == 0:
                    frame.pack(fill='both', expand=1, padx=(5, 2), pady=(0, 5))
                elif i == 1:
                    frame.pack(side='left', pady=(5, 10))
                else:
                    frame.pack(side='right', pady=(5, 10))
            self.rooms[row]['widgets'] = {
                'label_name':
                tk.ttk.Label(self.rooms[row]['frame'][1], text=room_name),
                'label_connection':
                tk.ttk.Label(self.rooms[row]['frame'][1],
                             textvariable=self.rooms[row]['connections_var']),
                # 'enable': CustomButton(self.rooms[row]['frame'][2], text='\u23f5', width=40, height=30),
                # 'disable': CustomButton(self.rooms[row]['frame'][2], text='\u23f9', width=40, height=30, state='disabled'),
                'chat':
                CustomButton(self.rooms[row]['frame'][2],
                             text='\u2338',
                             width=40,
                             height=30),
                'delete':
                CustomButton(self.rooms[row]['frame'][2],
                             text='\u26a0',
                             width=50,
                             height=30),
            }
            self.rooms[row]['tips'] = {
                # 'enable_tip': ToolTip(self.rooms[row]['widgets']['enable'], 'Enable'),
                # 'disable_tip': ToolTip(self.rooms[row]['widgets']['disable'], 'Disable'),
                'chat_tip':
                ToolTip(self.rooms[row]['widgets']['chat'], 'Chat Window'),
                'delete_tip':
                ToolTip(self.rooms[row]['widgets']['delete'], 'Delete'),
            }
            for widget in self.rooms[row]['widgets']:
                if widget == 'label_connection' or widget == 'label_name':
                    self.rooms[row]['widgets'][widget].pack(side='top')
                elif widget == 'delete':
                    self.rooms[row]['widgets'][widget].pack(side='left',
                                                            padx=(0, 10))
                else:
                    self.rooms[row]['widgets'][widget].pack(side='left')
            self.status['rooms'].set(f'{len(self.rooms)} Room(s)')

    def get_address(self):
        return (self.address.get(), int(self.port_entry.get()))

    def listen(self):
        try:
            self.listen_server()
        except socket.error as e:
            self.insert(str(e))

    def listen_server(self):
        address = self.get_address()
        self.server = CreateServer(address)
        self.server.listen()
        self.status['server'].set(f"Listening")
        self.start_server(self.server)

    def start_server(self, server):
        self.room = HandleRooms(socket=self.server,
                                window=self,
                                name=self.room_entry.get())
        self.room.start()

    def stop(self):
        try:
            self.store()
            self.server.stop()
            self.is_update = False
            self.status['server'].set("Inactive")
        except Exception as e:
            messagebox.showerror("Error", str(e))

    def close(self):
        try:
            self.server.stop()
            self.mainwindow.destroy()
        except:
            self.mainwindow.destroy()

    def store(self):
        now = datetime.datetime.now()
        filename = f'{now.date()}'
        data = [{
            key: value
            for key, value in room.items() if key == 'name' or key == 'data'
        } for room in self.rooms]
        if self.rooms:
            with bz2.BZ2File(filename + '.pbz2', 'w') as file:
                cPickle.dump(data, file)
        else:
            pass

    def restore(self):
        filename = os.listdir()
        # print(filename)
        if 'pbz2' in [ext.split('.')[-1] for ext in filename]:
            file, = [f for f in filename if '.pbz2' in f]
            # print(file)
            data = bz2.BZ2File(file, 'rb')
            data = cPickle.load(data)
            # print(data)
            [self.create_room(room['name']) for room in data]
        else:
            pass

    def toggle_verbose(self):
        state = self.status['verbose'].get()
        if state:
            self.__verbose_frame.pack(side='top',
                                      padx=(0, 5),
                                      pady=5,
                                      fill='both',
                                      expand=True)
            self.verbose_window.pack(fill='both', expand=True)
        else:
            self.__verbose_frame.pack_forget()
            self.verbose_window.pack_forget()
Esempio n. 13
0
class AppEntrance(object):
    """进行打包的可视化外壳"""
    prograss_int = 0

    def __init__(self):
        """
         if exist_ttkthemes:
            # self.rootwindow = tk.Tk()
            self.rootwindow = ThemedTk(theme="arc")
        else:
            self.rootwindow = tk.Tk()
        self.rootwindow.title("")
        
        """

        if exist_ttkthemes:
            # self.rootwindow = tk.Tk()
            self.rootwindow = ThemedTk(theme="arc")
        else:
            self.rootwindow = tk.Tk()
            self.rootwindow.title("")

        # self.rootwindow = tk.Tk()
        # self.rootwindow.title("")
        # self.rootwindow.title("GISPOT")
        # self.rootwindow.update_idletasks()
        # self.rootwindow.overrideredirect(True)
        # self.rootwindow.tk_setPalette(background="#f5f6f7") # 一次性修改所有背景颜色
        newGUI.screen_cetre(self.rootwindow,
                            width=hyini.width,
                            height=hyini.height)
        self.rootwindow.iconbitmap(default=icon)
        self.rootwindow.resizable(1, 1)
        # self.rootwindow.attributes('-topmost', 0)
        self.gradient_bar()
        self.upgrade_from_github()
        # -------------------------------------
        # 主界面左侧图标工具栏
        # Frame的实际大小不仅仅受width控制,如果其中有其它部件,
        # 以其它部件大小为准
        self.main_face = tk.Frame(self.rootwindow,
                                  relief="sunken",
                                  width=55,
                                  height=600,
                                  bd=1)
        self.main_face.pack(side="left", fill="both", expand=True)
        # self.toolbar.place(x=0,y=0)
        # 初始界面右侧的交互界面的框架 interface_frame
        # self.interface_frame = tk.Frame(self.rootwindow, relief="groove",width= 900, height = 600)
        # self.interface_frame.pack(side="right", expand=True, fill="both")
        # self.interface_frame.place(x=55,y=0)

        # 绑定退出弹窗与退出功能,实现退出功能
        self.rootwindow.protocol("WM_DELETE_WINDOW", self.on_closing)
        # 界面
        # self.run_menu()
        # self.run_toolbar_viewer()
        tnb = interface.ttknotebook(self.main_face)
        interface.ToolSet(tnb.notebook2)

        self.rootwindow.mainloop()

    def gradient_bar(self):
        self.gradient_canv = newGUI.GradientCanvas(self.rootwindow,
                                                   "#ffc851",
                                                   "#808000",
                                                   relief="flat")
        self.gradient_canv.pack(side="bottom", anchor=tk.SE, fill="x")
        self.gradient_canv.create_text(32, 10, text="gispot 1")

    def upgrade_from_github(self):
        def open_u():
            update_url = r"https://github.com/hygnic/GisCat/archive/master.zip"
            weberopen(update_url, new=0, autoraise=True)

        # self.image_octacat = tk.PhotoImage(file=gispotpath.PngIcon.github)
        self.image_octacat = ImageTk.PhotoImage(
            Image.open(gppath.PngIcon.github))
        ap_button = newGUI.HoverButton(master=self.gradient_canv,
                                       command=open_u,
                                       bd=2,
                                       image=self.image_octacat,
                                       width=15,
                                       height=15)
        # ap_button = ttk.Button(master=self.gradient_canv,
        # 							   command=open_u,
        # 							   image=self.image_octacat)
        ap_button.pack(side='top', expand='yes', anchor="se")

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

    def button_config(self):
        def open_u():
            import webbrowser
            update_url = r"https://github.com/hygnic/GisCat/archive/master.zip"
            webbrowser.open(update_url, new=0, autoraise=True)

        ap_button = ttk.Button(text=u"获取更新", command=open_u)
        ap_button.pack(side='top', expand='yes', anchor="se")

    def on_closing(self):
        # 退出确认功能,防止误触发
        if tkMessageBox.askokcancel("Quit", "   Do you want to quit?"):
            self.rootwindow.destroy()
Esempio n. 14
0
    pressureVar.set("Pression: " + data["Pressure"] + " hPa")
    humidityVar.set("Humidité: " + data["Humidity"] + " %")
    updateXslx()  # Et ensuite de mettre les valeurs dans le fichier Excel


def close():
    """Fonction pour fermer la fenetre correctement"""
    main.destroy()
    excelwb.close()


main.title('Station météo')
main.geometry('515x615')  # 350x100
main.iconphoto(True, PhotoImage(file="gui/resources/icon.png"))
style = ThemedStyle(main)
main.protocol('WM_DELETE_WINDOW', close)
reloadData()
# sense.stick.direction_any = reloadData

timeLabel = Label(main,
                  textvariable=timeVar)  # On crée un label qui affiche la date
timeLabel.grid(row=0, column=0, columnspan=3)

temperatureLabel = Label(
    main,
    textvariable=temperatureVar)  # On crée un label qui affiche la température
temperatureLabel.grid(row=1, column=0)

pressureLabel = Label(
    main, textvariable=pressureVar)  # On crée un label qui affiche la pression
pressureLabel.grid(row=1, column=1)
Esempio n. 15
0
    ''' executes at WM_DELETE_WINDOW event - see below '''
    with open("winfo", "w") as fout:
        fout.write(root.geometry())
    root.destroy()


# ttkthemes
# 'alt', 'scidsand', 'classic', 'scidblue',
# 'scidmint', 'scidgreen', 'default', 'scidpink',
# 'arc', 'scidgrey', 'scidpurple', 'clam', 'smog'
# 'kroc', 'black', 'clearlooks'
# 'radiance', 'blue' : https://wiki.tcl-lang.org/page/List+of+ttk+Themes
root = ThemedTk(theme="scidgreen")

# change working directory to path for this file
p = os.path.realpath(__file__)
os.chdir(os.path.dirname(p))

if os.path.isfile("winfo"):
    with open("winfo") as f:
        lcoor = f.read()
    root.geometry(lcoor.strip())
else:
    root.geometry("400x300")  # WxH+left+top

root.title("Editor Demo")
root.protocol("WM_DELETE_WINDOW", save_location)
Sizegrip(root).place(rely=1.0, relx=1.0, x=0, y=0, anchor=SE)
app = Application(root)
app.mainloop()
    for i1 in names:
        list_.insert(x124, i1)
        lisst.append(list_.get(0, END))
        print(lisst)

        x124 += 1

    list_.bind('<Double-Button>', question1)


def CLOSE():
    pygame.mixer.music.stop()
    exit()


root.protocol('WM_DELETE_WINDOW', CLOSE)
open_dir_paths = []
play_ing_song_name = []
pygame.mixer.init()


def active_all():
    play['state'] = 'active'
    prev['state'] = 'active'
    next1['state'] = 'active'
    stop['state'] = 'active'


def _add_folder():
    global dir_name, open_dir_paths, mp3_wav_ogg, val, folder_name
    dir_name = filedialog.askdirectory()
Esempio n. 17
0
def main():
    # Check if Greenflare has been launched as part of a binary bundle as this
    # impacts the working_dir
    if getattr(sys, 'frozen', False):
        Defaults.set_working_dir(path.dirname(sys.executable))
    else:
        Defaults.set_working_dir(path.dirname(path.realpath(__file__)))

    # Linux specific settings
    if sys.platform == 'linux':

        import importlib
        check = importlib.util.find_spec("ttkthemes")

        # Use arc theme if available
        if check:
            from ttkthemes import ThemedTk
            root = ThemedTk(theme=Defaults.linux_theme)
        else:
            root = tk.Tk()

        # This ugly step is needed to initialise the filemanager variables we
        # are setting below
        try:
            root.tk.call('tk_getOpenFile', '-foobarbaz')
        except TclError:
            pass

        # Disable hidden files in file dialogues by default but show option to
        # show them
        root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1')
        root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0')

    else:
        root = tk.Tk()

    root.geometry("1024x768")
    # macOS tkinter cannot handle iconphotos at the time being, disabling it
    # for now
    if sys.platform != "darwin":
        root.iconphoto(False, tk.PhotoImage(file=Defaults.root_icon()))

    globalLock = Lock()
    crawl_items = Defaults.crawl_items
    Settings = Defaults.settings.copy()
    Crawler = GFlareCrawler(settings=Settings, gui_mode=True, lock=globalLock)

    app = mainWindow(root, crawler=Crawler)

    # running on macOS
    if sys.platform == "darwin":
        # Use TK's Apple Event Handler to react to clicked/open documents
        root.createcommand("::tk::mac::OpenDocument", app.open_file_on_macos)

    # Parse and load db file if provided
    parser = argparse.ArgumentParser()
    parser.add_argument("file_path", type=Path, nargs='*')

    p = parser.parse_args()

    if p.file_path and p.file_path[0].exists():
        app.load_crawl(db_file=p.file_path[0])

    root.protocol("WM_DELETE_WINDOW", app.on_closing)
    root.mainloop()
class GfxTabletGui:
    def __init__(self):
        self.main_window = ThemedTk(theme="breeze", background=True)
        #CenterScreen(self.main_window)
        self.main_window.protocol("WM_DELETE_WINDOW",
                                  lambda: self.main_window.iconify())
        self.main_window.resizable(False, False)
        self.main_window.title("GfxTablet GUI 1.0")
        #Status Group
        self.main_group = ttk.LabelFrame(self.main_window,
                                         text="Server Status",
                                         width=20)
        ##Server Hostname
        ttk.Label(self.main_group, text="Server Name: ",
                  width=25).pack(padx=10, pady=(10, 0), anchor="w")
        self.lbl_server_name = ttk.Label(self.main_group, text="NaN")
        self.lbl_server_name.pack(padx=(30, 0), anchor="w")
        ##Server IP
        ttk.Label(self.main_group, text="Server IP: ").pack(padx=10,
                                                            pady=(10, 0),
                                                            anchor="w")
        self.lbl_server_ip = ttk.Label(self.main_group, text="NaN")
        self.lbl_server_ip.pack(padx=(30, 0), anchor="w")
        ##Screen Resolution
        ttk.Label(self.main_group, text="Selected Screen: ").pack(padx=10,
                                                                  pady=(10, 0),
                                                                  anchor="w")
        self.lbl_screen_resolution = ttk.Label(self.main_group, text="NaN")
        self.lbl_screen_resolution.pack(padx=(30, 0), anchor="w")
        ##Status
        ttk.Label(self.main_group, text="Status: ").pack(padx=10,
                                                         pady=(10, 0),
                                                         anchor="w")
        self.lbl_status = ttk.Label(self.main_group, text="Waiting")
        self.lbl_status.pack(padx=(30, 0), anchor="w")
        ##Refresh Button
        self.btn_refresh = ttk.Button(self.main_group,
                                      text="Refresh",
                                      command=self.refresh)
        self.btn_refresh.pack(pady=(20, 5))
        ##Help Button
        self.btn_help = ttk.Button(self.main_group,
                                   text="Help",
                                   command=self.help)
        self.btn_help.pack(pady=(5, 5))
        ##About Button
        self.btn_about = ttk.Button(self.main_group,
                                    text="About",
                                    command=self.show_about)
        self.btn_about.pack(pady=(5, 5))
        ##Exit Button
        self.btn_close = ttk.Button(self.main_group,
                                    text="Quit",
                                    command=self.exit_program)
        self.btn_close.pack(pady=(5, 5))
        ##Download APK
        self.lbl_down_apk = Label(self.main_group,
                                  text="Download GfxTablet\nAndroid Package",
                                  fg="blue",
                                  font="Verdana 9 underline",
                                  cursor="hand2")
        self.lbl_down_apk.bind("<1>", self.down_apk)
        self.lbl_down_apk.pack(pady=5)
        #End Status Group
        self.main_group.pack(expand=False,
                             fill="both",
                             padx=(10, 5),
                             pady=10,
                             side="left")
        #Log Group
        self.log_group = ttk.LabelFrame(self.main_window, text="Logs")
        ##Log Text
        self.txt_log = Text(self.log_group,
                            width=50,
                            bg="white",
                            relief="solid",
                            font=("Verdana", 10))
        self.txt_log.pack(expand=True,
                          fill="both",
                          padx=5,
                          pady=5,
                          side="left")
        self.txt_scrollbar = ttk.Scrollbar(self.log_group,
                                           command=self.txt_log.yview)
        self.txt_log.config(yscrollcommand=self.txt_scrollbar.set)
        self.txt_scrollbar.pack(expand=True, fill="y", side="left")
        #End Log Group
        self.log_group.pack(expand=True,
                            fill="both",
                            padx=(10, 5),
                            pady=10,
                            side="right")
        self.load_values()
        threading.Thread(target=self.connect_cli).start()
        #Check Sudo
        if not os.geteuid() == 0:
            self.main_window.withdraw()
            messagebox.showerror(
                "Error", "You need root permissions to using GfxTablet GUI")
            exit()
        self.center_screen(self.main_window)
        self.main_window.mainloop()

    def load_values(self):
        self.lbl_server_name.config(text=self.get_server_name())
        self.lbl_server_ip.config(text=self.get_server_ip())
        self.lbl_screen_resolution.config(
            text=self.get_screen_resolution().decode("utf-8").rstrip("\n"))

    def get_server_name(self):
        return socket.getfqdn()

    def get_screen_resolution(self):
        return subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',
                                shell=True,
                                stdout=subprocess.PIPE).communicate()[0]

    def get_server_ip(self):
        try:
            conn = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            conn.connect(('8.8.8.8', 1))
            return conn.getsockname()[0]
        except:
            return "No Network Connection"

    def connect_cli(self):
        list_files = os.listdir(os.curdir)
        if "networktablet" in list_files:
            subprocess.check_call(['chmod', 'a+x', './networktablet'],
                                  cwd=os.path.dirname(
                                      os.path.realpath(__file__)))
            self.gfx_process = subprocess.Popen(
                ['./networktablet'],
                stdout=subprocess.DEVNULL,
                shell=True,
                cwd=os.path.dirname(os.path.realpath(__file__)))
            self.log_insert("Starting gfxtablet.")
            time.sleep(5)
            try:
                self.gfx_result = subprocess.check_output(['xinput', 'list'])
            except:
                self.gfx_result = subprocess.check_output(
                    ['libinput', 'list-devices'])  #For Arch and Wayland
            if not self.gfx_result.decode(
                    encoding="utf-8").find("Network Tablet") == -1:
                self.log_insert("Gfxtablet input driver is ready!")
                self.log_insert("Now you can connect to " +
                                self.lbl_server_ip["text"] +
                                " ip address from your Android device.")
                self.lbl_status["text"] = "Ready"
            else:
                self.log_insert("Gfxtablet input driver was not found.")
        else:
            self.log_insert("Gfxtablet not found.")
            self.btn_refresh["state"] = "disabled"
            try:
                downloadUrlGet = requests.get(
                    "https://github.com/rfc2822/GfxTablet/releases/download/android-app-1.4-linux-driver-1.5/networktablet"
                )
                with open('networktablet', 'wb') as newFile:
                    newFile.write(downloadUrlGet.content)
                self.log_insert("Downloading...")
                self.log_insert("Gfxtablet has been downloaded successfully.")
                self.btn_refresh["state"] = "normal"
                self.refresh()
            except:
                self.log_insert("No Network Connection.")

    def help(self):  #For running xdg-open without root. This is bad code.
        pid = os.fork()
        if pid == 0:
            try:
                self.btn_help["state"] = "disabled"
                os.setuid(1000)
                webbrowser.open("https://rfc2822.github.io/GfxTablet/")
            finally:
                os._exit(0)
                self.btn_help["state"] = "normal"

    def down_apk(self,
                 event):  #For running xdg-open without root. This is bad code.
        pid = os.fork()
        if pid == 0:
            try:
                self.lbl_down_apk.unbind("<1>")
                os.setuid(1000)
                webbrowser.open(
                    "https://github.com/rfc2822/GfxTablet/releases/download/android-app-1.4-linux-driver-1.5/gfxtablet_1_4.apk"
                )
            finally:
                os._exit(0)
                self.lbl_down_apk.bind("<1>", self.down_apk)

    def refresh(self):
        try:
            os.killpg(os.getpgid(self.gfx_process.pid), signal.SIGINT)
        except:
            pass
        finally:
            self.lbl_status["text"] = "Waiting"
            self.log_insert("Refreshing...")
            self.load_values()
            threading.Thread(target=self.connect_cli).start()

    def log_insert(self, text):
        self.txt_log.config(state="normal")
        self.txt_log.insert(END, text + '\n')
        self.txt_log.config(state="disabled")

    def center_screen(self, win):
        win.update_idletasks()
        width = win.winfo_width()
        frm_width = win.winfo_rootx() - win.winfo_x()
        win_width = width + 2 * frm_width
        height = win.winfo_height()
        titlebar_height = win.winfo_rooty() - win.winfo_y()
        win_height = height + titlebar_height + frm_width
        x = win.winfo_screenwidth() // 2 - win_width // 2
        y = win.winfo_screenheight() // 2 - win_height // 2
        win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
        win.deiconify()

    def show_about(self):
        messagebox.showinfo(
            "About Gfxtablet GUI",
            "gfxtablet 1.4\nAuthor: Ricki Hirner [email protected]\n\nGfxtablet GUI 1.0\nAuthor: Muhammet Emin TURGUT [email protected]"
        )

    def exit_program(self):
        try:
            os.killpg(os.getpgid(self.gfx_process.pid), signal.SIGINT)
        except:
            pass
        os._exit(0)
Esempio n. 19
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()
)  # Showing Our Label In Our Main Window That Means I Am Packing The Label.


def tkinter_window_is_closed(
):  # A Function That Ask Are You Sure Quit? When User Closes The Window.
    from tkinter import messagebox  # Importing messagebox For Asking Question.
    question = messagebox.askquestion('?',
                                      'Are You Sure Quit?')  # This Is Question
    if question == 'yes':  # If question answer is yes the destroy window If No Then Do Nothing.
        root.destroy()
    if question == 'no':
        None


root.protocol(
    'WM_DELETE_WINDOW', tkinter_window_is_closed
)  # Detecting That Our Window Is Closed. If Closed Then Call This kinter_window_is_closed() function.
root.title('Image Converter')  # Specifying Title
root.geometry('400x210')  # Specifying  Size


# This Function Converts An Image To PDF Format.
def pdfconversion():
    import tkinter.messagebox
    import tkinter
    from PIL import Image
    import os
    from tkinter import filedialog
    filename_1 = filedialog.asksaveasfile()
    rela_file_name = filename_1
    name = os.path.basename(str(rela_file_name))
            
            if message == "DIE":
                await discord_client.logout()
                break
            else:
                await dice_channel.send(message)
        
    #discord_client.run(TOKEN)
    discord_client.run(BOT_TOKEN, bot=True)
    
def on_app_close():
    messageQueue.put("DIE")
    root.destroy()

if __name__ == '__main__':
    mp.freeze_support()
    
    root = ThemedTk(theme="equilux")
    root.title("Frak's stupid dice roller")
    app = Application(master=root)
    root.geometry("+300+300")
    root.wm_attributes("-topmost", 1)
    root.protocol("WM_DELETE_WINDOW", on_app_close)
    
    ctx = mp.get_context('spawn')
    messageQueue = ctx.Queue()
    discordProcess = ctx.Process(target=discord_process, args=(messageQueue,))
    discordProcess.start()
    app.messageQueue = messageQueue
    
    app.mainloop()
Esempio n. 22
0
                        default=30,
                        help="Number of LED pixels")
    parser.add_argument("--led_pin",
                        type=int,
                        help="GPIO pin connected to the pixels")
    parser.add_argument("--led_brightness",
                        type=int,
                        help="Brightness of pixels (between 0 and 255)")
    parser.add_argument(
        "--use_gui",
        type=bool,
        default=True,
        help="If True, launch Tkinter GUI. If False, use command line")
    args = parser.parse_args()

    # Create a Moodlight object
    moodlights = Moodlights(args.led_count, args.led_pin, LED_FREQ_HZ, LED_DMA,
                            LED_INVERT, args.led_brightness, LED_CHANNEL)

    if args.use_gui:
        root = ThemedTk(theme="arc")
        gui = GUI(root, moodlights)
        root.protocol("WM_DELETE_WINDOW", moodlights.shutdown)
        root.mainloop()
    else:
        # Ask for user input
        while True:
            print_menu()
            option = input("Option: ")
            action(option)
Esempio n. 23
0
    response = cursor.fetchall()
    obj4 = response

    query = f"SELECT * from questions WHERE category='Sports' ORDER BY random() LIMIT 15;"
    cursor.execute(query)
    response = cursor.fetchall()
    obj5 = response

    #some used variables
    score = 0
    count = 1
    timer_status = 0
    selected = ""
    status = 0

    home.protocol("WM_DELETE_WINDOW", on_closing)

    def add_q(question_input, category, incorrect_1, incorrect_2, incorrect_3):
        if incorrect_3 == "" and incorrect_2 == "":
            sql = "INSERT INTO questions (question, category, correct_answer, incorrect_answer_1) VALUES (?,?,?,?)"
            values = (question_input, category, correct_answer_add.get(),
                      incorrect_1)
        else:
            sql = "INSERT INTO questions (question, category, correct_answer, incorrect_answer_1, incorrect_answer_2, incorrect_answer_3 ) VALUES (?,?,?,?,?,?)"
            values = (question_input, category, correct_answer_add.get(),
                      incorrect_1, incorrect_2, incorrect_3)
        try:
            cursor.execute(sql, values)
            conn.commit()
            tmsg.showinfo("Success", "Question added successfully")
            raise_frame(admin_panel)