Ejemplo n.º 1
0
    def destroy(self):
        """
        Destroy the MainWindow after checking for running processes

        Destroying the MainWindow is not allowed while connected to a
        Strategy Server or running one, the user will have to exit the
        server first.
        """
        if self.strategies_frame.settings is not None:
            if self.strategies_frame.settings.server:
                messagebox.showerror("Error", "You cannot exit the GSF Parser while running a Strategy Server.")
                return False
            if self.strategies_frame.settings.client:
                messagebox.showerror("Error", "You cannot exit the GSF Parser while connected to a Strategy Server.")
                return False
            self.strategies_frame.settings.destroy()
        if self.realtime_frame.parser is not None:
            if self.realtime_frame.parser.is_alive():
                self.realtime_frame.stop_parsing()
        ThemedTk.destroy(self)
        if self.rpc is not None:
            self.rpc.update()
            self.rpc.close()
        return True
Ejemplo n.º 2
0
        """Set the displayed month to the given value"""
        self._date = datetime(year=year, month=month, day=1)
        self.redraw_calendar()


class SetVar(object):
    """Set a predefined value in a variable upon call"""

    def __init__(self, variable: tk.Variable, value: Any):
        """
        :param variable: Variable to set the value for
        :param value: Value to apply to the Variable
        """
        self.variable = variable
        self.value = value

    def __call__(self):
        """Apply the value to the variable"""
        self.variable.set(self.value)


if __name__ == '__main__':
    from ttkthemes import ThemedTk
    w = ThemedTk(theme="arc")
    c = Calendar(w)
    now = datetime.now()
    year, month = now.year, now.month
    c.update_heatmap({datetime(year=year, month=month, day=i): i % 4 for i in range(1, 28)})
    c.grid()
    w.mainloop()
Ejemplo n.º 3
0
    versions = natsorted(versions, reverse=True)
    return versions


#The creation of the main window
if __name__ == '__main__':
    log_coloured(ASCII, random.choice(COLOURS))
    log_info("Checking internet status...")
    ConfigLoad()
    if Config.RPCEnable:
        log_info("Configuring the Discord Rich Presence...")
        RPC = Presence(Config.ClientId)
        RPC.connect()
        DefaultPresence()
    log_info("Loading themes...")
    MainWindow = ThemedTk(theme=Config.Theme)
    #Styles
    log_info("Configuring the UI...")
    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
Ejemplo n.º 4
0

def getFrameIndexFromXandY():
    x = window.winfo_pointerx() - window.winfo_rootx()
    y = window.winfo_pointery() - window.winfo_rooty()
    for i in range(MaxMoviesFrame):
        Frame_X, Frame_Y = FramesList[i][4], FramesList[i][5]
        if (Frame_X <= x and x <=
            (Frame_Width + Frame_X)) and (Frame_Y <= y and y <=
                                          (Frame_Height + Frame_Y)):
            return i


# Get Age and gender window

askWindow = ThemedTk(theme="equilux")
askWindow.geometry("320x240")
askWindow.tk.call('wm', 'iconphoto', askWindow._w,
                  tk.PhotoImage(file='Images/Icon.png'))
askWindow.title("User Info Window")
askWindow.resizable(False, False)

# askWindow frame

askWindowFrame = ttk.Frame(askWindow, width=640, height=480)
askWindowFrame.place(x=0, y=0)

# Drop down menu for age and gender

Age_Var_Label = tk.StringVar()
Age_Label = ttk.Label(askWindowFrame,
Ejemplo n.º 5
0
    user="******",
    passwd="root",
    database="bibliotecaparra"
)

mycursor = mydb.cursor()

#abrir ventana en el centro
def centrar_ventana(ventana):
    windowWidth = ventana.winfo_reqwidth()
    windowHeight = ventana.winfo_reqheight()
    positionRight = int(ventana.winfo_screenwidth()/2 - windowWidth/2)
    positionDown = int(ventana.winfo_screenheight()/3 - windowHeight/3)
    ventana.geometry("+{}+{}".format(positionRight, positionDown))

root = ThemedTk(theme="breeze")
root.title("Biblioteca Parra")
root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='book.png'))
root.geometry("305x200")
root.config(bg="white")
centrar_ventana(root)




#Ventana para registrar usuario
def open_registro():

    def popup_usuario_agregado():
        messagebox.showinfo("Listo", "Usuario agregado con exito!")
Ejemplo n.º 6
0
import openpyxl
from ttkthemes import ThemedTk



#----------------------------------------making pkl file of encodings-------------------------------------------
# encodings = face_recognition.face_recognition_cli.scan_known_people('images')
#
# pickle_out = open('encodings.pkl', 'wb')
# pickle.dump(encodings, pickle_out)
# pickle_out.close()


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

root = ThemedTk(theme='radiance')
root.resizable(0,0)
root.title('Attendance System')
root.iconbitmap('icon.ico')
root.geometry('1000x600')

logined = False
fristPage_image = ImageTk.PhotoImage(file = 'attendence.png')
imagetk = ImageTk.PhotoImage(file = 'recognition.png')
login_page_image = ImageTk.PhotoImage(file = 'manager.png')
# defining frames


def mainPage():
    root.geometry('1320x620')
    lmain2.destroy()
Ejemplo n.º 7
0
Archivo: gt2.py Proyecto: hygnic/Gispot
    def y_move(self, event):
        # 使可滚动界面根据鼠标滑轮滚动
        # 适配多种操作系统
        if platform.system() == 'Windows':
            self.canvas.yview_scroll(-1 * int(event.delta / 120), 'units')
        elif platform.system() == 'Darwin':
            self.canvas.yview_scroll(-1 * int(event.delta), 'units')
        else:
            if event.num == 4:
                self.canvas.yview_scroll(-1, 'units')
            elif event.num == 5:
                self.canvas.yview_scroll(1, 'units')


if __name__ == '__main__':
    root = ThemedTk(theme="arc")
    # root = tk.Tk()
    root.title("adv scrollbar")
    # root.geometry()
    # upper = tk.Frame(root, height=400)
    # upper.pack()
    # bottom = tk.Frame(root, bg="blue")
    # bottom.pack(side="bottom", fill="x")
    # tk.Button(bottom, text="test").pack()

    window = ScrollWidget(root)
    window.pack(expand=True, fill='both')
    window.update_idletasks()
    text = tk.Text(window.box)  # width=600, height=800
    text.pack(expand=1, fill="both")  # expand=1, fill="both"
    with open("Do Not Go Gentle into That Good Night.txt", "r") as f:
Ejemplo n.º 8
0
#

# UNCOMMENT THE FOLLOWING TO SAVE GEOMETRY INFO
# def save_location(e=None):
#     ''' 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="scidmint")

# 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("400x300") # WxH+left+top

root.title("Tkinter Demo")
# root.protocol("WM_DELETE_WINDOW", save_location)  # UNCOMMENT TO SAVE GEOMETRY INFO
Ejemplo n.º 9
0
    def show_login_window(self):
        root = ThemedTk(theme=self.STYLE)
        root.geometry("400x250")
        root.title('Login')
        root.resizable(0, 0)

        # title
        ttk.Label(root,
                  font=('default', 19, 'bold'),
                  text='*******Moriarity Point******').grid(row=0,
                                                            column=0,
                                                            sticky='w',
                                                            padx=15)
        ttk.Separator(root, orient='horizontal').grid(row=1,
                                                      columnspan=2,
                                                      sticky='ew')

        # sub title
        ttk.Label(root, font=('default', 14, 'bold'),
                  text='Admin Login').grid(row=2,
                                           column=0,
                                           sticky='w',
                                           padx=5,
                                           pady=10)

        def show_signup():
            root.destroy()
            self.show_signup_window()

        def login_db():
            conn = sqlite3.connect('user.db')
            p = var_user.get()
            query = conn.execute(
                "SELECT password FROM user_accounts WHERE name='" + p + "'")
            for row in query:
                id = row[0]
            if id == int(var_pass.get()):
                m = messagebox.askyesno(
                    'Success!', 'User logged in! Continue to make your orders')
                if m > 0:
                    root.destroy()
                    import restaurantmangement

            else:
                messagebox.showerror('Error!',
                                     'Username or password does not match!')

        PADX, PADY = 5, 5
        # login form
        ttk.Label(root, text='Username:'******'w',
                                               padx=PADX,
                                               pady=PADY)
        ttk.Label(root, text='Password:'******'w',
                                               padx=PADX,
                                               pady=PADY)

        var_user, var_pass = StringVar(), StringVar()
        ttk.Entry(root, textvariable=var_user, width=25).grid(row=3,
                                                              column=0,
                                                              sticky='e',
                                                              padx=PADX,
                                                              pady=PADY)
        ttk.Entry(root, textvariable=var_pass, width=25).grid(row=4,
                                                              column=0,
                                                              sticky='e',
                                                              padx=PADX,
                                                              pady=PADY)

        ttk.Button(root, text='Signup', command=show_signup).grid(row=5,
                                                                  column=0,
                                                                  sticky='w',
                                                                  padx=PADX,
                                                                  pady=PADY)
        ttk.Button(root, text='Login', command=login_db).grid(row=5,
                                                              column=0,
                                                              sticky='e',
                                                              padx=PADX,
                                                              pady=PADY)
        root.mainloop()
Ejemplo n.º 10
0
    def show_signup_window(self):
        root = ThemedTk(theme=self.STYLE)
        root.geometry("400x250")
        root.title('Signup')
        root.resizable(0, 0)

        # title
        ttk.Label(root,
                  font=('default', 19, 'bold'),
                  text='******Moriarity Point******').grid(row=0,
                                                           column=0,
                                                           sticky='w',
                                                           padx=15)
        ttk.Separator(root, orient='horizontal').grid(row=1,
                                                      columnspan=2,
                                                      sticky='ew')

        # sub title
        ttk.Label(root,
                  font=('default', 14, 'bold'),
                  text='Add a new employee').grid(row=2,
                                                  column=0,
                                                  sticky='w',
                                                  padx=5,
                                                  pady=10)

        # defs
        def show_login():
            root.destroy()
            self.show_login_window()

        def signup_db():
            conn = sqlite3.connect('user.db')
            if not var_pass.get() == var_repass.get():
                messagebox.showwarning('Warning!', 'Passwords do not match.')
                return
            try:
                query = "INSERT INTO user_accounts(name, password) VALUES ( '{var_user.get()}', '{var_pass.get()}' )"

                conn.execute(query)
                conn.commit()
                messagebox.showinfo(
                    'Success!', 'User account for %s successfuly created!' %
                    var_user.get())
                show_login()
            except:
                messagebox.showerror('Error!',
                                     'There was an unexpected error!')

        PADX, PADY = 5, 5
        # signup form
        ttk.Label(root, text='Username:'******'w',
                                               padx=PADX,
                                               pady=PADY)
        ttk.Label(root, text='Password:'******'w',
                                               padx=PADX,
                                               pady=PADY)
        ttk.Label(root, text='Re-Password:'******'w',
                                                  padx=PADX,
                                                  pady=PADY)

        var_user, var_pass, var_repass = StringVar(), StringVar(), StringVar()
        ttk.Entry(root, textvariable=var_user, width=25).grid(row=3,
                                                              column=0,
                                                              sticky='e',
                                                              padx=PADX,
                                                              pady=PADY)
        ttk.Entry(root, textvariable=var_pass, width=25).grid(row=4,
                                                              column=0,
                                                              sticky='e',
                                                              padx=PADX,
                                                              pady=PADY)
        ttk.Entry(root, textvariable=var_repass, width=25).grid(row=5,
                                                                column=0,
                                                                sticky='e',
                                                                padx=PADX,
                                                                pady=PADY)

        ttk.Button(root, text='Signup', command=signup_db).grid(row=8,
                                                                column=0,
                                                                sticky='e',
                                                                padx=PADX,
                                                                pady=PADY)
        ttk.Button(root, text='Login', command=show_login).grid(row=8,
                                                                column=0,
                                                                sticky='w',
                                                                padx=PADX,
                                                                pady=PADY)

        root.mainloop()
Ejemplo n.º 11
0
        ''' docstring '''

    def mn_edit_selall(self):
        ''' docstring '''

    def mn_edit_copy(self):
        ''' docstring '''

    def mn_edit_paste(self):
        ''' docstring '''

    def mn_help_index(self):
        ''' docstring '''

    def mn_help_about(self):
        ''' docstring '''


# root = Tk()
# Requires ttkthemes module
# '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="clearlooks")

root.title("menu demo")
app = Application(root)
app.mainloop()
from tkinter import *
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from ttkthemes import ThemedTk
from pygame import mixer
from mutagen.mp3 import MP3
import os
import time
import threading

main_application = ThemedTk(theme = "breeze")
main_application.title('SC Music Player')
main_application.geometry('600x600')
main_application.wm_iconbitmap('SC Media Player.ico')

status_bar_label = ttk.Label(main_application, text = 'Welcome To SC Music Player', relief = GROOVE, borderwidth = 2, font = ('Times New Roman', 15, 'italic'))
status_bar_label.pack(side = BOTTOM, fill = X)

button_frame = Frame(main_application)
button_frame.pack(side  = BOTTOM, fill = X)

length_frame = Frame(main_application)
length_frame.pack(side = BOTTOM, fill = X)

#&&&&&&&&&&&&&&&&&&&&&&&&&&&&& Start Icon Code &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

play_icon = PhotoImage(file = 'icon/play.png')
stop_icon = PhotoImage(file = 'icon/stop.png')
pause_icon = PhotoImage(file = 'icon/pause.png')
openfile_icon = PhotoImage(file = 'icon/file.png')
openfolder_icon = PhotoImage(file = 'icon/folder.png')
Ejemplo n.º 13
0
    def __init__(self):
        """ Inicializador da janela principal. """
        self.window = ThemedTk(theme='plastik')
        self.window.title("Cadastro de Produtos em Tkinter")
        self.window.resizable(0, 0)
        self.window.geometry(self.centraliza_window(568, 500))

        self.frame_principal = tk.Frame(self.window)
        self.frame_principal.pack(fill=BOTH)

        self.label_espaco = tk.Label(self.frame_principal)
        self.label_espaco.grid(row=0, column=1, pady=4)

        self.label_nome = tk.Label(self.frame_principal,
                                   text='Nome do produto:')
        self.label_nome.grid(row=1, column=1, padx=10)

        self.entry_nome = tk.Entry(self.frame_principal, width=45)
        self.entry_nome.grid(row=1, column=2, pady=4)
        self.entry_nome.focus()

        self.label_preco = tk.Label(self.frame_principal,
                                    text='Preço do produto:')
        self.label_preco.grid(row=2, column=1, padx=10)

        self.entry_preco = tk.Entry(self.frame_principal, width=10)
        self.entry_preco.grid(row=2, column=2, pady=4, sticky=W)

        self.button_cadastrar = tk.Button(self.frame_principal,
                                          text='CADASTRAR',
                                          width=15,
                                          command=lambda: self.adicionar(self))
        self.button_cadastrar.grid(row=2, column=2, padx=5, pady=15, sticky=E)
        self.button_cadastrar.bind('<Return>', self.adicionar)

        self.separator = tk.Separator(self.window, orient='horizontal')
        self.separator.pack(fill='x')

        self.frame_pesquisar = tk.Frame(self.window)
        self.frame_pesquisar.pack(fill='x')

        self.frame_espaco = tk.Frame(self.frame_pesquisar)
        self.frame_espaco.pack(pady=30)

        self.label_pesquisar = tk.Label(self.frame_pesquisar,
                                        text='Pesquisar:').pack(side=LEFT,
                                                                padx=20)

        self.entry_pesquisar = tk.Entry(self.frame_pesquisar, width=30)
        self.entry_pesquisar.pack(pady=10, side=LEFT)

        self.button_pesquisar = tk.Button(self.frame_pesquisar,
                                          text='Ok',
                                          command=self.pesquisar)
        self.button_pesquisar.pack(side=LEFT, padx=5)

        self.button_limpar = tk.Button(self.frame_pesquisar,
                                       text='Limpar',
                                       command=self.limpar)
        self.button_limpar.pack(side=LEFT, padx=5)

        self.frame_treeview = tk.Frame(self.window)
        self.frame_treeview.pack(fill='x')

        self.treeview = tk.Treeview(self.frame_treeview,
                                    columns=('id', "produto", 'preco'),
                                    show='headings')
        self.treeview.column('id', minwidth=0, width=30)
        self.treeview.column('produto', minwidth=0, width=250)
        self.treeview.column('id', minwidth=0, width=100)
        self.treeview.heading('id', text='ID')
        self.treeview.heading('produto', text='PRODUTO')
        self.treeview.heading('preco', text='PREÇO')
        self.treeview.grid(row=1, column=1)

        # scrollbar
        self.scrollbar = tk.Scrollbar(self.frame_treeview,
                                      orient="vertical",
                                      command=self.treeview.yview)
        self.scrollbar.grid(row=1, column=2, ipady=76)

        self.treeview.configure(yscrollcommand=self.scrollbar.set)

        self.frame_botoes = tk.Frame(self.window)
        self.frame_botoes.pack(side=BOTTOM, pady=10)

        self.button_excluir = tk.Button(self.frame_botoes,
                                        text='EXCLUIR',
                                        width=15,
                                        command=self.deletar)
        self.button_excluir.pack(side=LEFT)

        self.button_editar = tk.Button(self.frame_botoes,
                                       text='EDITAR',
                                       width=15,
                                       command=self.window_editar)
        self.button_editar.pack(side=LEFT, padx=5)

        self.button_sair = tk.Button(self.frame_botoes,
                                     text='SAIR',
                                     width=15,
                                     command=lambda: self.window.destroy())
        self.button_sair.pack(side=LEFT)

        self.visualizar_registros()

        self.window.mainloop()
Ejemplo n.º 14
0
class Cadastro_Produtos():
    """ Classe principal - chama a janela window com todos os widgets. """
    db_name = 'database.db'

    def __init__(self):
        """ Inicializador da janela principal. """
        self.window = ThemedTk(theme='plastik')
        self.window.title("Cadastro de Produtos em Tkinter")
        self.window.resizable(0, 0)
        self.window.geometry(self.centraliza_window(568, 500))

        self.frame_principal = tk.Frame(self.window)
        self.frame_principal.pack(fill=BOTH)

        self.label_espaco = tk.Label(self.frame_principal)
        self.label_espaco.grid(row=0, column=1, pady=4)

        self.label_nome = tk.Label(self.frame_principal,
                                   text='Nome do produto:')
        self.label_nome.grid(row=1, column=1, padx=10)

        self.entry_nome = tk.Entry(self.frame_principal, width=45)
        self.entry_nome.grid(row=1, column=2, pady=4)
        self.entry_nome.focus()

        self.label_preco = tk.Label(self.frame_principal,
                                    text='Preço do produto:')
        self.label_preco.grid(row=2, column=1, padx=10)

        self.entry_preco = tk.Entry(self.frame_principal, width=10)
        self.entry_preco.grid(row=2, column=2, pady=4, sticky=W)

        self.button_cadastrar = tk.Button(self.frame_principal,
                                          text='CADASTRAR',
                                          width=15,
                                          command=lambda: self.adicionar(self))
        self.button_cadastrar.grid(row=2, column=2, padx=5, pady=15, sticky=E)
        self.button_cadastrar.bind('<Return>', self.adicionar)

        self.separator = tk.Separator(self.window, orient='horizontal')
        self.separator.pack(fill='x')

        self.frame_pesquisar = tk.Frame(self.window)
        self.frame_pesquisar.pack(fill='x')

        self.frame_espaco = tk.Frame(self.frame_pesquisar)
        self.frame_espaco.pack(pady=30)

        self.label_pesquisar = tk.Label(self.frame_pesquisar,
                                        text='Pesquisar:').pack(side=LEFT,
                                                                padx=20)

        self.entry_pesquisar = tk.Entry(self.frame_pesquisar, width=30)
        self.entry_pesquisar.pack(pady=10, side=LEFT)

        self.button_pesquisar = tk.Button(self.frame_pesquisar,
                                          text='Ok',
                                          command=self.pesquisar)
        self.button_pesquisar.pack(side=LEFT, padx=5)

        self.button_limpar = tk.Button(self.frame_pesquisar,
                                       text='Limpar',
                                       command=self.limpar)
        self.button_limpar.pack(side=LEFT, padx=5)

        self.frame_treeview = tk.Frame(self.window)
        self.frame_treeview.pack(fill='x')

        self.treeview = tk.Treeview(self.frame_treeview,
                                    columns=('id', "produto", 'preco'),
                                    show='headings')
        self.treeview.column('id', minwidth=0, width=30)
        self.treeview.column('produto', minwidth=0, width=250)
        self.treeview.column('id', minwidth=0, width=100)
        self.treeview.heading('id', text='ID')
        self.treeview.heading('produto', text='PRODUTO')
        self.treeview.heading('preco', text='PREÇO')
        self.treeview.grid(row=1, column=1)

        # scrollbar
        self.scrollbar = tk.Scrollbar(self.frame_treeview,
                                      orient="vertical",
                                      command=self.treeview.yview)
        self.scrollbar.grid(row=1, column=2, ipady=76)

        self.treeview.configure(yscrollcommand=self.scrollbar.set)

        self.frame_botoes = tk.Frame(self.window)
        self.frame_botoes.pack(side=BOTTOM, pady=10)

        self.button_excluir = tk.Button(self.frame_botoes,
                                        text='EXCLUIR',
                                        width=15,
                                        command=self.deletar)
        self.button_excluir.pack(side=LEFT)

        self.button_editar = tk.Button(self.frame_botoes,
                                       text='EDITAR',
                                       width=15,
                                       command=self.window_editar)
        self.button_editar.pack(side=LEFT, padx=5)

        self.button_sair = tk.Button(self.frame_botoes,
                                     text='SAIR',
                                     width=15,
                                     command=lambda: self.window.destroy())
        self.button_sair.pack(side=LEFT)

        self.visualizar_registros()

        self.window.mainloop()

    def executa_banco(self, query, parameters=()):
        """
        Executa o banco de dados, o mesmo leva duas variáveis.

        query - instrução para executar o banco de dados,
        ex.: 'SELECT * FROM product ORDER BY id'.
        parameters - recebe os parametros para a execução da query; parameters
        é uma tupla.
        """
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            query_result = cursor.execute(query, parameters)
            conn.commit()
            return query_result

    def visualizar_registros(self):
        """ Pega todos os registros e coloca dentro da Treeview """
        records = self.treeview.get_children()
        for element in records:
            self.treeview.delete(element)
        query = 'SELECT * FROM product ORDER BY id'
        db_rows = self.executa_banco(query)
        for row in db_rows:
            self.treeview.insert('',
                                 'end',
                                 text=row[0],
                                 values=(row[0], row[1], row[2]))
        self.entry_pesquisar.delete(0, END)

    def validar(self):
        """ Verifica se as duas entradas não estão vazias """
        return len(self.entry_nome.get()) != 0 and len(
            self.entry_preco.get()) != 0

    def pesquisar(self):
        """ Realiza a pesquisa usando o método LIKE do SQL """
        parameters = (self.entry_pesquisar.get() + '%', )
        query = 'SELECT * FROM product WHERE name LIKE ?'
        db_rows = self.executa_banco(query, parameters)
        records = self.treeview.get_children()
        for element in records:
            self.treeview.delete(element)
        for row in db_rows:
            self.treeview.insert('',
                                 'end',
                                 text=row[0],
                                 values=(row[0], row[1], row[2]))

    def limpar(self):
        """ Limpa a entry pesquisar. """
        self.entry_pesquisar.delete(0, END)
        self.visualizar_registros()

    def adicionar(self, event):
        """ Adiciona nova entrada no banco de dados. """
        if self.validar():
            query = 'INSERT INTO product VALUES(NULL, ?, ?)'
            name = self.entry_nome.get().title()
            price = self.entry_preco.get()
            parameters = (name, price)
            self.executa_banco(query, parameters)
            self.entry_nome.delete(0, END)
            self.entry_preco.delete(0, END)
            self.mensagem(
                'info', 'Atenção',
                'Produto {} cadastrado:'.format(self.entry_nome.get()))
        else:
            self.mensagem('erro', 'Atenção',
                          'Favor preencher todos os campos.')
            self.entry_nome.focus()
        self.entry_nome.focus()
        self.visualizar_registros()

    def deletar(self):
        """ Deleta o item selecionado na Treeview. """
        if not self.treeview.item(self.treeview.selection())['text']:
            self.mensagem('erro', 'Atenção', 'Selecione um item para excluir.')
        else:
            name_item = self.treeview.item(self.treeview.selection())['values']
            msgBox = mb.askquestion(
                'Atenção',
                'Tem certeza que deseja excluir "{}"? Este processo é irreversível.'
                .format(name_item[1]))
            if msgBox == 'no':
                pass
            else:
                id = self.treeview.item(self.treeview.selection())['text']
                query = 'DELETE FROM product WHERE id = ?'
                self.executa_banco(query, (id, ))
                self.visualizar_registros()
                self.mensagem('info', 'Atenção',
                              '{} deletado.'.format(name_item[1]))

    def window_editar(self):
        """ Chama a janela de edição. """
        if not self.treeview.item(self.treeview.selection())['text']:
            self.mensagem('erro', 'Atenção', 'Selecione um item para editar.')
        else:
            selecao = self.treeview.item(self.treeview.selection())['values']
            id = selecao[0]
            name = selecao[1]
            price = selecao[2]
            self.edit_wind = Toplevel()
            self.edit_wind.title('Editando "{}"'.format(name))
            self.edit_wind.geometry('550x170')
            self.edit_wind.transient(self.window)
            self.edit_wind.focus_force()
            self.edit_wind.grab_set()

            self.frame_principal = tk.Frame(self.edit_wind)
            self.frame_principal.pack(fill=BOTH)

            self.label_espaco = tk.Label(self.frame_principal)
            self.label_espaco.grid(row=0, column=1, pady=4)

            self.label_nome = tk.Label(self.frame_principal,
                                       text='Nome do produto:')
            self.label_nome.grid(row=1, column=1, padx=10)

            self.entry_nome = tk.Entry(self.frame_principal, width=45)
            self.entry_nome.grid(row=1, column=2, pady=4)
            self.entry_nome.focus()

            self.label_preco = tk.Label(self.frame_principal,
                                        text='Preço do produto:')
            self.label_preco.grid(row=2, column=1, padx=10)

            self.entry_preco = tk.Entry(self.frame_principal, width=10)
            self.entry_preco.grid(row=2, column=2, pady=4, sticky=W)

            self.button_salvar = tk.Button(self.frame_principal,
                                           text='SALVAR',
                                           width=15,
                                           command=self.editar_registros)
            self.button_salvar.grid(row=5, column=1)
            #self.button_salvar.bind('<Return>', self.editar_registros)

            self.button_cancelar = tk.Button(
                self.frame_principal,
                text='CANCELAR',
                width=15,
                command=lambda: self.edit_wind.destroy())
            self.button_cancelar.grid(row=5, column=2, pady=30, sticky=W)

            self.entry_nome.insert(0, name)
            self.entry_preco.insert(0, price)

    def editar_registros(self):
        """ Substitui no banco de dados o registro anterior selecionado pelo registro editado. """
        selecao = self.treeview.item(self.treeview.selection())['values']
        id = selecao[0]
        name = selecao[1]
        old_price = selecao[2]
        new_name = self.entry_nome.get().title()
        new_price = self.entry_preco.get()
        parameters = (new_name, new_price, name, old_price)
        query = 'UPDATE product SET name=?, price=? WHERE name=? AND price=?'
        self.executa_banco(query, parameters)
        self.edit_wind.destroy()
        self.mensagem('info', 'Atenção',
                      'Cadastro "{}" editado com sucesso!'.format(name))
        self.visualizar_registros()

    def mensagem(self, tipoMsg, title, msg):
        """ Exibe mensagens de alerta ao usuário, o mesmo pode ser de erro ou atenção. """
        if tipoMsg == "erro":
            mb.showerror(title, msg)
        else:
            mb.showinfo(title, msg)

    def centraliza_window(self, comprimento, altura):
        """
        Dimensiona e centraliza a janela.

        recebe duas variáveis:
        comprimento - a largura da janela
        altura - a altura da janela
        """
        # Dimensões da janela
        self.comprimento = comprimento
        self.altura = altura
        # Resolução da tela
        self.comprimento_screen = self.window.winfo_screenwidth()
        self.altura_screen = self.window.winfo_screenheight()
        # Posição da janela
        self.pos_x = (self.comprimento_screen / 2) - (self.comprimento / 2)
        self.pos_y = (self.altura_screen / 2) - (self.altura / 2) - 10

        self.window.geometry("{}x{}+{}+{}".format(
            int(self.comprimento),
            int(self.altura),
            int(self.pos_x),
            int(self.pos_y),
        ))
Ejemplo n.º 15
0
def min(item):
    global party

    sc = ThemedTk(theme="arc")
    sc.title("ballot_page")
    sc.attributes('-fullscreen', True)
    sc.iconbitmap("gov2.ico")

    f1 = Frame(sc, height=123, width=2000, bg="#8fb7f7")
    c = Canvas(f1, width=120, height=100)

    def counter():
        tim = 30
        while 1:

            la = Label(sc, fg="red", font="10")
            timeformat = "Time remain: 00:{:02d}".format(tim)
            la["text"] = timeformat
            time.sleep(1)
            tim -= 1
            la.place(relx=0.45, rely=0.08)
            if tim == -1:
                messagebox.askokcancel(
                    message="Time Expired!\nPlease try later.")
                sc.destroy()

    th = threading.Thread(target=counter)
    th.daemon = True
    th.start()

    pd = item[7]
    with open("np.png", "wb") as fptr:
        fptr.write(base64.b64decode(item[7]))
    i = Image.open("np.png")
    i.thumbnail((120, 105))
    i.save("n.png")
    m = Image.open("n.png")
    k = ImageTk.PhotoImage(m)
    # c.create_image(image=k)

    gov2 = PhotoImage(file="gov2.png")
    gov1 = PhotoImage(file="gov1.png")
    l1 = Label(sc, image=gov2)
    l2 = Label(sc, image=gov1)
    f2 = Frame(sc, height=1000, width=1000, bg="#8fb7f7")

    l3 = Label(f1, bg="#8fb7f7")
    l4 = Label(f1, bg="#8fb7f7")
    l5 = Label(f1, bg="#8fb7f7")
    b117 = Button(image=k, bg="#8fb7f7")
    b117.place(relx=0.9, rely=0.135)

    l3["text"] = "Voter ID: " + str(item[9])
    l4["text"] = "Citizen ID Number: " + str(item[8])
    l5["text"] = "Name: " + item[0]
    l6 = Label(sc, fg="red", font="10")
    l6["text"] = "Party Selected: None"

    p1 = PhotoImage(file="1.png")
    p2 = PhotoImage(file="2.png")
    p3 = PhotoImage(file="3.png")
    p4 = PhotoImage(file="4.png")
    p5 = PhotoImage(file="5.png")
    p6 = PhotoImage(file="6.png")
    p7 = PhotoImage(file="7.png")
    p8 = PhotoImage(file="8.png")
    p9 = PhotoImage(file="9.png")
    p10 = PhotoImage(file="10.png")
    p11 = PhotoImage(file="11.png")
    p12 = PhotoImage(file="12.png")
    p13 = PhotoImage(file="13.png")
    p14 = PhotoImage(file="14.png")
    p15 = PhotoImage(file="15.png")

    def ff1(*args):
        global party
        party = 1
        l6["text"] = "Party Selected: " + str("Bibeksheel Sajha Party ")

    def ff2(*args):
        global party
        party = 2
        l6["text"] = "Party Selected: " + str("Federal Socialist Forum")

    def ff3(*args):
        global party
        party = 3
        l6["text"] = "Party Selected: " + str("Rastriya Janamorcha")

    def ff4(*args):
        global party
        party = 4
        l6["text"] = "Party Selected: " + str("Rastriya Prajatantra Party ")

    def ff5(*args):
        global party
        party = 5
        l6["text"] = "Party Selected: " + str("Naya Shakti Party")

    def ff6(*args):
        global party
        party = 6
        l6["text"] = "Party Selected: " + str("Bahujan Shakti Party ")

    def f7():
        global party
        party = 7
        l6["text"] = "Party Selected: " + str(
            "Communist Party of Nepal (Marxist–Leninist)")

    def f8():
        global party
        party = 8
        l6["text"] = "Party Selected: " + str(
            "Communist Party of Nepal (Unified Marxist–Leninist)")

    def f9():
        global party
        party = 9
        l6["text"] = "Party Selected: " + str("Nepal Pariwar Dal ")

    def f10():
        global party
        party = 10
        l6["text"] = "Party Selected: " + str("Nepal Federal Socialist Party ")

    def f11():
        global party
        party = 11
        l6["text"] = "Party Selected: " + str("Nepali Congress  ")

    def f12():
        global party
        party = 12
        l6["text"] = "Party Selected: " + str("Nepali Janata Dal")

    def f13():
        global party
        party = 13
        l6["text"] = "Party Selected: " + str("Rastriya Janamukti Party")

    def f14():
        global party
        party = 14
        l6["text"] = "Party Selected: " + str("Rastriya Janata Party ")

    def f15():
        global party
        party = 15
        l6["text"] = "Party Selected: " + str(
            "Rastriya Prajatantra Party (United) ")

    def submit():
        try:
            global party
            msg = messagebox.askyesno(message="Are you sure want to continue?")
            if msg == True:
                client.sendvote(party, item)
                os.remove("n.png")
                sc.destroy()
            else:
                pass
        except NameError:
            messagebox.showinfo(message="One candidate must be selected.")
            pass

    b1 = ttk.Button(f2, image=p1)
    b1.bind("<Button-1>", ff1)
    b2 = ttk.Button(f2, image=p2)
    b2.bind("<Button-1>", ff2)
    b3 = ttk.Button(f2, image=p3)
    b3.bind("<Button-1>", ff3)
    b4 = ttk.Button(f2, image=p4, command=ff4)
    b5 = ttk.Button(f2, image=p5, command=ff5)
    b6 = ttk.Button(f2, image=p6, command=ff6)
    b7 = ttk.Button(f2, image=p7, command=f7)
    b8 = ttk.Button(f2, image=p8, command=f8)
    b9 = ttk.Button(f2, image=p9, command=f9)
    b10 = ttk.Button(f2, image=p10, command=f10)
    b11 = ttk.Button(f2, image=p11, command=f11)
    b12 = ttk.Button(f2, image=p12, command=f12)
    b13 = ttk.Button(f2, image=p13, command=f13)
    b14 = ttk.Button(f2, image=p14, command=f14)
    b15 = ttk.Button(f2, image=p15, command=f15)

    b1.grid(row=0, column=1, padx=20, pady=20)
    b2.grid(row=0, column=2, padx=20, pady=20)
    b3.grid(row=0, column=3, padx=20, pady=20)
    b4.grid(row=0, column=4, padx=20, pady=20)
    b5.grid(row=0, column=5, padx=20, pady=20)
    b6.grid(row=1, column=1, padx=20, pady=20)
    b7.grid(row=1, column=2, padx=20, pady=20)
    b8.grid(row=1, column=3, padx=20, pady=20)
    b9.grid(row=1, column=4, padx=20, pady=20)
    b10.grid(row=1, column=5, padx=20, pady=20)
    b11.grid(row=2, column=1, padx=20, pady=20)
    b12.grid(row=2, column=2, padx=20, pady=20)
    b13.grid(row=2, column=3, padx=20, pady=20)
    b14.grid(row=2, column=4, padx=20, pady=20)
    b15.grid(row=2, column=5, padx=20, pady=20)

    f4 = Frame(sc, height=50, width=2000, bg="#8fb7f7")
    sub = ttk.Button(sc, text="Submit", command=submit)

    l1.place(relx=0.92, rely=0.001)
    l2.place(relx=0.01, rely=0.01)
    f1.place(relx=0, rely=0.125)
    f2.place(relx=0.24, rely=0.3)
    l4.place(relx=0.02, rely=0.1)
    l3.place(relx=0.047, rely=0.25)
    l5.place(relx=0.052, rely=0.4)
    l6.place(relx=0.24, rely=0.837)
    f4.place(relx=0, rely=0.87)
    sub.place(relx=0.71, rely=0.88)

    sc.mainloop()
Ejemplo n.º 16
0
 def report_callback_exception(self, exc, val, tb):
     """Redirect Exceptions in the mainloop to RavenClient"""
     if not os.path.exists("development"):
         self.raven.captureException()
     ThemedTk.report_callback_exception(self, exc, val, tb)
Ejemplo n.º 17
0
def main():
    root = ThemedTk(theme="breeze")
    root.geometry("500x500+250+100")
    app = Root(root)
    root.mainloop()
Ejemplo n.º 18
0
# A starter program for Python with Tkinter

from tkinter import *  # import Tkinter library
from tkinter.ttk import *
from ttkthemes import ThemedTk

window = ThemedTk(theme="arc")  # Create the application window
window.title("Hello")
window.geometry('500x500')

combo = Combobox(window)
combo['values'] = (1, 2, 3, 4, 5, "Text")
combo.current(1)  #set the selected item
combo.grid(column=0, row=0)

lbl = Label(window, text="Welcome", font=("Arial Bold", 10))
lbl.grid(column=0, row=0)

txt = Entry(window, width=10)
txt.grid(column=1, row=0)


def clicked():
    lbl.configure(text=txt.get() + " clicked the button!")
    lbl.configure(text=res)


txt.focus()

btn = Button(window, text="Click Me", command=clicked)
btn.grid(column=2, row=0)
Ejemplo n.º 19
0
def _create(gui: 'GUI'):
    engines = gui.engines

    gui._root = ThemedTk(theme="equilux", background=True)
    gui._root.title("Fishybot for Elder Scrolls Online")
    gui._root.iconbitmap(helper.manifest_file('icon.ico'))

    # region menu
    menubar = Menu(gui._root)

    filemenu = Menu(menubar, tearoff=0)

    login = web.is_logged_in(config.get('uid'))
    gui.login = IntVar()
    gui.login.set(1 if login > 0 else 0)
    state = DISABLED if login == -1 else ACTIVE
    filemenu.add_checkbutton(label="Login",
                             command=lambda: discord_login(gui),
                             variable=gui.login,
                             state=state)
    filemenu.add_command(label="Create Shortcut",
                         command=lambda: helper.create_shortcut(False))

    # filemenu.add_command(label="Create Anti-Ghost Shortcut", command=lambda: helper.create_shortcut(True))

    def _toggle_mode():
        config.set("dark_mode", not config.get("dark_mode", True))
        gui._start_restart = True

    dark_mode_var = IntVar()
    dark_mode_var.set(int(config.get('dark_mode', True)))
    filemenu.add_checkbutton(label="Dark Mode",
                             command=_toggle_mode,
                             variable=dark_mode_var)

    menubar.add_cascade(label="Options", menu=filemenu)

    debug_menu = Menu(menubar, tearoff=0)
    debug_menu.add_command(label="Check PixelVal",
                           command=lambda: gui.engine.check_pixel_val())

    debug_var = IntVar()
    debug_var.set(int(config.get('debug', False)))

    def keep_console():
        config.set("debug", bool(debug_var.get()))
        logging.debug("Restart to update the changes")

    debug_menu.add_checkbutton(label="Keep Console",
                               command=keep_console,
                               variable=debug_var)
    debug_menu.add_command(label="Restart", command=helper.restart)
    menubar.add_cascade(label="Debug", menu=debug_menu)

    help_menu = Menu(menubar, tearoff=0)
    help_menu.add_command(
        label="Need Help?",
        command=lambda: helper.open_web("http://discord.definex.in"))
    help_menu.add_command(
        label="Donate",
        command=lambda: helper.open_web("https://paypal.me/AdamSaudagar"))
    menubar.add_cascade(label="Help", menu=help_menu)

    gui._root.config(menu=menubar)
    # endregion

    # region console
    gui._console = Text(gui._root,
                        state='disabled',
                        wrap='none',
                        background="#707070",
                        fg="#ffffff")
    gui._console.pack(fill=BOTH, expand=True, pady=(15, 15), padx=(10, 10))
    gui._console.mark_set("sentinel", INSERT)
    gui._console.config(state=DISABLED)
    # endregion

    # region controls
    start_frame = Frame(gui._root)

    gui._engine_var = StringVar(start_frame)
    labels = list(engines.keys())
    last_started = config.get("last_started", labels[0])
    gui._engine_select = OptionMenu(start_frame, gui._engine_var, last_started,
                                    *labels)
    gui._engine_select.pack(side=LEFT)

    gui._config_button = Button(
        start_frame,
        text="⚙",
        width=0,
        command=lambda: engines[gui._engine_var.get()][0]())
    gui._config_button.pack(side=RIGHT)

    gui._start_button = Button(start_frame,
                               text=gui._get_start_stop_text(),
                               width=25,
                               command=gui.funcs.start_engine)
    gui._start_button.pack(side=RIGHT)

    start_frame.pack(padx=(10, 10), pady=(5, 15), fill=X)
    # endregion

    _apply_theme(gui)
    gui._root.update()
    gui._root.minsize(gui._root.winfo_width() + 10,
                      gui._root.winfo_height() + 10)
    if config.get("win_loc") is not None:
        gui._root.geometry(config.get("win_loc"))

    hotkey.set_hotkey(Key.F9, gui.funcs.start_engine)

    # noinspection PyProtectedMember
    def set_destroy():
        if gui._bot_running:
            if (not messagebox.askyesno(
                    title="Quit?",
                    message="Bot engine running. Quit Anyway?")):
                return

        config.set("win_loc", gui._root.geometry())
        gui._destroyed = True

    gui._root.protocol("WM_DELETE_WINDOW", set_destroy)
    gui._destroyed = False

    while True:
        gui._root.update()
        gui._clear_function_queue()
        if gui._start_restart:
            gui._root.destroy()
            gui._root.quit()
            gui._start_restart = False
            gui.create()
        if gui._destroyed:
            gui.engine.quit()
            break
        time.sleep(0.01)
Ejemplo n.º 20
0
def main():
    if platform.system() != 'Linux':
        showerror('Error', 'Linux Is Required')
        return 1

    global window

    window = ThemedTk(theme='equilux', className='mcpil')
    window.title('MCPIL')
    window.geometry('512x400')
    window.resizable(True, True)

    # Set icon in taskbar
    window.iconphoto(True, PhotoImage(file="/usr/share/pixmaps/mcpil.png"))

    tabs = ttk.Notebook(window)
    tabs.add(play_tab(tabs), text='Play')
    tabs.add(features_tab(tabs), text='Features')
    tabs.add(multiplayer_tab(tabs), text='Multiplayer')
    tabs.add(settings_tab(tabs), text='Settings')
    tabs.add(about_tab(tabs), text='About')
    tabs.pack(fill=BOTH, expand=True)

    load()
    save()

    window.wm_protocol('WM_DELETE_WINDOW', quit)
    signal.signal(signal.SIGINT, lambda *args: quit())

    try:
        window.mainloop()
    except KeyboardInterrupt:
        quit()

    return 0
Ejemplo n.º 21
0
from tkinter import *
from tkinter import ttk
from ttkthemes import ThemedTk
from tkinter import font as tkFont

root = ThemedTk(theme='arc')
root.iconbitmap('./img/calculator.ico')
root.resizable(0, 0)
box = ttk.Entry(root, width=53)
add = ''
result = ''

root.title("Calculator")
box.grid(column=0, row=0, columnspan=4, ipady=10)


def button_click(number):
    global add
    global result
    try:
        if number == 'AC':
            add = ''
            result = ''
        else:
            if number == '÷':
                add += number
                result += '/'
            elif number == '×':
                add += number
                result += '*'
            elif number == 'CE':
Ejemplo n.º 22
0
        os.startfile('%s' % filename)
    else:
        # we assume Mac since we do not support linux yet
        subprocess.call(["open", filename])


# function that deletes a contract
def delete_contract():
    filename = filedialog.askopenfilename(filetypes=(("Word Files", "*.docx"),
                                                     ("All files", "*.*")))
    os.remove('%s' % filename)


# main part
# create the window
window = ThemedTk(screenName="Contract Generator", theme="sriv")

window.title("Generate Docs")
# window.geometry("1400x700")
window.resizable(0, 0)

# with ttk we need to configure styles:
style = Style()
style.configure("TButton", font=("Arial", 12, 'bold'), width=25)
style.configure("TLabel",
                font=("Arial", 15),
                anchor=tk.W,
                width=30,
                foreground="darkblue")
style.configure("TEntry", font=("Arial", 15), anchor=tk.W)
Ejemplo n.º 23
0
        plt.xlabel("NAME")
        plt.ylabel("MARKS")
        plt.title("PERFOMANCE")
        plt.grid()
        plt.show()
    except cx_Oracle.DatabaseError as e:
        messagebox.showerror("issue : ", e)
    finally:
        if con is not None:
            con.close()


pygame.mixer.init()
success = pygame.mixer.music.load('success.mp3')

root = ThemedTk(theme='radiance')
root.title("Student Management System")
root.geometry("300x400+200+100")
mainlbl = ttk.Label(root, text="Student Management System", justify=CENTER)
mainlbl.pack(pady=5)
addbtn = ttk.Button(root, text="Add", command=show_add, width=20)
addbtn.pack(pady=5)
viewbtn = ttk.Button(root, text="View", command=show_view, width=20)
viewbtn.pack(pady=5)
updbtn = ttk.Button(root, text="Update", command=show_upd, width=20)
updbtn.pack(pady=5)
delbtn = ttk.Button(root, text="Delete", command=show_del, width=20)
delbtn.pack(pady=5)
graphbtn = ttk.Button(root, text="Graph", command=show_graph, width=20)
graphbtn.pack(pady=5)
try:
Ejemplo n.º 24
0
class GUI:
    root = ThemedTk(theme="default")
    # ttk.Style().theme_use('default')
    windowWidth = 1500
    windowHeight = 800
    screenWidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    xCord = (screenWidth / 2) - (windowWidth / 2)
    yCord = (screenheight / 2) - (windowHeight / 2)
    root.geometry('%dx%d+%d+%d' % (windowWidth, windowHeight, xCord, yCord))
    root.title("Resilionator")
    G = nx.Graph()
    nodesFromTextBox = list()
    frames = list()

    def __init__(self):
        self.layouts = [
            'Spring',
            'Planar',
            'Circular',
            # 'Kamada-Kawai',
            'Random',
            'Spectral',
            'Spiral'
        ]
        self.dir = '/home'
        self.routingFilePath = ''
        self.createMenu()
        self.createCanvas()
        FullScreenApp(self.root)
        self.root.mainloop()

    def on_mousewheel(self, event):
        scroll = -1 if event.delta > 0 else 1
        self.canvas.yview_scroll(scroll, "units")

    def createScrollingFrame(self):
        self.createMainFrame()

        # Create canvas
        self.canvas = Canvas(self.mainFrame, width=160)
        self.canvas.pack(side=LEFT, fill=BOTH)
        # self.canvas.pack(fill=BOTH, expand=1)

        # Add scrollbar to canvas
        self.scrollBar = Scrollbar(self.mainFrame,
                                   orient=VERTICAL,
                                   command=self.canvas.yview)
        self.scrollBar.pack(side=LEFT, fill=Y)
        # self.scrollBar.pack(side=RIGHT, fill=Y)

        # Configure canvas
        self.canvas.configure(yscrollcommand=self.scrollBar.set)
        self.canvas.bind(
            "<Configure>", lambda e: self.canvas.configure(scrollregion=self.
                                                           canvas.bbox("all")))
        self.canvas.bind_all("<MouseWheel>", self.on_mousewheel)

        # Create another frame inside canvas
        self.scrollFrame = Frame(self.canvas)

        # Add that new frame to a window in the canvas
        self.canvas.create_window((0, 0), window=self.scrollFrame, anchor="nw")

    def createConnectivityFrames(self, graph, figure, nodes=False):
        self.createDualFrameView()

        Lb = Listbox(self.leftFrame)
        Lb.configure(width=40)
        if nodes:
            Lb.insert(1, " Node: " + str(graph[0]))
        else:
            Lb.insert(1, " Edge: " + str(graph[0]))

        Lb.insert(2, " Connected: " + str(graph[1]))
        Lb.insert(3, " Has bridges: " + str(graph[2]))
        if graph[2]:
            Lb.insert(4, " Bridges: " + str(graph[3]))
            Lb.insert(4, " Articulation Points: " + str(graph[4]))
        Lb.pack(fill='both', expand=1)

        Button(self.leftFrame,
               text="Save as image",
               command=lambda: self.saveGraphAsImage(figure)).pack(fill=BOTH)

        try:
            self.fig.get_tk_widget().destroy()
        except Exception as e:
            print(e)
            pass
        self.fig = FigureCanvasTkAgg(figure, master=self.rightFrame)
        self.fig.get_tk_widget().pack(fill='both', expand=1)
        self.addFigureCanvasNavigation(self.fig, self.rightFrame)

    def createEdgeAugmentationFrames(self, graph, figure, edges):
        self.createDualFrameView()

        Lb = Listbox(self.leftFrame)
        Lb.configure(width=40)
        Lb.insert(1, " New egdes: " + str(edges))
        Lb.pack(fill='both', expand=1)

        Button(self.leftFrame,
               text="Adapt graph",
               command=lambda: self.adaptGraph(graph)).pack(fill=BOTH)
        Button(self.leftFrame,
               text="Export graph",
               command=lambda: self.exportGraph(graph)).pack(fill=BOTH)
        Button(self.leftFrame,
               text="Save graph as image",
               command=lambda: self.saveGraphAsImage(figure)).pack(fill=BOTH)

        try:
            self.fig.get_tk_widget().destroy()
        except Exception as e:
            print(e)
            pass
        self.fig = FigureCanvasTkAgg(figure, master=self.rightFrame)
        self.fig.get_tk_widget().pack(fill='both', expand=1)
        self.addFigureCanvasNavigation(self.fig, self.rightFrame)

    def createNodeAugmentationFrames(self, graph, figure, nodes):
        self.createDualFrameView()

        Lb = Listbox(self.leftFrame)
        Lb.configure(width=40)
        Lb.insert(1, " New nodes: " + str(nodes))
        Lb.pack(fill='both', expand=1)

        Button(self.leftFrame,
               text="Adapt graph",
               command=lambda: self.adaptGraph(graph)).pack(fill=BOTH)
        Button(self.leftFrame,
               text="Export graph",
               command=lambda: self.exportGraph(graph)).pack(fill=BOTH)
        Button(self.leftFrame,
               text="Save graph as image",
               command=lambda: self.saveGraphAsImage(figure)).pack(fill=BOTH)

        try:
            self.fig.get_tk_widget().destroy()
        except Exception as e:
            print(e)
            pass
        self.fig = FigureCanvasTkAgg(figure, master=self.rightFrame)
        self.fig.get_tk_widget().pack(fill='both', expand=1)
        self.addFigureCanvasNavigation(self.fig, self.rightFrame)

    def initConnectivity(self, nodesActive=True):

        self.isGraphEmtpy()
        self.createScrollingFrame()

        if nodesActive:
            graphs, figures = net.nodeConnectivity(self.G,
                                                   layout=self.layouts[0])
            self.createConnectivityFrames(graphs[0],
                                          figures[0],
                                          nodes=nodesActive)
            for g, f, i in zip(graphs, figures, range(len(graphs))):
                if i == 0:
                    text = 'Original'
                else:
                    text = 'Removed: ' + str(g[0])
                Button(
                    self.scrollFrame,
                    text=text,
                    command=lambda graph=g, figure=f: self.
                    createConnectivityFrames(graph, figure, nodes=nodesActive),
                    width=18).grid(row=i, column=0, sticky="we", columnspan=1)
        else:
            graphs, figures = net.edgeConnectivity(self.G,
                                                   layout=self.layouts[0])
            self.createConnectivityFrames(graphs[0], figures[0])
            for g, f, i in zip(graphs, figures, range(len(graphs))):
                if i == 0:
                    text = 'Original'
                else:
                    text = 'Removed: ' + str(g[0])
                Button(self.scrollFrame,
                       text=text,
                       command=lambda graph=g, figure=f: self.
                       createConnectivityFrames(graph, figure),
                       width=18).grid(row=i,
                                      column=0,
                                      sticky="we",
                                      columnspan=1)

    def initEdgeAugmentation(self):
        self.isGraphEmtpy()
        self.createScrollingFrame()

        graphs, figures, edges = net.edgeAugementation(self.G,
                                                       3,
                                                       layout=self.layouts[0])
        self.createEdgeAugmentationFrames(graphs[0], figures[0], edges[0])
        for g, f, e, i in zip(graphs, figures, edges, range(len(graphs))):
            if i == 0:
                text = 'Original'
            elif i == 1:
                text = 'Resistance: ' + str(i) + ' Fail'
            else:
                text = 'Resistance: ' + str(i) + ' Fails'
            Button(self.scrollFrame,
                   text=text,
                   command=lambda graph=g, figure=f, edges=e: self.
                   createEdgeAugmentationFrames(graph, figure, edges),
                   width=18).grid(row=i, column=0, sticky="we", columnspan=1)

    def initNodeAugmentation(self):
        self.isGraphEmtpy()
        self.createScrollingFrame()

        graphs, figures, nodes = net.kNodeAlgorithm(self.G,
                                                    layout=self.layouts[0])
        self.createNodeAugmentationFrames(graphs[0], figures[0], nodes[0])
        for g, f, n, i in zip(graphs, figures, nodes, range(len(graphs))):
            if i == 0:
                text = 'Original'
            elif i == 1:
                text = 'Resistance: ' + str(i) + ' Fail'
            else:
                text = 'Resistance: ' + str(i) + ' Fails'
            Button(self.scrollFrame,
                   text=text,
                   command=lambda graph=g, figure=f, nodes=n: self.
                   createNodeAugmentationFrames(graph, figure, nodes),
                   width=18).grid(row=i, column=0, sticky="we", columnspan=1)

    def initRouting(self, source, target, original=False):
        try:
            path = list()
            if original:
                path = net.dijkstra_original(self.G, source, target,
                                             self.nodesFromTextBox)
            else:
                path = net.shortest_path_dijkstra(self.G, source, target,
                                                  self.nodesFromTextBox)

            figures = net.create_figures_for_routing(self.G,
                                                     source,
                                                     target,
                                                     path,
                                                     self.nodesFromTextBox,
                                                     layout=self.layouts[0])
            self.popupWindow.destroy()
            self.createScrollingFrame()
            self.createRoutingFrames(0, figures, path, path[0],
                                     self.nodesFromTextBox)
            for i, f in zip(range(len(figures)), figures):
                Button(self.scrollFrame,
                       text="Step " + str(i + 1),
                       command=lambda index=i, figure=f: self.
                       createRoutingFrames(index, figures, path, path[index],
                                           self.nodesFromTextBox),
                       width=18).grid(row=i,
                                      column=0,
                                      sticky="we",
                                      columnspan=1)
        except Exception as e:
            messagebox.showerror(title=None, message=e)

    def initCustomRouting(self, source, target, file_path):
        path = list()
        try:
            print(file_path)
            path = net.build_path(self.G, source, target,
                                  self.nodesFromTextBox, file_path)
            figures = net.create_figures_for_routing(self.G,
                                                     source,
                                                     target,
                                                     path,
                                                     self.nodesFromTextBox,
                                                     layout=self.layouts[0])
            self.popupWindow.destroy()
            self.createScrollingFrame()
            self.createRoutingFrames(0, figures, path, path[0],
                                     self.nodesFromTextBox)
            for i, f in zip(range(len(figures)), figures):
                Button(self.scrollFrame,
                       text="Step " + str(i + 1),
                       command=lambda index=i, figure=f: self.
                       createRoutingFrames(index, figures, path, path[index],
                                           self.nodesFromTextBox),
                       width=18).grid(row=i,
                                      column=0,
                                      sticky="we",
                                      columnspan=1)
        except Exception as e:
            messagebox.showerror(title=None, message=e)

    def createRoutingAnimationWindow(self, figures):
        animationWindow = Toplevel(self.root)
        animationWindow.title('Routing Animation')
        animationWindow.geometry('1400x1000')
        for figure, index in zip(figures, range(len(figures))):
            fig = FigureCanvasTkAgg(figure, master=animationWindow)
            fig.get_tk_widget().pack(fill='both', expand=1)
            animationWindow.update()
            time.sleep(1.5)
            if index < len(figures) - 1:
                fig.get_tk_widget().destroy()
        animationWindow.destroy()

    def createRoutingFrames(self,
                            index,
                            figures,
                            path,
                            currentNode,
                            excluded=None):
        try:
            self.fig.get_tk_widget().destroy()
        except Exception as e:
            print(e)
            pass

        self.createDualFrameView()

        Lb = Listbox(self.leftFrame)
        Lb.configure(width=40)
        Lb.insert(
            1, "Routing step: (" + str(index + 1) + "/" + str(len(path)) + ")")
        Lb.insert(2, "Current node: " + currentNode)
        Lb.insert(3, "Path: " + str(path))
        if excluded is not None:
            Lb.insert(4, "Excluded nodes: " + str(excluded))
        Lb.pack(fill='both', expand=1)

        Button(
            self.leftFrame,
            text="Animate routing",
            command=lambda: self.createRoutingAnimationWindow(figures)).pack(
                fill=BOTH)
        Button(self.leftFrame,
               text="Save graph as image",
               command=lambda: self.saveGraphAsImage(figures)).pack(fill=BOTH)

        self.fig = FigureCanvasTkAgg(figures[index], master=self.rightFrame)
        self.fig.get_tk_widget().pack(fill='both', expand=1)
        self.addFigureCanvasNavigation(self.fig, self.rightFrame)

    def addEdge(self, nodeID1, nodeID2, weight):
        if weight == '':
            weight = 1
        if nodeID1.strip() != "" and nodeID2.strip() != "":
            self.popupWindow.destroy()
            net.addEdge(self.G, nodeID1, nodeID2, float(weight))
            self.createCanvas(layout=self.layouts[0])
        else:
            Label(self.popupWindow, text="Field can't be empty", font=('calibre', 10, 'normal'), fg='red') \
                .grid(row=0, column=0, columnspan=2, padx=5, sticky="we")

    def removeEdge(self, nodeID1, nodeID2):
        self.popupWindow.destroy()
        net.removeEdge(self.G, nodeID1, nodeID2)
        self.createCanvas(layout=self.layouts[0])

    def addNode(self, nodeID):
        if nodeID.strip() != "":
            self.popupWindow.destroy()
            net.addNode(self.G, nodeID)
            self.createCanvas(layout=self.layouts[0])
        else:
            Label(self.popupWindow, text="Field can't be empty", font=('calibre', 10, 'normal'), fg='red')\
                .grid(row=0, column=0, columnspan=2, padx=5, sticky="we")

    def removeNode(self, nodeID):
        self.popupWindow.destroy()
        net.removeNode(self.G, nodeID)
        self.createCanvas(layout=self.layouts[0])

    def importTxTFile(self):
        filepath = filedialog.askopenfilename(initialdir=self.dir,
                                              title="Select a File",
                                              filetypes=(("Text files",
                                                          "*.txt"), ))
        self.routingFilePath = filepath
        partitionedString = filepath.rpartition('/')
        self.dir = partitionedString[0]

        self.popupWindow.destroy()
        self.createCustomRoutingWindow()

    def importGraph(self):
        filepath = filedialog.askopenfilename(
            initialdir=self.dir,
            title="Select a File",
            filetypes=(("Text files", "*.txt"), ("Graphml files", "*.graphml"),
                       ("GML", "*.gml")))
        fileExtension = filepath.rpartition('.')
        if fileExtension[2] == "txt":
            self.G = net.importGraph(filepath)
            self.createCanvas(layout=self.layouts[0])
        if fileExtension[2] == "graphml":
            self.G = net.importGraphGraphml(filepath)
            self.createCanvas(layout=self.layouts[0])
        if fileExtension[2] == "gml":
            self.G = net.importGraphGml(filepath)
            self.createCanvas(layout=self.layouts[0])

        partitionedString = filepath.rpartition('/')
        self.dir = partitionedString[0]

    def exportGraph(self, G):

        self.isGraphEmtpy()

        filepath = filedialog.asksaveasfilename(initialdir=self.dir,
                                                title='Export graph',
                                                filetypes=[
                                                    ("Text files", "*.txt"),
                                                    ("Graphml files",
                                                     "*.graphml"),
                                                    ("GML files", "*.gml")
                                                ])

        fileExtension = filepath.rpartition('.')
        if fileExtension[2] == "txt":
            print(filepath)
            net.exportGraphTxt(G, filepath)
        if fileExtension[2] == "graphml":
            net.exportGraphGraphml(G, filepath)
        if fileExtension[2] == "gml":
            net.exportGraphGml(G, filepath)

        partitionedString = filepath.rpartition('/')
        self.dir = partitionedString[0]

    def saveGraphAsImage(self, figure):

        self.isGraphEmtpy()

        filepath = filedialog.asksaveasfilename(initialdir=self.dir,
                                                title='Save graph',
                                                filetypes=[
                                                    ("PNG files", "*.png"),
                                                    ("JPG files", "*.jpg")
                                                ])
        if filepath:
            print(filepath)
            net.saveGraphAsImage(filepath, figure)

        partitionedString = filepath.rpartition('/')
        self.dir = partitionedString[0]

    def adaptGraph(self, newGraph):
        answer = messagebox.askokcancel("Warning",
                                        "Adapt current graph to this one?")
        if answer:
            self.G = newGraph
            self.createCanvas(layout=self.layouts[0])

    def removeGraph(self):
        answer = messagebox.askokcancel("Warning", "Delete current graph?")
        if answer:
            self.G = nx.Graph()
            self.createCanvas(layout=self.layouts[0])

    def validate_float_input(self, action, index, value_if_allowed,
                             prior_value, text, validation_type, trigger_type,
                             widget_name):
        # action=1 -> insert
        if (action == '1'):
            if text in '0123456789.-+':
                try:
                    float(value_if_allowed)
                    return True
                except ValueError:
                    return False
            else:
                return False
        else:
            return True

    def createAddEdgeWindow(self):

        try:
            if len(self.G.nodes) < 2:
                raise nx.NetworkXError(
                    'Create at least two nodes to create an edge!')
        except Exception as e:
            messagebox.showerror(title=None, message=e)
            raise e

        self.createPopupWindow('Add edge')
        Label(self.popupWindow, text='Select 1.Endpoint:').grid(row=0,
                                                                column=0,
                                                                padx=5)
        nodeSelect1 = Combobox(self.popupWindow,
                               values=[node for node in self.G.nodes],
                               state="readonly")
        nodeSelect1.current(0)
        nodeSelect1.bind("<<ComboboxSelected>>")
        nodeSelect1.grid(row=0, column=1)

        Label(self.popupWindow, text='Select 2.Endpoint:').grid(row=1,
                                                                column=0,
                                                                padx=5)
        nodeSelect2 = Combobox(self.popupWindow,
                               values=[node for node in self.G.nodes],
                               state="readonly")
        nodeSelect2.current(1)
        nodeSelect2.bind("<<ComboboxSelected>>")
        nodeSelect2.grid(row=1, column=1)

        weight = StringVar(self.popupWindow)
        Label(self.popupWindow, text='Weight:').grid(row=2, column=0, padx=5)

        vcmd = (self.popupWindow.register(self.validate_float_input), '%d',
                '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        Entry(self.popupWindow,
              textvariable=weight,
              validate='key',
              validatecommand=vcmd).grid(row=2, column=1)

        Button(self.popupWindow,
               text="Confirm",
               command=lambda: self.addEdge(nodeSelect1.get(), nodeSelect2.get(
               ), weight.get()),
               width=15).grid(row=3, column=0, sticky="we", columnspan=2)

    def createRemEdgeWindow(self):

        self.isGraphEmtpy()

        self.createPopupWindow('Remove edge')
        Label(self.popupWindow, text='Select an Edge:').grid(row=0,
                                                             column=0,
                                                             padx=5)
        edgeSelect = Combobox(self.popupWindow,
                              values=[edge for edge in self.G.edges],
                              state="readonly")
        edgeSelect.current(0)
        edgeSelect.bind("<<ComboboxSelected>>")
        edgeSelect.grid(row=0, column=1)

        nodes = edgeSelect.get().split()
        Button(self.popupWindow,
               text="Confirm",
               command=lambda: self.removeEdge(nodes[0], nodes[1]),
               width=15).grid(row=1, column=0, sticky="we", columnspan=2)

    def createAddNodeWindow(self):
        self.createPopupWindow('Add node')
        Label(self.popupWindow, text='Node:').grid(row=1, column=0, padx=5)
        nodeID = StringVar()
        Entry(self.popupWindow, textvariable=nodeID, font=('calibre', 12, 'normal')) \
            .grid(row=1, column=1, pady=5, padx=5)
        Button(self.popupWindow,
               text="Confirm",
               command=lambda: self.addNode(nodeID.get()),
               width=15).grid(row=2, column=0, sticky="we", columnspan=2)

    def createRemNodeWindow(self):

        self.isGraphEmtpy()

        self.createPopupWindow('Remove node')
        Label(self.popupWindow, text='Select a Node:').grid(row=0,
                                                            column=0,
                                                            padx=5)
        nodeSelect = Combobox(self.popupWindow,
                              values=[node for node in self.G.nodes],
                              state="readonly")
        nodeSelect.current(0)
        nodeSelect.bind("<<ComboboxSelected>>")
        nodeSelect.grid(row=0, column=1)

        Button(self.popupWindow,
               text="Confirm",
               command=lambda: self.removeNode(nodeSelect.get()),
               width=15).grid(row=1, column=0, sticky="we", columnspan=2)

    def createTextBox(self, row, column, text=None):
        try:
            self.nodeText.destroy()
        except Exception as e:
            print(e)

        self.nodeText = Text(self.popupWindow, height=4, width=23)
        if text is not None:
            self.nodeText.insert(END, text)
        self.nodeText.config(state=DISABLED)
        self.nodeText.grid(row=row, column=column)

    def createNodesFromTextBox(self, node, row, column):
        if node in self.nodesFromTextBox:
            messagebox.showerror(title='Failed',
                                 message=node + ' is already in the list!')
        else:
            self.nodesFromTextBox.append(node)
            self.createTextBox(row, column, self.nodesFromTextBox)

    def createRoutingWindow(self, original=False):

        self.isGraphEmtpy()

        # Clear list when window is created
        self.nodesFromTextBox.clear()

        self.createPopupWindow('Dijkstra')
        Label(self.popupWindow, text='Source:').grid(row=0, column=0, padx=5)
        source = Combobox(self.popupWindow,
                          values=[node for node in self.G.nodes],
                          state="readonly")
        source.current(0)
        source.bind("<<ComboboxSelected>>")
        source.grid(row=0, column=1)

        Label(self.popupWindow, text='Target:').grid(row=1, column=0, padx=5)
        target = Combobox(self.popupWindow,
                          values=[node for node in self.G.nodes],
                          state="readonly")
        target.current(1)
        target.bind("<<ComboboxSelected>>")
        target.grid(row=1, column=1)

        Label(self.popupWindow, text='Exclude:').grid(row=2, column=0, padx=5)
        exclude = Combobox(self.popupWindow,
                           values=[node for node in self.G.nodes],
                           state="readonly")
        exclude.bind("<<ComboboxSelected>>")
        exclude.grid(row=2, column=1)

        self.createTextBox(3, 1, 'Excluded nodes...')

        Button(
            self.popupWindow,
            text="Add",
            command=lambda: self.createNodesFromTextBox(exclude.get(), 3, 1),
            width=10).grid(row=2, column=2, sticky="we", columnspan=1)

        Button(self.popupWindow,
               text="Clear",
               command=lambda: (self.nodesFromTextBox.clear(),
                                self.createTextBox(3, 1, 'Excluded nodes...')),
               width=10).grid(row=3, column=2, sticky="we", columnspan=1)

        Button(self.popupWindow,
               text="Start",
               command=lambda: self.initRouting(source.get(), target.get(),
                                                original),
               width=15).grid(row=5, column=0, sticky="we", columnspan=3)

    def createCustomRoutingWindow(self):

        self.isGraphEmtpy()

        # Clear list when window is created
        self.nodesFromTextBox.clear()

        self.createPopupWindow('Custom Routing')

        Label(self.popupWindow, text='Priorities:').grid(row=0,
                                                         column=0,
                                                         padx=5,
                                                         pady=10)
        Button(self.popupWindow,
               text="Open file",
               command=self.importTxTFile,
               width=15).grid(row=0,
                              column=1,
                              sticky="we",
                              columnspan=3,
                              pady=10)

        loadedFile = self.routingFilePath.rpartition('/')
        Label(self.popupWindow, text='File:').grid(row=1,
                                                   column=0,
                                                   padx=5,
                                                   pady=10)
        Label(self.popupWindow, text=loadedFile[2]).grid(row=1,
                                                         column=1,
                                                         padx=5,
                                                         pady=10)

        Label(self.popupWindow, text='Source:').grid(row=2, column=0, padx=5)
        source = Combobox(self.popupWindow,
                          values=[node for node in self.G.nodes],
                          state="readonly")
        source.current(0)
        source.bind("<<ComboboxSelected>>")
        source.grid(row=2, column=1)

        Label(self.popupWindow, text='Target:').grid(row=3, column=0, padx=5)
        target = Combobox(self.popupWindow,
                          values=[node for node in self.G.nodes],
                          state="readonly")
        target.current(1)
        target.bind("<<ComboboxSelected>>")
        target.grid(row=3, column=1)

        Label(self.popupWindow, text='Exclude:').grid(row=4, column=0, padx=5)
        exclude = Combobox(self.popupWindow,
                           values=[node for node in self.G.nodes],
                           state="readonly")
        exclude.current(2)
        exclude.bind("<<ComboboxSelected>>")
        exclude.grid(row=4, column=1)

        self.createTextBox(5, 1, 'Excluded nodes...')

        Button(
            self.popupWindow,
            text="Add",
            command=lambda: self.createNodesFromTextBox(exclude.get(), 5, 1),
            width=10).grid(row=4, column=2, sticky="we", columnspan=1)

        Button(self.popupWindow,
               text="Clear",
               command=lambda: (self.nodesFromTextBox.clear(),
                                self.createTextBox(3, 1, 'Excluded nodes...')),
               width=10).grid(row=5, column=2, sticky="we", columnspan=1)

        Button(self.popupWindow,
               text="Start",
               command=lambda: self.initCustomRouting(source.get(), target.get(
               ), self.routingFilePath),
               width=15).grid(row=6, column=0, sticky="we", columnspan=3)

    def createDualFrameView(self):
        try:
            self.destroyFrame(self.leftPW)
        except Exception as e:
            print(e)
        try:
            self.destroyFrame(self.rightPW)
        except Exception as e:
            print(e)

        self.leftPW = PanedWindow(self.mainFrame, orient=HORIZONTAL)
        self.leftFrame = Frame(self.leftPW)
        self.leftPW.pack(fill='both', expand=1)
        self.frames.append(self.leftPW)
        self.leftPW.add(self.leftFrame)

        self.rightPW = PanedWindow(self.mainFrame, orient=HORIZONTAL)
        self.rightFrame = Frame(self.rightPW)
        self.frames.append(self.rightPW)
        self.leftPW.add(self.rightPW)
        self.rightPW.add(self.rightFrame)

    def createLeftFrame(self):
        try:
            self.destroyFrame(self.leftFrame)
        except Exception as e:
            print(e)

        self.leftFrame = PanedWindow(self.mainFrame, orient=HORIZONTAL)
        self.frames.append(self.leftFrame)
        self.leftFrame.pack(fill='both', expand=1)

    def createRightFrame(self):
        try:
            self.destroyFrame(self.rightFrame)
        except Exception as e:
            print(e)

        self.rightFrame = PanedWindow(self.mainFrame, orient=HORIZONTAL)
        self.frames.append(self.rightFrame)
        self.leftFrame.add(self.rightFrame)

    def createMainFrame(self):
        self.destroyAllFrames()
        self.mainFrame = Frame(self.root)
        self.frames.append(self.mainFrame)
        self.mainFrame.pack(fill=BOTH, expand=1)

    def createNavigationFrame(self, frame=None):
        try:
            self.destroyFrame(self.navigationFrame)
        except Exception as e:
            print(e)

        # style = Style()
        # style.configure("BW.TLabel", background="grey")
        # style = "BW.TLabel" (Paste this into frame constructor)
        if frame is None:
            self.navigationFrame = Frame(self.mainFrame)
        else:
            self.navigationFrame = Frame(frame)
        self.frames.append(self.navigationFrame)
        self.navigationFrame.pack(fill=X)

    def addFigureCanvasNavigation(self, figureCanvas, parentFrame):
        # Add matplotlib toolbar
        NavigationToolbar2Tk(figureCanvas, parentFrame)

    def addNavigation(self):
        Label(self.navigationFrame, text='Graph Layout:').grid(row=0,
                                                               column=0,
                                                               padx=5)
        layoutSelect = Combobox(self.navigationFrame,
                                values=self.layouts,
                                state="readonly")
        layoutSelect.current(0)
        layoutSelect.bind("<<ComboboxSelected>>",
                          lambda x: self.changeLayout(layoutSelect.get()))
        layoutSelect.grid(row=0, column=1)

        Label(self.navigationFrame, text='Nodes:').grid(row=0,
                                                        column=2,
                                                        padx=5)
        Button(self.navigationFrame,
               text="+",
               command=self.createAddNodeWindow).grid(row=0, column=3)
        Button(self.navigationFrame,
               text="-",
               command=self.createRemNodeWindow).grid(row=0, column=4)

        Label(self.navigationFrame, text='Edges:').grid(row=0,
                                                        column=5,
                                                        padx=5)
        Button(self.navigationFrame,
               text="+",
               command=self.createAddEdgeWindow).grid(row=0, column=6)
        Button(self.navigationFrame,
               text="-",
               command=self.createRemEdgeWindow).grid(row=0, column=7)

        Label(self.navigationFrame, text='|').grid(row=0, column=8, padx=5)
        Button(self.navigationFrame,
               text="Create random graph",
               command=self.createRandomGraph).grid(row=0, column=9)
        Label(self.navigationFrame, text='|').grid(row=0, column=10, padx=5)
        Button(self.navigationFrame,
               text="Remove graph",
               command=self.removeGraph).grid(row=0, column=11)

    def changeLayout(self, selectedLayout):
        self.layouts.remove(selectedLayout)
        self.layouts.insert(0, selectedLayout)
        self.createCanvas(layout=selectedLayout)

    def createCanvas(self, layout='Spring', text=None):
        self.createMainFrame()
        self.createNavigationFrame()
        self.addNavigation()
        try:
            self.figCanvas.get_tk_widget().destroy()
        except Exception as e:
            print(e)
            pass

        if len(self.G.nodes) == 0:
            self.figCanvas = FigureCanvasTkAgg(net.createFigure(
                self.G, text='Import or create a graph'),
                                               master=self.mainFrame)
        elif text is None:
            text = 'Nodes ' + str(self.G.nodes)
            self.figCanvas = FigureCanvasTkAgg(net.createFigure(self.G,
                                                                layout=layout,
                                                                text=text),
                                               master=self.mainFrame)
        else:
            self.figCanvas = FigureCanvasTkAgg(net.createFigure(self.G,
                                                                layout=layout,
                                                                text=text),
                                               master=self.mainFrame)

        self.addFigureCanvasNavigation(self.figCanvas, self.mainFrame)

        self.figCanvas.get_tk_widget()
        self.figCanvas.get_tk_widget().pack(expand=1, fill="both")

    def createPopupWindow(self, title):
        self.popupWindow = Toplevel(self.root)
        self.popupWindow.title(title)
        centerCoord = self.calcRootCenter()
        self.popupWindow.geometry(f'+{centerCoord["x"]}+{centerCoord["y"]}')
        self.popupWindow.resizable(False, False)

    def createMenu(self):
        mainMenu = Menu(self.root)
        self.root.config(menu=mainMenu)
        graphMenu = Menu(mainMenu, tearoff=0)
        analysisMenu = Menu(mainMenu, tearoff=0)
        routingMenu = Menu(mainMenu, tearoff=0)
        helpMenu = Menu(mainMenu, tearoff=0)

        mainMenu.add_cascade(label='Graph', menu=graphMenu)
        mainMenu.add_cascade(label='Analysis', menu=analysisMenu)
        mainMenu.add_cascade(label='Routing', menu=routingMenu)
        mainMenu.add_cascade(label='Help', menu=helpMenu)

        graphMenu.add_command(
            label="Show graph",
            command=lambda: self.createCanvas(self.layouts[0]))
        graphMenu.add_command(label="Create random graph",
                              command=self.createRandomGraph)
        graphMenu.add_command(label="Import graph", command=self.importGraph)
        graphMenu.add_command(label="Export graph",
                              command=lambda: self.exportGraph(self.G))
        graphMenu.add_command(
            label="Save graph as image",
            command=lambda: self.saveGraphAsImage(net.createFigure(self.G)))
        graphMenu.add_command(label="Remove graph", command=self.removeGraph)

        nodeMenu = Menu(graphMenu, tearoff=0)
        graphMenu.add_cascade(label="Nodes", menu=nodeMenu)
        nodeMenu.add_command(label="Add node",
                             command=self.createAddNodeWindow)
        nodeMenu.add_command(label="Remove node",
                             command=self.createRemNodeWindow)

        edgeMenu = Menu(graphMenu, tearoff=0)
        graphMenu.add_cascade(label="Edges", menu=edgeMenu)
        edgeMenu.add_command(label="Add edge",
                             command=self.createAddEdgeWindow)
        edgeMenu.add_command(label="Remove edge",
                             command=self.createRemEdgeWindow)

        conMenu = Menu(analysisMenu, tearoff=0)
        analysisMenu.add_cascade(label="Connectivity", menu=conMenu)
        conMenu.add_command(label="Node connectivity",
                            command=self.initConnectivity)
        conMenu.add_command(
            label="Edge connectivity",
            command=lambda: self.initConnectivity(nodesActive=False))

        augmentMenu = Menu(analysisMenu, tearoff=0)
        analysisMenu.add_cascade(label="Augmentation", menu=augmentMenu)
        augmentMenu.add_command(label="K-Edge augmentation",
                                command=self.initEdgeAugmentation)
        augmentMenu.add_command(label="K-Node augmentation",
                                command=self.initNodeAugmentation)

        routingMenu.add_command(
            label="Dijkstra - Original",
            command=lambda: self.createRoutingWindow(original=True))
        routingMenu.add_command(label="Dijkstra - Recalculated distances",
                                command=self.createRoutingWindow)
        routingMenu.add_command(label="Custom Routing",
                                command=self.createCustomRoutingWindow)

        helpMenu.add_command(
            label="Github Repository",
            command=lambda: self.openURL(
                'https://github.com/philippzabka/resilionator'))
        helpMenu.add_command(label="About", command=self.createAboutWindow)

        # mainMenu.add_command(label="Quit", command=self.root.destroy)

    def calcRootCenter(self):
        root_x = int(self.root.winfo_rootx() +
                     (self.root.winfo_width() / 2.25))
        root_y = int(self.root.winfo_rooty() +
                     (self.root.winfo_height() / 3.0))
        return {'x': root_x, 'y': root_y}

    def destroyFrame(self, frame):
        try:
            frame.destroy()
        except Exception as e:
            print(e)

    def destroyAllFrames(self):
        for frame in self.frames:
            print(len(self.frames))
            try:
                frame.destroy()
            except Exception as e:
                print(e)
            finally:
                continue
        self.frames = list()

    def hideFrames(self):
        [frame.pack_forget() for frame in self.frames]

    def openURL(self, url):
        webbrowser.open(url)

    def isGraphEmtpy(self):
        try:
            if nx.is_empty(self.G):
                raise nx.NetworkXError('No graph found!')
        except Exception as e:
            messagebox.showerror(title=None, message=e)
            raise e

    def createRandomGraph(self):
        # self.removeGraph()
        self.G = net.createRandomGraph()
        self.createCanvas(layout=self.layouts[0])

    def createAboutWindow(self):
        self.createPopupWindow('About')
        f1 = Frame(self.popupWindow)
        f2 = Frame(self.popupWindow)
        f1.pack(fill=BOTH, expand=1)
        f2.pack(fill=BOTH, expand=1)

        url_python = 'https://www.python.org/'
        url_python_license = 'https://docs.python.org/3.8/license.html'
        url_matplotlib = 'https://matplotlib.org/stable/index.html'
        url_networkx = 'https://networkx.org/'
        url_networkx_license = 'https://raw.githubusercontent.com/networkx/networkx/master/LICENSE.txt'
        url_tkinter = 'https://docs.python.org/3.8/library/tkinter.html'
        url_re = 'https://docs.python.org/3.8/library/re.html'
        url_web = 'https://docs.python.org/3.8/library/webbrowser.html'
        url_rnd = 'https://docs.python.org/3.8/library/random.html'
        url_time = 'https://docs.python.org/3/library/time.html'
        url_ttkthemes = 'https://ttkthemes.readthedocs.io/en/latest/'
        url_ttkthemes_license = 'https://ttkthemes.readthedocs.io/en/latest/licenses.html'

        Label(f1, text='Author: 2021, Philipp Zabka').grid(row=0,
                                                           column=0,
                                                           padx=5,
                                                           pady=5)
        Label(f1, text='This software uses following products:')\
            .grid(row=1, column=0, padx=5, pady=5, sticky='we')

        # Matplotlib Homepage and License
        label_matplotlib = Label(f2, text='Matplotlib', foreground="blue")
        label_matplotlib.grid(row=2, column=0, padx=5, pady=5)
        label_matplotlib_license = Label(f2, text='License', foreground="blue")
        label_matplotlib_license.grid(row=2, column=1, padx=5, pady=5)

        # NetworkX Homepage and License
        label_networkx = Label(f2, text='NetworkX', foreground="blue")
        label_networkx.grid(row=3, column=0, padx=5, pady=5)
        label_networkx_license = Label(f2, text='License', foreground="blue")
        label_networkx_license.grid(row=3, column=1, padx=5, pady=5)

        # Python Homepage and License
        label_python = Label(f2, text='Python 3.8', foreground="blue")
        label_python.grid(row=4, column=0, padx=5, pady=5)
        label_python_license = Label(f2, text='License', foreground="blue")
        label_python_license.grid(row=4, column=1, padx=5, pady=5)

        # Random Homepage and License
        label_rnd = Label(f2, text='Python-Random', foreground="blue")
        label_rnd.grid(row=5, column=0, padx=5, pady=5)
        label_rnd_license = Label(f2, text='License', foreground="blue")
        label_rnd_license.grid(row=5, column=1, padx=5, pady=5)

        # Re Homepage and License
        label_re = Label(f2, text='Python-Re', foreground="blue")
        label_re.grid(row=6, column=0, padx=5, pady=5)
        label_re_license = Label(f2, text='License', foreground="blue")
        label_re_license.grid(row=6, column=1, padx=5, pady=5)

        # Time Homepage and License
        label_time = Label(f2, text='Python-Time', foreground="blue")
        label_time.grid(row=7, column=0, padx=5, pady=5)
        label_time_license = Label(f2, text='License', foreground="blue")
        label_time_license.grid(row=7, column=1, padx=5, pady=5)

        # Web Homepage and License
        label_web = Label(f2, text='Python-Webbrowser', foreground="blue")
        label_web.grid(row=8, column=0, padx=5, pady=5)
        label_web_license = Label(f2, text='License', foreground="blue")
        label_web_license.grid(row=8, column=1, padx=5, pady=5)

        # Tkinter Homepage and License
        label_tkinter = Label(f2, text='Tkinter', foreground="blue")
        label_tkinter.grid(row=9, column=0, padx=5, pady=5)
        label_tkinter_license = Label(f2, text='License', foreground="blue")
        label_tkinter_license.grid(row=9, column=1, padx=5, pady=5)

        #Ttkthemes Homepage and License
        label_ttkthemes = Label(f2, text='Ttkthemes', foreground="blue")
        label_ttkthemes.grid(row=10, column=0, padx=5, pady=5)
        label_ttkthemes_license = Label(f2, text='License', foreground="blue")
        label_ttkthemes_license.grid(row=10, column=1, padx=5, pady=5)

        label_python.bind("<Button-1>", lambda e: self.openURL(url_python))
        label_python_license.bind("<Button-1>",
                                  lambda e: self.openURL(url_python_license))
        label_tkinter.bind("<Button-1>", lambda e: self.openURL(url_tkinter))
        label_tkinter_license.bind("<Button-1>",
                                   lambda e: self.openURL(url_python_license))
        label_networkx.bind("<Button-1>", lambda e: self.openURL(url_networkx))
        label_networkx_license.bind(
            "<Button-1>", lambda e: self.openURL(url_networkx_license))
        label_matplotlib.bind("<Button-1>",
                              lambda e: self.openURL(url_matplotlib))
        label_matplotlib_license.bind(
            "<Button-1>", lambda e: self.openURL(url_python_license))
        label_re.bind("<Button-1>", lambda e: self.openURL(url_re))
        label_re_license.bind("<Button-1>",
                              lambda e: self.openURL(url_python_license))
        label_web.bind("<Button-1>", lambda e: self.openURL(url_web))
        label_web_license.bind("<Button-1>",
                               lambda e: self.openURL(url_python_license))
        label_rnd.bind("<Button-1>", lambda e: self.openURL(url_rnd))
        label_rnd_license.bind("<Button-1>",
                               lambda e: self.openURL(url_python_license))
        label_time.bind("<Button-1>", lambda e: self.openURL(url_time))
        label_time_license.bind("<Button-1>",
                                lambda e: self.openURL(url_python_license))
        label_ttkthemes.bind("<Button-1>",
                             lambda e: self.openURL(url_ttkthemes))
        label_ttkthemes_license.bind(
            "<Button-1>", lambda e: self.openURL(url_ttkthemes_license))
Ejemplo n.º 25
0
            self['fg'] = self.default_fg_color

    def foc_out(self, *args):
        if not self.get():
            self.put_placeholder()


def exitApp():
    exit()


if __name__ == '__main__':
    "Main function to produce the interface"
    LOGO_SIZE = 230

    root = ThemedTk(theme='arc')
    root.title('CHD predictor')
    root.resizable(False, False)
    #     root.configure(background="#222")

    path = "./Logo.png"
    img = Image.open(path)  # PIL solution
    img = img.resize((LOGO_SIZE, LOGO_SIZE),
                     Image.ANTIALIAS)  #The (250, 250) is (height, width)
    img = ImageTk.PhotoImage(img)
    panel = ttk.Label(root, image=img, anchor='center')
    panel.image = img
    panel.pack(side=TOP, fill=X)
    panel.configure(background=root.cget('bg'))

    lab = Label(root, width=20, text=description, font='Helvetica 14', pady=5)
Ejemplo n.º 26
0
#

# def save_location():
#     ''' executes at WM_DELETE_WINDOW event '''
#     with open("winfoxy", "w") as fout:
#         fout.write(str(root.winfo_x()) + "\n" + str(root.winfo_y() - 24))
#     root.destroy()

# root = Tk()
# Requires ttkthemes module
# '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="clam")

# root.geometry("200x120") # WxH+left+top
#   or the following:
#   the following repositions the window from last time '''
# if os.path.isfile("winfoxy"):
#     lcoor = tuple(open("winfoxy", 'r'))  # no relative path for this
#     root.geometry('350x200+%d+%d'%(int(lcoor[0].strip()),int(lcoor[1].strip())))
# else:
#     root.geometry("350x200") # WxH+left+top

root.title("Tkinter Demo")
# Sizegrip(root).place(rely=1.0, relx=1.0, x=0, y=0, anchor=SE)
# root.resizable(0,0) # no resize & removes maximize button
# root.overrideredirect(True) # removed window decorations
# root.iconphoto(False, PhotoImage(file='icon.png'))
Ejemplo n.º 27
0
import tkinter.ttk
from tkinter import*
from ttkthemes import ThemedTk
from tkinter import messagebox
from google_currency import convert  
import re
root=ThemedTk(themebg=True)
currencies_form=('Us Dollar (USD)','Indian Rupee (INR)','Japanese yen (JPY)','Euro (EUR)','Bulgarian lev (BGN)','Czech koruna (CZK)','Danish krone (DKK)','Hungarian forint (HUF)','Polish zloty (PLN)','Swedish krona (SEK)','Swiss franc (CHF)','Icelandic krona (ISK)','Norwegian krone (NOK)','Croatian kuna (HRK)','Russian rouble (RUB)','Turkish lira (TRY)','Australian dollar (AUD)','Brazilian real (BRL)','Canadian dollar (CAD)','Hong Kong dollar (HKD)','Indonesian rupiah (IDR)','South Korean won (KRW)','Mexican peso (MXN)','Malaysian ringgit (MYR)','New Zealand dollar (NZD)','Philippine peso (PHP)','Singapore dollar (SGD)','Thai baht (THB)','South African rand (ZAR)','Vietnamese Dong (VND)','Uzbekistani Som (UZS)','Uruguayan Peso (UYU)','British Pound (GBP)','Ukrainian Hryvnia (UAH)','Ugandan Shilling (UGX)','Tunisian Dinar (TND)','Tanzanian Shilling (TZS)','New Taiwan Dollar (TWD)','Swiss Franc (CHF)','Sri Lankan Rupee (LKR)','Singapore Dollar (SGD)','Saudi Riyal (SAR)','Poland Złoty (PLN)','Peruvian Sol (PEN)','Paraguay Guarani (PYG)','Panamanian Balboa (PAB)','Pakistani Rupee (PKR)','Omani Rial (OMR)','Norwegian Krone (NOK)','Nigerian Naira (NGN)','Nicaraguan Cordoba (NIO)','New Zealand Dollar (NZD)','Nepalese Rupee (NPR)','Burmese Kyat (MMK)','Moroccan Dirham (MAD)','Mexican Peso (MXN)','Mauritian Rupee (MUR)','Malaysia Ringgit (MYR)','Lebanese Pound (LBP)','Kuwaiti Dinar (KWD)','Kenyan Shilling (KES)','Kazakhstani Tenge (KZT)','Jordanian Dinar (JOD)','Indonesian Rupiah (IDR)','Hungarian Forint (HUF)','Guatemalan Quetzal (GTQ)','Georgian Lari (GEL)','Ethiopian Birr (ETB)','Egyptian Pound (EGP)','Dominican Peso (DOP)','Costa Rican Colon (CRC)','Chilean Peso (CLP)','Canadian Dollar (CAD)','Cambodian Riel (KHR)','Brazilian Real (BRL)','Bangladeshi Taka (BDT)','Bahraini Dinar (BHD)','Argentinian Peso (ARS)','Angola Kwanza (AOA)','Algerian Dinar (DZD)')
currencies_to=('Us Dollar (USD)','Indian Rupee (INR)','Japanese yen (JPY)','Euro (EUR)','Bulgarian lev (BGN)','Czech koruna (CZK)','Danish krone (DKK)','Hungarian forint (HUF)','Polish zloty (PLN)','Swedish krona (SEK)','Swiss franc (CHF)','Icelandic krona (ISK)','Norwegian krone (NOK)','Croatian kuna (HRK)','Russian rouble (RUB)','Turkish lira (TRY)','Australian dollar (AUD)','Brazilian real (BRL)','Canadian dollar (CAD)','Hong Kong dollar (HKD)','Indonesian rupiah (IDR)','South Korean won (KRW)','Mexican peso (MXN)','Malaysian ringgit (MYR)','New Zealand dollar (NZD)','Philippine peso (PHP)','Singapore dollar (SGD)','Thai baht (THB)','South African rand (ZAR)','Vietnamese Dong (VND)','Uzbekistani Som (UZS)','Uruguayan Peso (UYU)','British Pound (GBP)','Ukrainian Hryvnia (UAH)','Ugandan Shilling (UGX)','Tunisian Dinar (TND)','Tanzanian Shilling (TZS)','New Taiwan Dollar (TWD)','Swiss Franc (CHF)','Sri Lankan Rupee (LKR)','Singapore Dollar (SGD)','Saudi Riyal (SAR)','Poland Złoty (PLN)','Peruvian Sol (PEN)','Paraguay Guarani (PYG)','Panamanian Balboa (PAB)','Pakistani Rupee (PKR)','Omani Rial (OMR)','Norwegian Krone (NOK)','Nigerian Naira (NGN)','Nicaraguan Cordoba (NIO)','New Zealand Dollar (NZD)','Nepalese Rupee (NPR)','Burmese Kyat (MMK)','Moroccan Dirham (MAD)','Mexican Peso (MXN)','Mauritian Rupee (MUR)','Malaysia Ringgit (MYR)','Lebanese Pound (LBP)','Kuwaiti Dinar (KWD)','Kenyan Shilling (KES)','Kazakhstani Tenge (KZT)','Jordanian Dinar (JOD)','Indonesian Rupiah (IDR)','Hungarian Forint (HUF)','Guatemalan Quetzal (GTQ)','Georgian Lari (GEL)','Ethiopian Birr (ETB)','Egyptian Pound (EGP)','Dominican Peso (DOP)','Costa Rican Colon (CRC)','Chilean Peso (CLP)','Canadian Dollar (CAD)','Cambodian Riel (KHR)','Brazilian Real (BRL)','Bangladeshi Taka (BDT)','Bahraini Dinar (BHD)','Argentinian Peso (ARS)','Angola Kwanza (AOA)','Algerian Dinar (DZD)')
root.set_theme('ubuntu')
root.title('CurrencyConverter')
root.geometry('450x200')
# root.minsize(450,200)
# root.maxsize(450,200)
heading=ttk.Label(root,text='Currency Converter',font=('Courier',15,'bold'))
heading.pack()
currency_value=StringVar()#unit converter and add more sound effect to my dekstop remainder project!
currencies_value_to=StringVar()
Amount_value=StringVar()
from_=ttk.Combobox(root,value=currencies_form,width=24,textvariable=currency_value)
from_.place(x=50,y=40)
currency_value.set('Select Currency')
currencies_value_to.set('Select Currency')
to_=ttk.Combobox(root,value=currencies_to,width=24,textvariable=currencies_value_to)
to_.place(x=280,y=40)
from_['state']='readonly'
to_['state']='readonly'
def conversion():
	reverse=(currency_value.get()[::-1])
	codes_=(reverse[1:4:])
	working_codes_from=codes_[::-1]
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
# -*- coding:utf-8 -*-
# User: liaochenchen
# Date: 2019/11/6

# !/usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter as tk
import ttk
from ttkthemes import ThemedTk

# win = tk.Tk()
win = ThemedTk(theme="arc")
win.title("Python GUI")  # 添加标题

ttk.Label(win, text="Chooes a number").grid(column=1,
                                            row=0)  # 添加一个标签,并将其列设置为1,行设置为0
ttk.Label(win, text="Enter a name:").grid(
    column=0, row=0)  # 设置其在界面中出现的位置  column代表列   row 代表行


# button被点击之后会被执行
def clickMe():  # 当acction被点击时,该函数则生效
    action.configure(text='Hello ' + name.get())  # 设置button显示的内容
    action.configure(state='disabled')  # 将按钮设置为灰色状态,不可使用状态


# 按钮
action = ttk.Button(
    win, text="Click Me!", command=clickMe
)  # 创建一个按钮, text:显示按钮上面显示的文字, command:当这个按钮被点击之后会调用command函数
Ejemplo n.º 30
0
def main():
    conn = sqlite3.connect(
        'C:/Users/wahab/Desktop/thread/thread.db')
    c = conn.cursor()

    # creating table if not exits already

    c.execute("""CREATE TABLE IF NOT EXISTS info(id INTEGER PRIMARY KEY AUTOINCREMENT ,batchId INTEGER, height REAL ,width REAL, torn INTEGER , not_clean INTEGER ,timestamp TEXT)""")
    c.execute("""CREATE TABLE IF NOT EXISTS area(id INTEGER  ,name TEXT ,  area INTEGER , xmin INTEGER , xmax INTEGER ,ymin INTEGER , ymax INTEGER ,timestamp TEXT) """)
    c.execute(
        """CREATE TABLE IF NOT EXISTS result(id INTEGER PRIMARY KEY  , result TEXT ,timestamp TEXT)""")
    c.execute("""CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY  AUTOINCREMENT, username TEXT ,password TEXT)""")
    # c.execute("""INSERT INTO USER(username, password) values('wahab' , 'wahab123')""")

    # checking if record of two weeks old exists and make report of it and delete

    two_week_old = c.execute(
        """SELECT * FROM info WHERE timestamp < datetime('now', '-14 days');""").fetchall()
    if len(two_week_old) != 0:
        last_week_record = c.execute(
            """SELECT * FROM info WHERE timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days');""").fetchall()
        # print(last_week_record)
        accepted = c.execute(
            "SELECT COUNT(*) from result where result='False' and timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]
        rejected = c.execute(
            "SELECT COUNT(*) from result where result='True' and  timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]
        total_batches = c.execute(
            "SELECT COUNT(DISTINCT batchId) from info where timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]
        batches = c.execute(
            "SELECT torn , not_clean , timestamp from info where timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days')  ").fetchall()
        total_correct_dimensions = c.execute(
            "SELECT COUNT(DISTINCT batchId)  from info where  height>=20 and height<=25  and timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]
        total_wrong_dimensions = total_batches = total_correct_dimensions
        total_torn = 0
        total_dirty = 0

        # print(b)
        for a in batches:
            total_torn += a[0]
            total_dirty += a[1]

        # counting numbers of files in weekly reports for numbering
        DIR = "C:/Users/wahab/Desktop/thread/weekly_reports"
        week = len([name for name in os.listdir(DIR)
                    if os.path.isfile(os.path.join(DIR, name))])

        workbook = xlsxwriter.Workbook(
            f'C:/Users/wahab/Desktop/thread/weekly_reports/week-{week+1}.xlsx')
        worksheet = workbook.add_worksheet()

        worksheet.set_column('A:A', 40)
        # Insert an image.

        worksheet.insert_image('A1', 'logo2.png')

        # Some data we want to write to the worksheet.
        expenses = (
            ['total tested ', total_batches],
            ['total accepted ',   accepted],
            ['total rejected ',  rejected],
            ['total number of torns',    total_torn],
            ['total number of dirty',    total_dirty],
            ['average number of torns per loom',    total_torn/4],
            ['average number of dirty per loom',    total_dirty/4],
            ['total correct dimensions',    total_correct_dimensions],
            ['total wrong dimensions',    total_wrong_dimensions],
        )

        # Start from the first cell. Rows and columns are zero indexed.
        row = 11
        col = 0
        bold = workbook.add_format({'bold': True})
        bold.set_font_size(15)
        # Iterate over the data and write it out row by row.
        for item, cost in (expenses):
            worksheet.write(row, col,     item, bold)
            worksheet.write(row, col + 1, cost)
            row += 1

        workbook.close()

        c.execute(
            "DELETE FROM result where  timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]
        c.execute(
            "DELETE FROM info where  timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]
        c.execute(
            "DELETE FROM area where  timestamp BETWEEN datetime('now', '-14 days') AND datetime('now', '-7 days') ").fetchall()[0][0]

    conn.commit()
    conn.close()

    # checking if images in directory are two weeks old if yes then delete

    now = time.time()
    dir = 'C:/Users/wahab/Desktop/thread/img_database/'
    for f in os.listdir(dir):
        if os.stat(os.path.join(dir, f)).st_mtime < now - 14 * 86400:
            shutil.rmtree(os.path.join(dir, f))

    root = ThemedTk(theme="adapta")
    root.state('iconic')
    root.resizable(False, False)
    width = root.winfo_screenwidth()
    height = root.winfo_screenheight()
    root.geometry(f"{width}x{height}")

    canvas = Canvas(root, width=width, height=height)

    app = Example(width, height, canvas)
    root.mainloop()
Ejemplo n.º 31
0
import os
import time
import threading
from tkinter import *
from tkinter import ttk
from ttkthemes import ThemedTk
from pygame import mixer
import tkinter.messagebox
from mutagen.mp3 import MP3
from tkinter import filedialog

root = ThemedTk(theme="yaru")

statusbar = ttk.Label(root,
                      text="Welcome to Player360",
                      relief=SUNKEN,
                      anchor=W,
                      font="Times 10 bold")
statusbar.pack(side=BOTTOM, fill=X)

playList = []

#config tapbar
menuBar = Menu(root)
root.config(menu=menuBar)


#make topbar
def browse_file():
    global filename
    filename = filedialog.askopenfilename()
Ejemplo n.º 32
0
class ClientWindow:
    def __init__(self):
        self.mainwindow = ThemedTk(theme='breeze')
        self.mainwindow.resizable(0, 0)
        self.address = tk.StringVar()
        self.port = tk.IntVar()
        self.username = tk.StringVar()
        self.room_var = tk.StringVar()
        self.address.set("127.0.0.1")
        self.port.set(5000)
        self.room_list = []
        self.is_join_room = False
        self.connection = None
        self.room = None
        self.title("ChatClient")
        self.__init()

    def title(self, title):
        self.mainwindow.title(title)

    def __init(self):
        # Frame Widgets
        self.__server_frame = tk.ttk.LabelFrame(self.mainwindow,
                                                text="Connection Info")
        self.__chat_frame = tk.ttk.LabelFrame(self.mainwindow,
                                              text="Chat Room")
        self.__input_frame = tk.ttk.Frame(self.mainwindow)
        # Frame Packing
        self.__server_frame.pack(side='top', fill='both', pady=(10, 0), padx=5)
        self.__chat_frame.pack(side='top', fill='both', padx=5, pady=5)
        self.__input_frame.pack(side='top', fill='both', pady=10, padx=10)
        # Widgets
        # Connection Form Widgets
        self.room_entry = tk.ttk.Entry(self.__server_frame,
                                       textvariable=self.room_var)
        self.address_label = tk.ttk.Label(self.__server_frame, text="Address")
        self.address_entry = tk.ttk.Entry(self.__server_frame,
                                          textvariable=self.address)
        self.port_label = tk.ttk.Label(self.__server_frame, text="Port")
        self.port_entry = tk.ttk.Entry(self.__server_frame,
                                       textvariable=self.port)
        self.connect_button = tk.ttk.Button(
            self.__server_frame,
            text="Connect",
            command=lambda: self.connecting(self.room_entry.get()))
        self.disconnect_button = tk.ttk.Button(self.__server_frame,
                                               text="Disconnect",
                                               command=self.disconnect)
        self.username_label = tk.ttk.Label(self.__server_frame,
                                           text="Username")
        self.username_entry = tk.ttk.Entry(self.__server_frame,
                                           textvariable=self.username)
        self.username_button_edit = tk.ttk.Button(self.__server_frame,
                                                  text="Edit",
                                                  state='disabled')
        self.room_label = tk.ttk.Label(self.__server_frame, text="Room")
        self.room_button_scan = tk.ttk.Button(self.__server_frame,
                                              text="Scan",
                                              command=self.request_room)
        # Chat Scrollframe Widget
        self.scrollframe = ScrollFrame(self.__chat_frame)
        # Message Form Widgets
        self.message_label = tk.ttk.Label(self.__input_frame, text="Message")
        self.message_text = tk.ttk.Entry(self.__input_frame, width=35)
        self.message_text.bind("<Return>", self.send)
        self.message_button = tk.ttk.Button(self.__input_frame,
                                            text="Send",
                                            command=self.send)
        ### Packing & Grid
        # Connection Form Grid
        self.address_label.grid(row=0, column=0)
        self.address_entry.grid(row=0, column=1)
        self.port_label.grid(row=1, column=0)
        self.port_entry.grid(row=1, column=1)
        self.connect_button.grid(row=0,
                                 column=2,
                                 rowspan=2,
                                 sticky="NSEW",
                                 padx=5)
        self.disconnect_button.grid(row=0,
                                    column=3,
                                    rowspan=2,
                                    sticky="NSEW",
                                    padx=5)
        self.username_label.grid(row=2, column=0)
        self.username_entry.grid(row=2, column=1)
        self.username_button_edit.grid(row=2,
                                       column=2,
                                       columnspan=2,
                                       sticky="NSEW",
                                       padx=5,
                                       pady=5)
        self.room_label.grid(row=3, column=0, pady=(0, 10))
        self.room_entry.grid(row=3, column=1, pady=(0, 10))
        self.room_button_scan.grid(row=3,
                                   column=2,
                                   columnspan=2,
                                   sticky="NSEW",
                                   padx=5,
                                   pady=(0, 10))
        # Chat Field Pack
        self.scrollframe.pack(side="top", fill="both", expand=True)
        # Message Widget Grid
        self.message_label.grid(row=0, column=0, sticky="NSEW")
        self.message_text.grid(row=0, column=1, sticky="NSEW")
        self.message_button.grid(row=0, column=2, sticky="NSEW", padx=(10, 2))

    def connecting(self, room=None):
        try:
            username = bool(self.username_entry.get())
            if username:
                self.connection = ConnectServer(
                    username=self.username_entry.get(),
                    address=(self.address_entry.get(),
                             int(self.port_entry.get())),
                    room=room)
                self.connection.connect()
                self.connected()
                self.title(room)
                self.username_button_edit.config(state='normal')
                self.username_entry.config(state='disabled')
                self.room_button_scan.config(state='disabled')
                self.room_entry.delete(0, 'end')
                self.room_entry.insert(0, room)
                self.room_entry.config(state='disabled')
            else:
                messagebox.showwarning("Warning",
                                       "Please fill username field.")
        except Exception as e:
            messagebox.showerror("Error", str(e))

    def connected(self):
        try:
            self.room = threading.Thread(
                target=self.connection.receive_message,
                kwargs={
                    'window': self,
                })
            self.room.start()
        except:
            messagebox.showerror('error', 'Failed')

    def disconnect(self):
        if self.connection != None:
            self.connection.disconnect()
            self.connection = None
            self.room = None
            messagebox.showinfo("Success", "Disconnected from server.")
            self.address_entry.configure(state='normal')
            self.port_entry.configure(state='normal')
            self.connect_button.configure(state='normal', text='Connect')
            self.username_entry.config(state='normal')
            self.username_button_edit.config(state='disabled')
            self.room_entry.config(state='normal')
            self.room_button_scan.config(state='normal')
        else:
            messagebox.showinfo("Info", "Connect to a Server First.")

    def send(self, event=None):
        try:
            message = self.message_text.get()
            data = {
                'type': 'message',
                'username': self.username_entry.get(),
                'room': self.room_entry.get(),
                'message': message
            }
            if message:
                self.connection.send_message(data)
                self.message_text.delete(0, 'end')
                self.insert(json.dumps(data), 'e')
        except:
            messagebox.showerror("Error", "Please connect to server and room.")

    def insert(self, text, anchor):
        data = json.loads(text)
        if data['type'] == 'message':
            f = tk.Frame(self.scrollframe.viewPort,
                         width=25,
                         highlightbackground='#3daee9',
                         highlightthickness=1)
            f.pack(fill='x', side='top', expand=True, padx=5, pady=5)
            tk.ttk.Label(f,
                         text=data['username'],
                         anchor=anchor,
                         font=('helvetica', 7)).pack(fill='x')
            tk.ttk.Label(f, text='  ' + data['message'],
                         anchor=anchor).pack(fill='x')
            self.scrollframe.canvas.yview_moveto(1)
        elif data['type'] == 'respond_room':
            for room in data['rooms']:
                self.room_list.append(
                    tk.ttk.Button(self.scrollframe.viewPort,
                                  text=room,
                                  command=partial(self.connecting, room)))
            for room in self.room_list:
                room.pack()
            if self.is_join_room is False:
                self.connection.disconnect()
                self.connection = None
        elif data['type'] == 'error':
            messagebox.showerror('error', data['message'])
            self.connection.disconnect()
        elif data['type'] == 'success':
            self.clear()
            if self.room_list:
                for room in self.room_list:
                    room.pack_forget()
                self.room_list = []
            f = tk.Frame(self.scrollframe.viewPort,
                         width=25,
                         highlightbackground='#3daee9',
                         highlightthickness=1)
            f.pack(fill='x', side='top', expand=True, padx=5, pady=5)
            tk.ttk.Label(f, text=data['message'], anchor='n').pack(fill='x')
            self.scrollframe.canvas.yview_moveto(1)
            self.is_join_room = True
            self.address_entry.configure(state='disabled')
            self.port_entry.configure(state='disabled')
            self.connect_button.configure(state='disabled', text='Connected')

    def request_room(self):
        try:
            data = {
                'type': 'request_room',
                'username': self.username_entry.get()
            }
            if self.room_list:
                for x in self.room_list:
                    x.pack_forget()
                self.room_list = []
            if self.connection == None:
                self.connection = ConnectServer()
                self.connection.connect_socket.connect(
                    (self.address_entry.get(), int(self.port_entry.get())))
                self.connection.is_connect = True
                self.connected()
                self.connection.send_message(data)
            else:
                self.connection.send_message(data)
        except Exception as e:
            messagebox.showerror("Error", str(e))
            self.connection.disconnect()
            self.connection = None

    def clear(self):
        for widget in self.scrollframe.viewPort.winfo_children():
            widget.destroy()

    def sync(self):
        pass
Ejemplo n.º 33
0
 def __init__(self, raven: RavenClient):
     self.raven = variables.raven = raven
     self.width = 800 if sys.platform != "linux" else 825
     self.height = 425 if sys.platform != "linux" else 450
     # Initialize window
     ThemedTk.__init__(self)
     self.set_attributes()
     self.update_scaling()
     self.open_debug_window()
     self.finished = False
     variables.main_window = self
     self.style = ttk.Style()
     self.set_icon()
     self.set_variables()
     self.config_style()
     self.discord = DiscordClient()
     # Get the default path for CombatLogs and the Installation path
     self.default_path = variables.settings["parsing"]["path"]
     # Set window properties and create a splash screen from the splash_screen class
     self.withdraw()
     self.splash = BootSplash(self)
     self.splash.label_var.set("Building widgets...")
     self.protocol("WM_DELETE_WINDOW", self.exit)
     # Add a notebook widget with various tabs for the various functions
     self.notebook = ttk.Notebook(self, height=420, width=self.width)
     self.file_tab_frame = ttk.Frame(self.notebook)
     self.realtime_tab_frame = ttk.Frame(self.notebook)
     self.settings_tab_frame = ttk.Frame(self.notebook)
     self.characters_frame = CharactersFrame(self.notebook, self)
     self.file_select_frame = FileFrame(self.file_tab_frame, self)
     self.middle_frame = StatsFrame(self.file_tab_frame, self)
     self.ship_frame = ShipFrame(self.middle_frame.notebook)
     self.middle_frame.notebook.add(self.ship_frame, text="Ship")
     self.realtime_frame = RealTimeFrame(self.realtime_tab_frame, self)
     self.settings_frame = SettingsFrame(self.settings_tab_frame, self)
     self.builds_frame = BuildsFrame(self.notebook, self)
     self.toolsframe = ToolsFrame(self.notebook)
     self.strategies_frame = StrategiesFrame(self.notebook)
     self.chat_frame = ChatFrame(self.notebook, self)
     # Pack the frames and put their widgets into place
     self.grid_widgets()
     self.child_grid_widgets()
     # Add the frames to the Notebook
     self.setup_notebook()
     # Update the files in the file_select frame
     self.splash.label_var.set("Parsing files...")
     self.notebook.grid(column=0, row=0, padx=2, pady=2)
     self.file_select_frame.update_files()
     self.settings_frame.update_settings()
     # Check for updates
     self.splash.label_var.set("Checking for updates...")
     self.update()
     check_update()
     # Synchronize with Discord Bot Server
     if settings["sharing"]["enabled"] is True:
         self.splash.label_var.set("Synchronizing with Discord Bot Server...")
         self.update()
         self.discord.send_files(self)
     # Discord Rich Presence
     if settings["realtime"]["drp"] is True:
         self.rpc = Presence(436173115064713216)
         try:
             self.rpc.connect()
         except Exception:
             messagebox.showwarning("Error", "Discord Rich Presence failed to connect.")
             self.rpc = None
     else:
         self.rpc = None
     self.update_presence()
     # Give focus to the main window
     self.deiconify()
     self.finished = True
     self.splash.destroy()
     self.splash = None
class App:
    def __init__(self):
        self.root = ThemedTk()
        self.root.title("Daily Nasa Knowledge App")
        self.size = 400
        self.root.geometry("650x700")
        ttk.Style().theme_use("black")
        ttk.Style().configure("TButton",
                              font="OpenSans 9 bold",
                              anchor="center",
                              background="#47d1ff",
                              foreground="white")
        ttk.Style().configure("TFrame", relief="ridge")
        self.frames()
        self.labels()
        self.create_buttons()
        self.mainloop()

    def images(self):
        self.nasapicture = ImageTk.PhotoImage(file="nasapic.png")

    def frames(self):
        self.window_frame = ttk.Frame(self.root)
        self.window_frame.place(relheight=1, relwidth=1)
        self.buttons_frame = ttk.Frame(self.window_frame)
        self.buttons_frame.place(relx=0.015,
                                 rely=0.025,
                                 relheight=0.1,
                                 relwidth=0.97)
        self.picture_frame = ttk.Frame(self.window_frame)
        self.picture_frame.place(relx=0.18,
                                 rely=0.15,
                                 relheight=0.35,
                                 relwidth=0.65)
        self.text_frame = ttk.Frame(self.window_frame)
        self.text_frame.place(relx=0.015,
                              rely=0.528,
                              relheight=0.449,
                              relwidth=0.97)

    def labels(self):
        self.picture_label = ttk.Label(self.picture_frame, relief="ridge")
        self.picture_label.place(relx=0.01,
                                 rely=0.02,
                                 relheight=0.96,
                                 relwidth=0.98)
        self.text_label = ttk.Label(self.text_frame,
                                    relief="ridge",
                                    wraplength=615,
                                    font="OpenSans 10 bold",
                                    anchor="nw")
        self.text_label.place(relx=0.01,
                              rely=0.02,
                              relheight=0.96,
                              relwidth=0.98)

    def create_buttons(self):
        self.get_data = ttk.Button(self.buttons_frame,
                                   text="Get Information",
                                   command=lambda: self.get_astro_data())
        self.get_data.place(relx=0.01, rely=0.18, relheight=0.6, relwidth=0.19)
        self.save_data = ttk.Button(
            self.buttons_frame,
            text="Save Information",
            command=lambda: self.save_daily_nasa_information())
        self.save_data.place(relx=0.205,
                             rely=0.18,
                             relheight=0.6,
                             relwidth=0.19)
        self.download_image = ttk.Button(
            self.buttons_frame,
            text="Download Image",
            command=lambda: self.download_picture())
        self.download_image.place(relx=0.405,
                                  rely=0.18,
                                  relheight=0.6,
                                  relwidth=0.19)
        self.nasa_api = ttk.Button(self.buttons_frame,
                                   text="Nasa API",
                                   command=lambda: self.open_nasa_api())
        self.nasa_api.place(relx=0.605,
                            rely=0.18,
                            relheight=0.6,
                            relwidth=0.19)
        self.about_ = ttk.Button(self.buttons_frame, text="About")
        self.about_.place(relx=0.8, rely=0.18, relheight=0.6, relwidth=0.19)

    def open_nasa_api(self):
        website = "https://api.nasa.gov/"
        webbrowser.open_new_tab('%s' % website)

    def save_daily_nasa_information(self):
        Nasa_dailyinfo = "https://api.nasa.gov/planetary/apod?api_key=93IbCsql4yIRiHnSej8MEZ8BvMUr0oS4sK7k6mTC"
        r = requests.get(Nasa_dailyinfo).json()
        with open("dailynasa.txt", 'a') as f:
            f.write("Date: " + r["date"] + " " + "Title: " + r["title"] +
                    "\n" + "Explanation: " + r["explanation"])
            f.write('\n')
            f.close()

    def download_picture(self):
        Nasa_dailyinfo = "https://api.nasa.gov/planetary/apod?api_key=93IbCsql4yIRiHnSej8MEZ8BvMUr0oS4sK7k6mTC"
        r = requests.get(Nasa_dailyinfo).json()
        self.picture = r["hdurl"]
        webbrowser.open_new_tab('%s' % self.picture)
        urllib.request.urlretrieve(self.picture, r["title"] + ".png")

    def get_astro_data(self):
        Nasa_dailyinfo = "https://api.nasa.gov/planetary/apod?api_key=93IbCsql4yIRiHnSej8MEZ8BvMUr0oS4sK7k6mTC"
        r = requests.get(Nasa_dailyinfo).json()
        self.picture = r["hdurl"]
        urllib.request.urlretrieve(self.picture, "DailyNasaPicture.png")
        self.text_label.configure(text="Date: " + r["date"] + " " + "Title: " +
                                  r["title"] + "\n" + "Explanation: " +
                                  r["explanation"])
        self.image = ImageTk.PhotoImage(
            Image.open("DailyNasaPicture.png").resize((425, 250)))
        self.picture_label.configure(image=self.image)

    def mainloop(self):
        self.root.mainloop()