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

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

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

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

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

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

        # Canvas
        canvas = Canvas(self.parent)
        self.canvas = canvas
        for i in range(15):
            for j in range(15):
                fillcolor = "gray80"
                self.canvas.create_rectangle(10+20*j,     10+20*i,
                                             10+20*(j+1), 10+20*(i+1),
                                             fill=fillcolor,
                                             tags="{},{}".format(i, j)
                )
        self.canvas.bind("<ButtonPress-1>", self.onClick)
        canvas.grid(row=1, columnspan=5, sticky=W+E+N+S)
        self.parent.grid_rowconfigure(1, weight=1)
Ejemplo n.º 2
0
def add_menubar( root ):
	menubar = Menu(root)

	#file menu
	filemenu = Menu(menubar, tearoff=0)
	# filemenu.add_command( label="Load project", command=build_in_progress )
	# filemenu.add_command( label="Save project", command=build_in_progress )
	filemenu.add_separator()
	filemenu.add_command( label="Exit", command=root.quit )

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

	#view menu
	viewmenu = Menu(menubar, tearoff=0)
	viewmenu.add_command( label="Progress", command=root.progress )
	viewmenu.add_command( label="Workflow", command=root.workflow )

	menubar.add_cascade( label="View", menu=viewmenu )

	#help menu
	helpmenu = Menu(menubar, tearoff=0)
	helpmenu.add_command( label="Help", command=build_in_progress )
	helpmenu.add_separator()
	helpmenu.add_command( label="About", command=about )

	menubar.add_cascade(label="Help", menu=helpmenu )
	
	root.config( menu=menubar )
Ejemplo n.º 3
0
 def __init__(self, master=None):
     Frame.__init__(self, master)
     self.pack(expand=1, fill='both')
     self.master.geometry('1440x900')
     paned_window = PanedWindow(self)
     self.treeview_kspelements = TreeviewKSPElements(self)
     self.treeview_kspobjects = TreeviewKSPObjects(self)
     paned_window.pack(expand=1, fill='both')
     paned_window.add(self.treeview_kspelements)
     paned_window.add(self.treeview_kspobjects)
     
     menubar = Menu(self)
     
     filemenu = Menu(self)
     filemenu.add_command(label='Open', command=self._open)
     filemenu.add_command(label='Save', command=self._save)
     filemenu.add_command(label='Save As', command=self._save_as)
     filemenu.add_separator()
     filemenu.add_command(label='Exit', command=self.master.destroy)
     menubar.add_cascade(menu=filemenu, label='File')
     
     insertmenu = Menu(self)
     insertmenu.add_command(label='KSP Element', command=self._insert_element, state='disabled')
     insertmenu.add_command(label='KSP Object', command=self._insert_object)
     menubar.add_cascade(menu=insertmenu, label='Insert')
     self.master.config(menu=menubar)
Ejemplo n.º 4
0
 def setupMenubar(self, root):
   menubar = Menu(root)
   filemenu = Menu(menubar, tearoff=0)
   filemenu.add_command(label="New", command=donothing(root))
   filemenu.add_command(label="Open", command=donothing(root))
   filemenu.add_command(label="Save", command=donothing(root))
   filemenu.add_command(label="Save as...", command=donothing(root))
   filemenu.add_command(label="Close", command=donothing(root))
   
   filemenu.add_separator()
   
   filemenu.add_command(label="Exit", command=root.quit)
   menubar.add_cascade(label="File", menu=filemenu)
   editmenu = Menu(menubar, tearoff=0)
   editmenu.add_command(label="Undo", command=donothing(root))
   
   editmenu.add_separator()
   
   editmenu.add_command(label="Cut", command=donothing(root))
   editmenu.add_command(label="Copy", command=donothing(root))
   editmenu.add_command(label="Paste", command=donothing(root))
   editmenu.add_command(label="Delete", command=donothing(root))
   editmenu.add_command(label="Select All", command=donothing(root))
   
   menubar.add_cascade(label="Edit", menu=editmenu)
   helpmenu = Menu(menubar, tearoff=0)
   helpmenu.add_command(label="Help Index", command=donothing(root))
   helpmenu.add_command(label="About...", command=donothing(root))
   menubar.add_cascade(label="Help", menu=helpmenu)
   
   root.config(menu=menubar)
   root.mainloop() 
Ejemplo n.º 5
0
    def handle_button_click(self, event):

        val = self.button_selected.get() - 1
        val = self.radio_buttons.index(event.widget)
        if event.state & 0x001:  # Shift key down
            self.x_flipped[val] = not self.x_flipped[val]
            try:
                raise IOError
                image_file = imget(self.img_lists[val][self.images_selected[val]])
                import_image = Image.open(image_file)
            except IOError:
                image_file = imget_bdgp(self.img_lists[val][self.images_selected[val]])
                import_image = Image.open(image_file)
                import_image = import_image.resize((180,80), Image.ANTIALIAS)
            import_image = import_image.rotate(180*self.x_flipped[val])
            embryo_image = ImageTk.PhotoImage(import_image)
            label = Label(image=embryo_image)
            label.image = embryo_image
            self.radio_buttons[val].configure(
                #text=image_file,
                image=label.image,
            )
        elif event.state & 0x004: # Control key down
            popup = Menu(root, tearoff=0)
            popup.add_command(label=self.radio_buttons[val].cget('text'))
            popup.add_separator()
            popup.add_command(label="Invert X")
            popup.add_command(label="Invert Y")
            try:
                popup.tk_popup(event.x_root, event.y_root, 0)
            finally:
                # make sure to release the grab (Tk 8.0a1 only)
                popup.grab_release()

        elif val >= 0:
            self.images_selected[val] = ((self.images_selected[val] + 2*event.num
                                         - 3) %
                                         len(self.img_lists[val]))
            self.x_flipped[val] = False
            if self.images_selected[val] == 0:
                stdout.write('\a')
                stdout.flush()

            try:
                raise IOError
                image_file = imget(self.img_lists[val][self.images_selected[val]])
                import_image = Image.open(image_file)
            except IOError:
                image_file = imget_bdgp(self.img_lists[val][self.images_selected[val]])
                import_image = Image.open(image_file)
                import_image = import_image.resize((180,80), Image.ANTIALIAS)
            embryo_image = ImageTk.PhotoImage(import_image)
            label = Label(image=embryo_image)
            label.image = embryo_image
            self.radio_buttons[val].configure(
                #text=image_file,
                image=label.image,
            )
            self.image_files[val] = image_file
        self.button_selected.set(-1)
Ejemplo n.º 6
0
class FrontEnd(Frame):
    def __init__(self, master, version):
        Frame.__init__(self, master)
        master.title(version[:-5])
        # MAKE IT LOOK GOOD
        style = Style()
        style.configure("atitle.TLabel", font="tkDefaultFont 12 bold italic")

        # CREATE AND SET VARIABLES
        self.version = version
        self.description = None
        self.logo = None
        self.status_lbl = StringVar()  # TO HOLD STATUS VARIABLE IN STATUSBAR

        # CREATE ROOT MENUBAR
        menubar = Menu(self.master)
        self.master["menu"] = menubar
        self.master.option_add("*tearOff", False)
        # CREATE FILE MENU
        self.menu_file = Menu(menubar, name="file")
        self.menu_file.add_separator()
        self.menu_file.add_command(label="Exit", accelerator="Alt-F4", command=self.master.destroy)
        menubar.add_cascade(menu=self.menu_file, label="File", underline=0)
        # CREATE HELP MENU
        menu_help = Menu(menubar, name="help")
        menu_help.add_command(label="About", command=self.show_about)
        menubar.add_cascade(menu=menu_help, label="Help", underline=0)

        # CREATE BUTTON BAR
        self.button_bar = Frame(self.master, relief="groove", padding="0 1 0 2")
        self.button_bar.grid(sticky="ew")

        # SETUP PRIMARY FRAME FOR WIDGETS
        self.frame = Frame(self.master, padding="25")
        self.frame.grid(sticky="nsew")

        # CREATE STATUS BAR
        Separator(self.master).grid(row=8, sticky="ew")
        self.status_bar = Frame(self.master, padding="8 0 0 1")
        self.status_bar.grid(row=9, sticky="ews")
        Label(self.status_bar, textvariable=self.status_lbl).grid(row=0, column=0, padx="0 7")
        Label(self.status_bar, text=self.version[-5:]).grid(row=0, column=8)
        Sizegrip(self.status_bar).grid(row=0, column=9, sticky="e")

        # CONFIGURE AUTO-RESIZING
        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(1, weight=1)
        self.frame.columnconfigure(0, weight=1)
        # self.frame.rowconfigure(0, weight=1)
        self.status_bar.columnconfigure(1, weight=1)

    def show_about(self):
        about = About(self.master, "About {}".format(self.version[:-5]), self.logo)
        Label(about.frame, text=self.version, style="atitle.TLabel").grid(sticky="w")
        Label(about.frame, text="Developer:  Joel W. Dafoe").grid(pady="6", sticky="w")
        link = Link(about.frame, text="http://cyberdatx.com", foreground="blue", cursor="hand2")
        link.grid(sticky="w")
        link.bind("<Button-1>", lambda e: webbrowser.open("http://cyberdatx.com"))
        Label(about.frame, text=self.description, wraplength=292).grid(columnspan=2, pady=6, sticky=W)
Ejemplo n.º 7
0
    def add_menus(self):
        menu_bar = Menu(self.root)
        stampede_menu = Menu(menu_bar, tearoff=0)
        stampede_menu.add_command(label="Settings", command=self.edit_default_settings)
        stampede_menu.add_separator()
        stampede_menu.add_command(label="Quit", command=self.root.quit)
        menu_bar.add_cascade(label="Stampede", menu=stampede_menu)

        self.root.config(menu=menu_bar)
Ejemplo n.º 8
0
	def modify_command(self, file_name):
		import tkinter as tk
		from tkinter import Menu
		from tkinter import messagebox
		import tkinter.scrolledtext as tkst
		import os.path
		if os.path.isfile(file_name):
			file = open(file_name, 'r')
			read_text = file.readlines()
			file_text = ''
			for line in read_text:
				file_text = file_text + line
			file.close()
		else:
			file_text = ''
		win = tk.Tk()
		win.title(file_name)
		frame1 = tk.Frame(
			master = win,
			bg = '#808000'
		)
		global editArea
		editArea = tkst.ScrolledText(
			master = frame1,
			wrap = tk.WORD,
			width = 20,
			height = 10
		)
		def save_command():
			global editArea
			file = open(file_name, 'w')
			data = editArea.get('1.0', 'end-1c')
			file.write(data)
			file.close()
		def not_save_exit_command():
			if messagebox.askokcancel("Quit", "(Not Save) Do you really want to quit?"):
				win.destroy()			
		def exit_command():
			global editArea
			file = open(file_name, 'w')
			data = editArea.get('1.0', 'end-1c')
			file.write(data)
			file.close()
			if messagebox.askokcancel("Quit", "Do you really want to quit?"):
				win.destroy()
		frame1.pack(fill='both', expand='yes')
		menu = Menu(win)
		win.config(menu=menu)
		filemenu = Menu(menu)
		menu.add_cascade(label='File', menu=filemenu)
		filemenu.add_command(label='Save', command=save_command)
		filemenu.add_command(label='Not Save and Exit', command=not_save_exit_command)
		filemenu.add_separator()
		filemenu.add_command(label='Save and Exit', command=exit_command)
		editArea.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
		editArea.insert(tk.INSERT, file_text)
		win.mainloop()
Ejemplo n.º 9
0
    def __init__(self, root, config_save):
        self.root = root
        self.config_save = config_save

        # Create a menu
        root_menu = Menu(root)
        root.config(menu=root_menu)

        xnat_menu = Menu(root_menu)
        root_menu.add_cascade(label="GIFT-Cloud", menu=xnat_menu)

        xnat_menu.add_command(label="About", command=self.menu_about)
        xnat_menu.add_separator()
        xnat_menu.add_command(label="Settings", command=self.menu_settings)
        xnat_menu.add_separator()
        xnat_menu.add_command(label="Quit", command=self.menu_exit)
Ejemplo n.º 10
0
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         


        if not os.path.exists(self.WORK_FILE):
            os.makedirs(self.WORK_DIR)
            self.simulateReboot(True)




        self.parent = parent

        menu = Menu(self.parent)
        menu1 = Menu(menu,tearoff=0)
        menu1.add_command(label="Simulate Reboot",command=self.simulateReboot)
        menu1.add_separator()
        menu1.add_command(label="Quit!", command=self.parent.quit)
        menu.add_cascade(label="Menu",menu=menu1)

        # display the menu
        self.parent.config(menu=menu)

        self.parent.title("GPIOSim")        
        self.pack(fill=BOTH, expand=1)

        self.canvas = None
        self.canvas = Canvas(self, bg=self.BG_COLOR) 
        #self.canvas.bind("<Button-1>",self.click)


        #Images (gif base64 encoded)
        imgInLeft = "R0lGODlhHgASAOf7AAoMCAITBBcQCAYbAAsaEBUYEBEaCRMeCB0ZIREhGRkhFB0gEyMmGiIpFy8mNTQyNiROCCJZACxYCTlUKzpWGyleADBeBjRdGCxiCShlAEFcM0BeKDJmAzpmBCFwADxlIBt1BC9yBGpZW0NpMTtvDzttKkdqPid8AENxHD12DDh5AE9tPEZyJUV2Lzh/AF5rYD5+CEV+Fz+AGFxzT1h4LUx9NUaEAkCGA2dxYUqCEF91V1V8ME+AG0WHADuKCFl/RU+IIT2PG2l8XkqPAEuMJFmFREWTBVCRDzGcAHl6g2yBaEuWADybAEKZDkaaAHCHYnaCgneEeFCcA2WPR0ChB1qaA1ebFnuIbk2gCkSlAFCiAFegAF6fAFehD3ORXmueEXOWT26aQU+qBnCZV1inF3yUboCRhWWmBlmqCnuYa2OqAGGqDGOnJVevAF6tAEi0AG2sAF2vIYyXhomado2Ze1S2BmOyBHKpO1e3AGqxBVy1B1q0GXKwAG6sNEm9AH2tB3WrNYmfc22zAHumX2K4AH+maWO0NW61D2m4En60AHK4AGy6AHm3AIW0AHW2IYKsYoSrbnuzPW22S2u7JXS3NpKzBmDAG5CyGW66OI2ph3G7MIuyP4mteou5AHu/AIOzYXa7QpSpnKajqHu8M4O/AIG+EZy4AHe/K4m+AJytdZW8AIO4XnDCNp+ug429KaGrppG4YX+8dHzDUZnAHZ3CAJ/AJo7FK5O+c5+7cp7CP5jKJ5bIQpvAhqi8ia+6lYfLZ5PPHZrFbKHNDK/HVqnJcqHRPqDSTLvDq7TTN7jGubTLnMbRO8DTQ8TGw7DSjb/UVLDSmMTTZ7rYXbjWeMvVVNPSX8jZQbnfOMjYYcfbU7Xeb9XaTs/abt7XcMLjUMXhe8fficvbwdzV4czncNnb2NThwcnkztXlt+nr6OXy2Ozx9PLx6OP34vnv9e306fzx/vP35vL3+ff2/v/3/fj69//58v/76//6+PH/8/L///799P78//j/9Pb/+vn+//3//CH+EUNyZWF0ZWQgd2l0aCBHSU1QACwAAAAAHgASAAAI/gCJATpFKRIrTM5+YYpEadIoUNBkadLUJ5KhVfDe9cO3b58/doaodEGj5gwaYneQiDmzxgqmW0yy7LHjpgsmd/9y/rs37xwbNdeWIePSB1cXRtuY6VqyKlgVRtaWAXMSC96+fvb0+ZvnDMsfatmKSZF0a4iibNlqMRkEy4grsJua8Lq37x8/fzl5GXE0TtouJJA4IbHV7RmiJp8+MSlWzZuiI8o6/qs7790gJ666YbPVoxeYIbnGRUOUI1WYL7OE0UJDJNy+e/T2xe4HZMkwbtwsgYBGhIyxarXcBOEEBI0qU6SWhEnXzh8/ffvipduBZRq4b2tI+OKxJZEqT06m/hS6kQdVpUQ9xtDj19Gev33lUMTRFm2WlhqZYsAh1anRkDFp3IDHcYec8Mhk/8ADnTkpYHHJJYs4QUMgMnDRCCqL2OCFFzeo0UgnioQwh0f+6KOPOiMYIQiIYnDQCgtPNaJIE0WUQQIXiZRyiAtTrHOPP/nc888KMORBiiB2VBCKCUPkwYgnW5RgRgld8JFIHka0EE49WnWkRAiI5AEHGhnQoYMKbthxiBYdXPGDD3YgWQULydRFD3SvYIAGIWq4oYIQV2QQJx56cIBDGR4sogYhaJAgR0d40XOMBF3ogYYdPawQhQRouKGGHiHoYEYEe7iRRxsWPDFZR/uIs8EQY2KssYYTGkBxgRRdtFFHCjMkAUEbbVzqwQsK5nSPPBvAUMcbeFgRwQsfDFEHHnbkQAEOt77hRxspTICOTjmJIMACCSRgQAEPOAAAAQQEMMABDCAwbgEKHNCAKM2QQw469PwTEAA7"
        imgInRight = "R0lGODlhHgASAOf8ABcOChASDwkZDg8YBxcZCw8dDicUJhcdABkfCxgmBBApABwnDi4kLCsnJjJHICNUBCZUACxdBC5fAD5XKTFgEiRmATZeLUVcOTpiJDhnGStuADZrDzxpFEZlLjVvATxuASl0ADpyAEhpODtzGUxrQEpwHUlwJDp6AVFsXlVwLUp0Ll9rXTaACF5uSzOEADuCAFpzTFJ5LWprdEx+HEWEEkiGBVh3bkaGEzWNADyMClh/PD+NAEeMAESKJjiSEk2MG2GAWVGMLTmYAFqJOkOXAFmKQXCBXUqWAHd8fkmWC22EX1KWDk+aAE2aE0edFUqeBHuEf3iJfEmkAFCiAF6dE1ihAF+gAHmQXkynAGeaPEWqAn2OfHWSbmKfOH+Sc16nBViqCU2vAFCsG4STe2KqAGeoC1SuD2KnLnedVYCXfWynHF6uAFiwAHCpEIaXhWeuAHOrAHmhUmOtII6YdVS1BWavFVa2AIOea2mqQoGgZnCvBGSzB3mvAH+uAGyzC1O8AGuwOG+1AGm3AHGyKGS6AIOyAHm2AG26AHuwOo2jiWm2PHS6Ani3FXa1NYKsa3a3I4G4BX+3GJmjkm65N421BpCpeW69GnG6MIGxX3O7Jma/KJS1C3q+AHm4SG7DAIq7AI63I5W3IHO/QYS2aoO+IZW8AIG6Une9YH3DFnjCN4+6W6CvlpqxlqC/AJvBAJC7ZpbDDYvHDpK8cZe4jpq7a6DBIJ26dbK+JIvIN4vJLpzELprEN4jGd57EUbW4lZbGc6bJPpzIaJnJdpzLXaPMQL7KMqjJjJHVcKvOl7zIsLbNnrfUWsrOYbLQoMXWNMbUTsbVV8vWQNDTVLbZc7/aUcXaQdXOjbnfOMrMycHaWbfeaL/hZcfkNsffbdPfUd/bcMHld9XW4NnjdN/c4dHjxdzfz8ztf+Di38vvtvXm9enr6Oby3/Py6ev26vzz7Or63/b0+Pb2//f61e/76Pb49P/1++77/Pb7/vn/4Pf+8/X/+v/8+/78///+9fn///3/+yH+EUNyZWF0ZWQgd2l0aCBHSU1QACwAAAAAHgASAAAI/gD55fvH7969d50aTRp0yZKqZqIUZboE6FEwZJoUNWI46Vi/ffTu8ZOH6AmZOmDCOOGVSooaPV+0nPklpswaMmuedMGXr94/ffReHcnF7VkkJrRMVanlrNqiJsLOkCkW7VqZM+j+iYTXz1aOTNCi7eLxStURXNKqRUoiCw8WYNCktWnSbF8/fvT+KUvyaJs3YEJOYSJiiVo2UDgcYRKyC9o2Rkl43fP5k9yPKaVuwaKSZRSNMt3EEWuCxlYNUsy+4eIRJx+/ePfcvQvCJFarUmSCVPoBRhe0YVR6GHNRxxy4XkSKzOMHTx/zPDkMtfq0h8adLkcguaJkxYcvD3LA/lmbhmXGun/7/vX754iFn1Kl9rC4gmbHok2G1syoFAMLqmXa1PEBOesZxM8/c4DgSR+UrPECF1fwQEghlIDBQiIlMHFIKKA8McI5BxJ0YDpDuMBIH5xUMYIXOjwRCCWLPGHCLBJ8YUghhyTRgT30fESPa+WYsMQhehjChAppYPAFJ3r4sQMJrECwhiF8vHEECT3x048++eyTzAZMvBGIIDXoEEUGUwQCByEhAJHGB3vooUcYHijBj5b6/KOVGxx8cZMfGnixggdrBLLGGhVsscIJYfjhBxgcSJKXSAYascEea4BhhgRjwEDoGmyAEUEUIuQAxhtsNEFBMiL1E5I+ZOy0UAEddIBBxgNIwPBCSnUcEQEUFzTBxrA1TBDOnXqKxI4DKbBhBx1rPGCDBTXQEQYdS1iAAgRVhPEHGyxg0M6B6owTDjarKJBAAQIgAIABDBwwALsEAMBAAwsQcEACCwQgQ0AAOw=="

        imgOutLeft = "R0lGODlhHgASAOf7AAgiSgYlPA8nNQYrLRUnOhovUxwwRB0yNgA2eiIzPyoxQgA2jh46TR85Wik9Vz44TBM/jARElgdEnSI/gRFEihhEfipBcgBIrQBLpBBFtwBOmhZLkSlJeQBSnABUpQBWrghTxABWwyNPpCBTjRZXlxpWowdZvxRXtABetyVYjBdWzxdbpABgvwBd4ABd5wBg2wRjyhpevwRj0BpexSlawxtc2TFbpBtd0wBk5TFdnwplxQxk2QBn4ThfjxNk6ABtzABs2QBr5gBq9BNrtABr7RhozwFt4jlloU5kdB1o3kllhQpv3QBy3i9rnABz2QBy5Uxjohdwww5x2A9v6wB3zwB070NqjgF5xAB26gB34zRtrgB50QB1/wB74R504wZ76DBv7mVpjwB+6gp77yF16k1vp0NwwQB+/wCC7jx0ygCC9kd2pmJwoCt9w092og6D6lp2lx5/9R6A71N2tgSJ6CB//AiG/z961BaH4E940Fl6oACL/j994COH2j2Bz06AqiaG5gCQ9QCS4xiK+DOG0zaE30CA7gCS/1GBxW5/kwGW9R+O9R+P71GD222BpV6GoAeY8GaFmkmKvzOM7TKP4mCLsACh+TGV4Red74CGqVSQzUiT1TGX+EuS3nyLqlqS1nqOshOn6zOe6nCTqGGUzGWVwSel8EOe5XCVvGiV23GWt0yb/3OWy3WW4kqj62+frHyZyG+e3oaduiiz/nGj0o+bzoKe4Tiz8Uqt+3ai6UWx6mOq+6ehrGGx7IGp5DS+/Ea5/5Wo7pSsyl656kO//zrG4j/F6H2z5V27/DzG/VTB85uyw4G411HH/5a52KW5uH7A/2nN81HV/6jA0nTL/2fQ/2PU+X7P8ZjO4JTN+bzL36fQ7LjL8rDQ4MfNz9HUxNvX0sfj7tLo+N7m7+Tp7OTw5/Px9fL08dr7/vj07Pzy+fv14O73//H3+fr18+P+6P/19u387//2/Pj69/X88fD9/u3/+P/92v/6+fT++f/87f77//j9//j/7v7+9Pz/+yH+EUNyZWF0ZWQgd2l0aCBHSU1QACwAAAAAHgASAAAI/gDzpcM375+8d50GFbpD6dKmbX4MTWrDCE+uYIAA+QFEiRCzfPz87Ztnr1GRJ3WY8MDhyxARI1Kk4ACTa4oUKmdcvODD7hzIf/VouViU7NelGL0+oRCVjBidFrTaOPllbNaYNOL2/RPZz5mKQrqamTLRatOLU9KKyTFxLE+UW8qIXYnC7V7Ifeu6oYjTzBouE6lKgcA0TJooFbbm4MDUDFmdFs7a+VNXz1y5E0AghcKEIw8pHV+oVVsVQlOpF5eiUbsUopW+fPH08UOn5cUgS5CMFIE1REgoV8BmmImlow+0a51gSDo3st6+dH92iBmkKIsJVHNuLFKkCIgWWTGu/mTDtquFlnL89vXTSurEmEGHvnhQhSjEF0GQiNBANeQHp2HIZNGEOPKEhI859QizwBd0MDJGDGvAkkEdgtAxxQeVlFHDFm/Y8cMK4cDzDz3/8NOOOqx4sEUgYwBRghuasCBGF3ssUUItIkhhxxNo6NCEOfT4ww8/BrFjhQdYoPEFFiuM0sMOdnThxQ45vOIBEHiokUUISuTDXD5C+jPOESZ4oUYVMNiQyQZGvEGFGhc8kogEWXxRxRga6KHVOf/Y484+2pAAAxlfZAECFJ5Q8IQaTnCRQSSOXIBFFUt0cQEo6ezTjj377JPPMhTI8MUSQHzghioLtCCHEEJEkAgbdhegMQUQVUAwDZHp4ePPP6BIwIMQVTixQRiZaEDEFlm80EEkSnwgxBNAyFDBN/NoNY9I/CAxwQtGEIEDAnBw0MEORAghwwhKVMBCEEkAgUEK42hFDjjgePOMBQ0ckEABBOgbAAACDDAAAQ8owIABBDjQgAO8BAQAOw=="

        imgOutRight = "R0lGODlhHgASAOf7AAsjMAklQQYnOA8lNxAnPyAoOBosNRowPhUyRAoyfic1OgA4kRw3WCo3RABAmTA9SgNDoydAWRZBiABHnwBGsgtHjRtCkCxCYSREeQBJvgFOoAFNrRZIqQROpx5LeQ5OmgBQvSBQlwBWvRJVlQBWygRZuDBSfAVarAJX0wBbyB1YpQ5btQBd0Q1Z1SdYkwBhuQBhxwBf2xdcywBh4wJi1xhevjRcjBpexSRfnwhlxRtirgBnzB5e1DFfmx9itgBm7yhjnRFowSlmmgBr5hZl4gBs4ABr7SBpowBu1Bhn1Rhozxhn3EpkbUNjjhdsuABu6ABw4gBy0Ddolwpv3QBw8QBy3ght+FRjgCBp5gBx+Q5v5ABz7RBv7DxskgB36wB45RVz2gB64FJoqU1smAR82wB+1Rt21gB94T9wuWFqlAp69gB/6wCA5Td0vAB/+QCA80l1mRN960tytxN/3xZ98ih56DZ51TZ6zwCI5y559x2B6GF1mAaI7gWM3QCM8U55yyCF3i6D0DOA4gCP6iKH2hOI/TGD1xKJ90GCt1x8pmV8mUCB1wCR9ymH6E+Bv1d/vnB8lACV7GKBnC6I8DyH4z6H6l2CyAyX9gCb+TSO6T6N2yOU5m+Go0CQ2ACg+FOM0HeGpEuO13SHq2qLsjOY5X2Jol6Qy3mMpGePwhek4R+g8jKb7nKRrW6SsyKk7GKUz0aZ9Teg7XeU1nGYxUeh6HOax3qYx4SbuGue63ygtW6h2YOfwjOx/Xqg4W2m0ZmdrECx94qf0GKq4GCs74enw0y084Gn8GGx7Di9/4Kq5kq850W/9jzD842v5Ve/+WK891q+/4a240HJ/5a2xYu52VvG+Ke9r6y7zm3K/qW921fR/3jI/mXO/2zN+pLL95TP573J16vP2MfJxqrO69XZyNfZ1s/l7s/s6eDp8ejq59/v9uzx9Pbz+OT67P307ev4///09fb2//D69P32///2/Pb98vH+//r8+f/7+f/+4fX/+v78//j+///+7//+9f3//CH+EUNyZWF0ZWQgd2l0aCBHSU1QACwAAAAAHgASAAAI/gCjCcpESRAgQ82MUcJDiFKlQOM6acpkp9KkT/Lu7fOHb5++d4tazIhTBowRXHViaAEzxQglYzyMTKmzhUYlffs26uPn79ydLbyYIdMSyJcSPcikuYJhSliOPsykbUoyy94+fvXY7cs3LkgZaMuARfmTrAYfZdpi0QiFC4YqacUayaBWb9+/f/T+scsmI8+zaqtmWOrFglS3Z5FQoHpFAhg3Z3RKhOs3758/fpZlFebWTVWKWq9S0OKGrc6NWn+IeErFqIgPcxr9Xd0XD1EOWN22EVqhq00SXsBcUXEyKwkST57wxECjjt/Vuv/aoYkx7Ju3Lyt2HRnCB9MgGnJa/onYEumSHhKO5OHFtxMfOiFmnh1jhOSILR1GLvV5g35WhzOMHBKZKRr9I88+7phzAhKF4AEIC3KMsoEWjEQSRwa2wMFDGIMw4oUDxFylzz/4rCMFDHp4UQgSHwTzAXd8rAHDI4mcAEUcfpzRASo5jfhPPU2I8AUbeBQxQS42LPEGHl8kgQMrKjwxxxterNDFO3nhgw8/kmiwhRtrDKEBJ4ls8AUZYSwRQik97BBHHGqIAIQ6svGDjzu3mBlGFk9swIkiFGThRRhaVCCKGCKEwcYWLLgAzj7w/MPPPddYUAQUVXjBwR6QTDCEFWpMsQArY4BQRKZKVDCNbB7xQw4GaDyAocUPL3QhSQVFIBFGERCAksYHslqBhQOn6MMqP+uYsMETRgyRgwRXjFADFkbQoIEHiiSwRBFFEOEAE/f8c0+4//wSQQQPHIAAAg80MIAAAAwQAAENGEAAAwUowMAF1ohTTjnphBsQADs="
        self.phInLeft = PhotoImage(data=bytes(imgInLeft, 'latin1'))
        self.phInRight = PhotoImage(data=bytes(imgInRight, 'latin1'))
        self.phOutLeft = PhotoImage(data=bytes(imgOutLeft, 'latin1'))
        self.phOutRight = PhotoImage(data=bytes(imgOutRight, 'latin1'))

        self.updateUI()
Ejemplo n.º 11
0
    def initUI(self):
        self.parent.title("Submenu")

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)

        submenu = Menu(fileMenu)
        submenu.add_command(label="New Feed")
        submenu.add_command(label="Bookmarks")
        submenu.add_command(label="Mail")
        fileMenu.add_cascade(label="Import", menu=submenu, underline=0)

        fileMenu.add_separator()

        fileMenu.add_command(label="Exit", underline=0, command=self.onExit)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)
Ejemplo n.º 12
0
 def createMenu(self):
     menu = Menu(self)
     self.config(menu=menu)
     #File
     mnFile = Menu(menu, tearoff=0)
     menu.add_cascade(label=_("File"), underline=0, menu=mnFile)
     mnFile.add_command(label=_("New..."), underline=0, command=lambda cmd='NEW':  self.onCommand(cmd))
     mnFile.add_command(label=_("Open..."), underline=0, command=lambda cmd='OPEN': self.onCommand(cmd))
     mnFile.add_separator()
     mnFile.add_command(label=_("Quit"), underline=0, command=lambda cmd='EXIT': self.onCommand(cmd))
     #View
     self.mnView = Menu(menu, tearoff=0)
     menu.add_cascade(label=_("View"), underline=0, menu=self.mnView)
     self.mnView.add_command(label=_("Tables at %s") % _('right'), underline=0, command=lambda cmd='TABLES_RL': self.onCommand(cmd))
     #Help
     mnHelp = Menu(menu, tearoff=0)
     menu.add_cascade(label=_("Help"), underline=0, menu=mnHelp)
     mnHelp.add_command(label=_("SQL by SQLite..."), underline=0, command=lambda: webbrowser.open(self.sqlSqliteUrl))
     mnHelp.add_command(label=_("About..."), underline=0, command=lambda cmd='ABOUT': self.onCommand(cmd))
Ejemplo n.º 13
0
class Interface(object):
    window = None
    text_pad = None
    menu = None
    file_menu = None

    def initialise_window(self):
        self.window = tkinter.Tk()
        self.window.wm_title(TITLE)
        self.window.geometry(WINDOW_SIZE)

        # add typing area
        self.text_pad = scrolledtext.ScrolledText(self.window, width=WINDOW_WIDTH, height=WINDOW_HEIGHT)

        self.add_options()
        self.text_pad.pack()
        self.window.mainloop()

    def add_options(self):
        self.menu = Menu(self.window)
        self.window.config(menu=self.menu)

        self.file_menu = Menu(self.window)
        self.options_menu = Menu(self.window)
        self.about_menu = Menu(self.window)

        # file filter menu
        self.menu.add_cascade(label="File", menu=self.file_menu)
        self.file_menu.add_command(label="New", command=self.dummy_action)
        self.file_menu.add_command(label="Open", command=self.dummy_action)
        self.file_menu.add_command(label="Save", command=self.dummy_action)
        self.file_menu.add_command(label="Save As...", command=self.dummy_action)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit", command=self.dummy_action)

        # option menu
        self.menu.add_cascade(label="Options", menu=self.options_menu)

        # about menu
        self.menu.add_cascade(label="About", menu=self.about_menu)

    def dummy_action(self):
        print(self.__class__.__name__ + " invoked")
Ejemplo n.º 14
0
class TopMenuBar(Menu):
    def __init__(self, parent):
        Menu.__init__(self, parent)
        self.parent = parent
        self.newmenu = Menu(self)
        self.showmenu = Menu(self)
        self.added_buttons = []
        self.newmenu.add_command(label="NPC", command=self.parent.onNew)
        self.newmenu.add_separator()
        self.newmenu.add_command(label="Save", command=self.parent.save)
        self.newmenu.add_command(label="Load", command=self.parent.load)
        self.showmenu.add_command(label="Info", command=self.parent.get_info)
        self.showmenu.add_command(label="Save Image", command=self.parent.save_image)
        self.newmenu.add_separator()
        self.showmenu.add_separator()
        self.add_cascade(label="New", menu=self.newmenu)
        self.add_cascade(label="Show", menu=self.showmenu)
        self.add_command(label="Exit", command=self.parent.quit)

    def add_button(self, menu, name, call):
        func = partial(call, name)
        if menu == "new":
            self.newmenu.add_command(label=name, command=func)
        elif menu == "show":
            self.showmenu.add_command(label=name, command=func)
        self.added_buttons.append(name)

    def remove_all(self):
        for but in self.added_buttons:
            self.remove_item(name)

    def remove_item(self, name):
        self.showmenu.delete(name)
Ejemplo n.º 15
0
	def __init__(self, parent=None):
		Frame.__init__(self,parent)
		self.parent = parent
		self.parent.title("Accounting")
		
		self.status = StatusBar(parent)
		self.status.set("%s","...")
		self.status.pack(side=BOTTOM, fill=BOTH)
		
		self.leftmenu = LeftMenu(parent)
		self.leftmenu.pack(side=LEFT, fill=BOTH)
			
		self.paymentframe = Frame(self,relief=GROOVE, bd=1)
		Label(self.paymentframe,text="Упорядочить по",height=2).grid(row=0,column=0,columnspan=2)
		self.paymentframe.pack(side=TOP,fill=BOTH,expand=YES)

		
		self.menubar = Menu(self)
		menu = Menu(self.menubar, tearoff=0)
		self.menubar.add_cascade(label="File", menu=menu)
		menu.add_command(label="LogIn", command=(lambda: authWindow(self)))
		menu.add_separator()
		menu.add_command(label="MessBox",command=(lambda: self.addPayment()))
		menu.add_separator()
		menu.add_command(label="Close", command=self.quit)

		menu = Menu(self.menubar, tearoff=0)
		self.menubar.add_cascade(label="Other", menu=menu)
		menu.add_command(label="Статистика", command=(lambda: Statistics(self)))
		menu.add_command(label="Copy")
		menu.add_command(label="Paste")
		
		try:
			self.master.config(menu=self.menubar)
		except AttributeError:
		    # master is a toplevel window (Python 1.4/Tkinter 1.63)
		    self.master.tk.call(master, "config", "-menu", self.menubar)		
		
		
		self.pack()
Ejemplo n.º 16
0
    def bind_menu_actions(self):
        """Create menu bar"""
        menubar = Menu(self)
        self.config(menu=menubar)

        # File menu
        filemenu = Menu(menubar, tearoff=False)
        filemenu.add_command(label="New Project", command=self._project_handler.new_project)
        filemenu.add_command(label="Open Project", command=self._project_handler.open_project)
        filemenu.add_separator()
        filemenu.add_command(label="Project Info", command=self._project_handler.edit_info)
        filemenu.add_separator()
        filemenu.add_command(label="Quit", command=self.exit)
        menubar.add_cascade(label="File", menu=filemenu)

        samplemenu = Menu(menubar, tearoff=False)
        samplemenu.add_command(label="Add Sample", command=self._project_handler.new_sample)
        samplemenu.add_command(label="Select Sample", command=self._project_handler.select_sample)
        samplemenu.add_command(label="Delete This Sample", command=self._project_handler.delete_curr_sample)
        menubar.add_cascade(label="Sample", menu=samplemenu)

        projectmenu = Menu(menubar, tearoff=False)
        projectmenu.add_command(label="Set Project Date", command=self._project_handler.set_date)
        menubar.add_cascade(label="Project", menu=projectmenu)
Ejemplo n.º 17
0
    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Reset Parser", underline=0, command=self.reset, accelerator="Del")
        filemenu.add_command(label="Print to Postscript", underline=0, command=self.postscript, accelerator="Ctrl-p")
        filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Edit Grammar", underline=5, command=self.edit_grammar, accelerator="Ctrl-g")
        editmenu.add_command(label="Edit Text", underline=5, command=self.edit_sentence, accelerator="Ctrl-t")
        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label="Step", underline=1, command=self.step, accelerator="Space")
        rulemenu.add_separator()
        rulemenu.add_command(label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s")
        rulemenu.add_command(label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r")
        rulemenu.add_separator()
        rulemenu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u")
        menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(
            label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar
        )
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label="Tiny", variable=self._size, underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label="Small", variable=self._size, underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label="Medium", variable=self._size, underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label="Large", variable=self._size, underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label="Huge", variable=self._size, underline=0, value=24, command=self.resize)
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0)
        animatemenu.add_radiobutton(
            label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator="-"
        )
        animatemenu.add_radiobutton(
            label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator="="
        )
        animatemenu.add_radiobutton(
            label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator="+"
        )
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        helpmenu.add_command(label="Instructions", underline=0, command=self.help, accelerator="F1")
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)
Ejemplo n.º 18
0
    def __init__(self, tk: Tk):
        tk.title("Layered Polygons")

        menubar = Menu(tk)

        menu_file = Menu(menubar, tearoff=0)
        menu_file.add_command(label="New...", command=self._new_scene)
        menu_file.add_command(label="Open...", command=self._open_scene)
        menu_file.add_separator()
        menu_file.add_command(label="Save", command=self._save_scene)
        menu_file.add_command(label="Save As...", command=self._save_scene_as)
        menu_file.add_separator()
        menu_export = Menu(menu_file, tearoff=0)
        menu_export.add_command(label="Wavefront (.obj)...",
                                command=self._export_obj)
        menu_file.add_cascade(label="Export As", menu=menu_export)
        menu_file.add_separator()
        menu_file.add_command(label="Quit", command=self._quit_app)
        menubar.add_cascade(label="File", menu=menu_file)

        tk.config(menu=menubar)

        paned = PanedWindow(tk, relief=RAISED)
        paned.pack(fill=BOTH, expand=1)

        frame = Frame(paned)
        paned.add(frame)
        self._canvas = LayPolyCanvas(frame)
        bar_x = Scrollbar(frame, orient=HORIZONTAL)
        bar_x.pack(side=BOTTOM, fill=X)
        bar_x.config(command=self._canvas.xview)
        bar_y = Scrollbar(frame, orient=VERTICAL)
        bar_y.pack(side=RIGHT, fill=Y)
        bar_y.config(command=self._canvas.yview)
        self._canvas.config(xscrollcommand=bar_x.set, yscrollcommand=bar_y.set)
        self._canvas.pack(side=LEFT, expand=True, fill=BOTH)
        # Thanks to the two guys on Stack Overflow for that!
        # ( http://stackoverflow.com/a/7734187 )

        self._layer_list = Listbox(paned, selectmode=SINGLE)
        paned.add(self._layer_list)

        self._scene = None
        self._current_layer = None
        self._is_drawing_polygon = False
        self._tk = tk

        self._canvas.bind("<Button-1>", self._canvas_left_click)
        self._canvas.bind("<Button-3>", self._canvas_right_click)
        self._canvas.bind("<Motion>", self._canvas_mouse_moved)
        self._layer_list.bind("<<ListboxSelect>>", self._layer_change)

        self._current_path = None
Ejemplo n.º 19
0
class TopMenuBar(Menu):
    def __init__(self, parent):
        Menu.__init__(self, parent)
        self.parent = parent
        self.newmenu = Menu(self)
        self.showmenu = Menu(self)
        self.newmenu.add_command(label="NPC", command=self.parent.onNew)
        self.newmenu.add_separator()
        self.newmenu.add_command(label="Save", command=self.parent.save)
        self.newmenu.add_command(label="Load", command=self.parent.load)
        self.showmenu.add_command(label="Info", command=self.parent.get_info)
        self.newmenu.add_separator()
        self.showmenu.add_separator()
        self.add_cascade(label="New", menu=self.newmenu)
        self.add_cascade(label="Show", menu=self.showmenu)
        self.add_command(label="Exit", command=self.parent.quit)

    def add_button(self, menu, name, call):
        func = partial(call, name)
        if menu == "new":
            self.newmenu.add_command(label=name, command=func)
        elif menu == "show":
            self.showmenu.add_command(label=name, command=func)
    def createWidgets(self):    
        # Tab Control introduced here --------------------------------------
        tabControl = ttk.Notebook(self.win)     # Create Tab Control
        
        tab1 = ttk.Frame(tabControl)            # Create a tab 
        tabControl.add(tab1, text='Tab 1')      # Add the tab
        
        tab2 = ttk.Frame(tabControl)            # Add a second tab
        tabControl.add(tab2, text='Tab 2')      # Make second tab visible
        
        tabControl.pack(expand=1, fill="both")  # Pack to make visible
        # ~ Tab Control introduced here -----------------------------------------
        
        # We are creating a container frame to hold all other widgets
        self.monty = ttk.LabelFrame(tab1, text=' Monty Python ')
        self.monty.grid(column=0, row=0, padx=8, pady=4)        
        
        # Changing our Label
        ttk.Label(self.monty, text="Enter a name:").grid(column=0, row=0, sticky='W')
        
        # Adding a Textbox Entry widget
        self.name = tk.StringVar()
        nameEntered = ttk.Entry(self.monty, width=12, textvariable=self.name)
        nameEntered.grid(column=0, row=1, sticky='W')
        
        # Adding a Button
        self.action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe)   
        self.action.grid(column=2, row=1)
        
        ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0)
        number = tk.StringVar()
        numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number)
        numberChosen['values'] = (1, 2, 4, 42, 100)
        numberChosen.grid(column=1, row=1)
        numberChosen.current(0)
             
        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.monty, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) 
        self.spin.grid(column=0, row=2)
                  
        # Using a scrolled Text control    
        scrolW  = 30; scrolH  =  3
        self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, row=3, sticky='WE', columnspan=3)
        
# TODO: ch11 new
    #------------------------------------------------------------------------- 
        #-------------------------------------------------------------------------    
        # Adding another Button
        self.action = ttk.Button(self.monty, text="Clear Text", command=self.clearScrol)   
        self.action.grid(column=2, row=2)
    
        # Adding more Feature Buttons
        startRow = 4
        for idx in range(12):
            if idx < 2:
                colIdx = idx
                col = colIdx
            else:
                col += 1
            if not idx % 3: 
                startRow += 1
                col = 0

            b = ttk.Button(self.monty, text="Feature " + str(idx+1))   
            b.grid(column=col, row=startRow)   
            
        # Tab Control 3  -----------------------------------------            
        tab3 = ttk.Frame(tabControl)            # Add a tab
        tabControl.add(tab3, text='Tab 3')      # Make tab visible
        
        # We are creating a container frame to hold all other widgets -- Tab3
        monty3 = ttk.LabelFrame(tab3, text=' New Features ')
        monty3.grid(column=0, row=0, padx=8, pady=4)

        # Adding more Feature Buttons
        startRow = 4
        for idx in range(24):
            if idx < 2:
                colIdx = idx
                col = colIdx
            else:
                col += 1
            if not idx % 3: 
                startRow += 1
                col = 0

            b = ttk.Button(monty3, text="Feature " + str(idx+1))   
            b.grid(column=col, row=startRow)    
            
        # Add some space around each label
        for child in monty3.winfo_children(): 
            child.grid_configure(padx=8)                                                                         
    #-------------------------------------------------------------------------    
# TODO: ch11 new end        
                       
        # Tab Control 2 refactoring  -----------------------------------------
        # We are creating a container frame to hold all other widgets -- Tab2
        self.monty2 = ttk.LabelFrame(tab2, text=' Holy Grail ')
        self.monty2.grid(column=0, row=0, padx=8, pady=4)
        # Creating three checkbuttons
        chVarDis = tk.IntVar()
        check1 = tk.Checkbutton(self.monty2, text="Disabled", variable=chVarDis, state='disabled')
        check1.select()
        check1.grid(column=0, row=0, sticky=tk.W)                 
        
        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.monty2, text="UnChecked", variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W )                  
         
        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.monty2, text="Toggle", variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)                 
    
        # trace the state of the two checkbuttons
        self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())    
        self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())   
        # ~ Tab Control 2 refactoring  -----------------------------------------
        
        # Radiobutton list
        colors = ["Blue", "Gold", "Red"]
        
        self.radVar = tk.IntVar()
        
        # Selecting a non-existing index value for radVar
        self.radVar.set(99)    
        
        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = 'rad' + str(col)  
            curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value=col, command=self.radCall)
            curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            tt.createToolTip(curRad, 'This is a Radiobutton control.')
            
        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ')
        labelsFrame.grid(column=0, row=7)
         
        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0)
        ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1)
        
        # Add some space around each label
        for child in labelsFrame.winfo_children(): 
            child.grid_configure(padx=8)
        
        
        # Creating a Menu Bar
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)
        
        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label="New")
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self._quit)
        menuBar.add_cascade(label="File", menu=fileMenu)
        
        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label="About")
        menuBar.add_cascade(label="Help", menu=helpMenu)
        
        # Change the main windows icon
        self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico')
        
        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')
        print(strData.get())
        
        # Default tkinter Variable Classes
        intData = tk.IntVar()
        print(intData.get())
        print(tk.DoubleVar())
        print(tk.BooleanVar())
        
        # It is not necessary to create a tk.StringVar() 
        strData = tk.StringVar()
        strData = self.spin.get()
        print("Hello " + strData)
        
        # Printing the Global works
        print(GLOBAL_CONST)
         
        # call method
        self.usingGlobal()
        
        # Place cursor into name Entry
        nameEntered.focus()     
        
        # Add a Tooltip to the Spinbox
        tt.createToolTip(self.spin, 'This is a Spin control.')         
        
        # Add Tooltips to more widgets
        tt.createToolTip(nameEntered, 'This is an Entry control.')  
        tt.createToolTip(self.action, 'This is a Button control.')                      
        tt.createToolTip(self.scr,    'This is a ScrolledText control.')
Ejemplo n.º 21
0
class PypeTkPad(object):

    def __init__(self, master, queue, pypeOutput):
      
        self.queue = queue
        self.pypeOutput = pypeOutput

        self.master = master
        self.master.title('PypePad')
        self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0))
        self.master.minsize(300, 100)
        self.output_file_name = None
        
        self.BuildMainFrame()
        self.UpdateOutput()

    def NewCommand(self):
        self.ClearAllCommand()

    def OpenCommand(self):
        import tkinter.filedialog
        from tkinter import END
        openfile = tkinter.filedialog.askopenfile()
        if not openfile:
            return
        for line in openfile.readlines():
            self.text_input.insert(END,line)
 
    def SaveCommand(self):
        import tkinter.filedialog
        from tkinter import END
        saveasfile = tkinter.filedialog.asksaveasfile()
        if not saveasfile:
            return
        alltext = self.text_input.get("1.0",END)
        saveasfile.write(alltext)
 
    def QuitCommand(self):
        self.master.quit()

    def ClearInputCommand(self):
        from tkinter import END
        self.text_input.delete("1.0",END)
        
    def ClearOutputCommand(self):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.delete("1.0",END)
        self.text_output["state"] = DISABLED
        self.text_output.see(END)
        self.text_output.update()
        
    def ClearAllCommand(self):
        self.ClearInputCommand()
        self.ClearOutputCommand()

    def OutputFileCommand(self):
        import tkinter.filedialog
        outputfilename = tkinter.filedialog.asksaveasfilename()
        if sys.platform == 'win32' and len(outputfilename.split()) > 1:
            outputfilename = '"%s"' % outputfilename
        self.output_file_name = outputfilename

    def AboutCommand(self):
        self.OutputText('\n')
        self.OutputText('* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n')
        self.OutputText('\n')

    def UpdateOutput(self):
        if self.pypeOutput:
            text = self.pypeOutput.pop(0)
            self.output_stream.write(text)
        self.master.after(10,self.UpdateOutput)

    def RunPype(self,arguments):
        if not arguments:
            return
        if self.output_to_file.get() is not 'n' and self.output_file_name:
            self.output_stream.output_to_file = True
            self.output_stream.output_file = open(self.output_file_name,self.output_to_file.get())
        else:
            self.output_stream.output_to_file = False

        self.queue.append(arguments)
 
    def GetWordUnderCursor(self):
        from tkinter import CURRENT
        splitindex = self.text_input.index(CURRENT).split('.')
        line = self.text_input.get(splitindex[0]+".0",splitindex[0]+".end")
        wordstart = line.rfind(' ',0,int(splitindex[1])-1)+1
        wordend = line.find(' ',int(splitindex[1]))
        if wordend == -1:
            wordend = len(line)
        word = line[wordstart:wordend]
        return word

    def GetWordIndex(self):
        startindex = self.text_input.index("insert-1c wordstart")
        endindex = self.text_input.index("insert-1c wordend")
        if self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == '-':
           startindex = self.text_input.index("insert-1c wordstart -2c") 
        elif self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == ' ':
           startindex = self.text_input.index("insert-1c wordstart -1c")
        self.wordIndex[0] = startindex
        self.wordIndex[1] = endindex
        word = self.text_input.get(self.wordIndex[0],self.wordIndex[1])
        return word

    def GetLogicalLine(self,physicallineid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallineid]]
 
    def GetLogicalLineRange(self,physicallinefirstid,physicallinelastid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallinefirstid]:indexes[physicallinelastid]+1]
   
    def GetAllLogicalLines(self):
        return self.GetLogicalLines()[1]
   
    def GetLogicalLines(self):
        from tkinter import END
        # Python 2 hack to remove the u'...' prefix from unicode literal strings. does not change py3 behavior
        physicallines = [str(line) for line in self.text_input.get("1.0",END).split('\n')]
        lines = []
        indexes = [0] * len(physicallines)
        lineid = 0
        previousline = ""
        join = 0
        for line in physicallines:
            if line.startswith('#'):
                if join:
                    indexes[lineid] = indexes[lineid-1]
            elif join:
                if line.endswith('\\'):
                    lines[-1] = lines[-1] + " " + line[:-1]
                    join = 1
                else:
                    lines[-1] = lines[-1] + " " + line
                    join = 0
                indexes[lineid] = indexes[lineid-1]
            else:
                if line.endswith('\\'):
                    join = 1
                    lines.append(line[:-1])
                else:
                    lines.append(line)
                    join = 0
                if lineid > 0:
                    indexes[lineid] = indexes[lineid-1]+1
            lineid += 1
        return indexes, lines

    def GetLineUnderCursor(self):
        from tkinter import INSERT
        currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1
        return self.GetLogicalLine(currentlineid)

    def RunAllCommand(self):
        lines = self.GetAllLogicalLines()
        for line in lines:
            if line and line.strip():
                self.RunPype(line)

    def RunLineCommand(self):
        line = self.GetLineUnderCursor()
        if line and line.strip():
            self.RunPype(line)
      
    def RunSelectionCommand(self):
        from tkinter import TclError, SEL_FIRST, SEL_LAST
        try:
            firstlineid = int(self.text_input.index(SEL_FIRST).split('.')[0]) - 1
            lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1
            lines = self.GetLogicalLineRange(firstlineid,lastlineid)
            for line in lines:
                self.RunPype(line)
        except TclError:
            pass

    def GetSuggestionsList(self,word):
        list = []
        try:
            from vmtk import vmtkscripts
            from vmtk import pypes
        except ImportError:
            return None
        if word.startswith('--'):
            list = ['--pipe','--help']
        elif word.startswith('-'):
            optionlist = []
            scriptindex = self.text_input.search('vmtk',self.wordIndex[0],backwards=1)
            moduleName  = self.text_input.get( scriptindex,scriptindex+' wordend' )
            try:
                module = importlib.import_module('vmtk.'+moduleName)
                # Find the principle class to instantiate the requested action defined inside the requested writerModule script.
                # Returns a single member list (containing the principle class name) which satisfies the following criteria:
                #   1) is a class defined within the script
                #   2) the class is a subclass of pypes.pypescript
                scriptObjectClasses = [x for x in dir(module) if isclass(getattr(module, x)) and issubclass(getattr(module, x), pypes.pypeScript)]
                scriptObjectClassName = scriptObjectClasses[0]
                scriptObject = getattr(module, scriptObjectClassName)
                scriptObject = scriptObject()
                members = scriptObject.InputMembers + scriptObject.OutputMembers
                for member in members:
                    optionlist.append('-'+member.OptionName)
                list = [option for option in optionlist if option.count(word)]
            except:
                return list
        else:
            list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word)]
            for index, item in enumerate(list):
                # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
                if 'vmtk.' == item[0:5]:
                    splitList = item.split('.')
                    list[index] = splitList[1]
                else:
                    continue
        return list

    def FillSuggestionsList(self,word):
        from tkinter import END
        self.suggestionslist.delete(0,END)
        suggestions = self.GetSuggestionsList(word)
        for suggestion in suggestions:
            self.suggestionslist.insert(END,suggestion)

    def ReplaceTextCommand(self,word):
        self.text_input.delete(self.wordIndex[0],self.wordIndex[1])
        self.text_input.insert(self.wordIndex[0],word)
        self.text_input.focus_set()

    def ShowHelpCommand(self):
        word = self.GetWordUnderCursor()
        self.OutputText(word)
        if word:
            self.RunPype(word+' --help')
        else: 
            self.OutputText('Enter your vmtk Pype above and Run.\n')

    def AutoCompleteCommand(self):
        word = self.GetWordIndex()
        self.suggestionswindow.withdraw()
        if word:
            self.FillSuggestionsList(word)
            self.suggestionswindow.geometry("%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),self.text_output.winfo_rooty()))
            self.suggestionswindow.deiconify()
            self.suggestionswindow.lift()
            
    def InsertScriptName(self,scriptname):
        from tkinter import INSERT
        self.text_input.insert(INSERT,scriptname+' ')
        
    def InsertFileName(self):
        from tkinter import INSERT
        import tkinter.filedialog
        openfilename = tkinter.filedialog.askopenfilename()
        if not openfilename:
            return
        if len(openfilename.split()) > 1:
            openfilename = '"%s"' % openfilename
        self.text_input.insert(INSERT,openfilename+' ')

    def KeyPressHandler(self,event):
        if event.keysym == "Tab" :
            self.AutoCompleteCommand()
            self.suggestionslist.focus_set()
            self.suggestionslist.selection_set(0)
            return "break"
        else:
            self.text_input.focus_set()

    def TopKeyPressHandler(self,event):
        from tkinter import ACTIVE, INSERT
        if event.keysym in ['Down','Up'] :
            self.suggestionslist.focus_set()
        elif event.keysym == "Return":
            word = self.suggestionslist.get(ACTIVE)
            self.ReplaceTextCommand(word)
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
        elif len(event.keysym) == 1 :
            self.suggestionswindow.withdraw()
            self.text_input.insert(INSERT,event.keysym)
            self.text_input.focus_set()
        else :
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
    
    def NewHandler(self,event):
        self.NewCommand() 

    def OpenHandler(self,event):
        self.OpenCommand()

    def SaveHandler(self,event):
        self.SaveCommand()

    def InsertFileNameHandler(self,event):
        self.InsertFileName()
        return "break"
 
    def QuitHandler(self,event):
        self.QuitCommand()

    def ShowHelpHandler(self,event):
        self.ShowHelpCommand()

    def RunKeyboardHandler(self,event):
        from tkinter import SEL_FIRST, TclError
        try: 
            self.text_input.index(SEL_FIRST)
            self.RunSelectionCommand()
        except TclError:
            self.RunLineCommand()
        return "break"
         
    def RunAllHandler(self,event):
        self.RunAllCommand()
      
    def PopupHandler(self,event):
        try:
            self.popupmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popupmenu.grab_release()

    def OutputText(self,text):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.insert(END,text)
        self.text_output["state"] = DISABLED

    def BuildScriptMenu(self,parentmenu,modulename):
        from tkinter import Menu
        menu = Menu(parentmenu,bd=1,activeborderwidth=0)
        try:
            module = importlib.import_module('vmtk.'+modulename)
        except ImportError:
            return None
        scriptnames = [scriptname for scriptname in getattr(module, '__all__')]
        for index, scriptname in enumerate(scriptnames):
            # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
            if 'vmtk.' == scriptname[0:5]:
                splitList = scriptname.split('.')
                scriptnames[index] = splitList[1]
            else:
                continue
        menulength = 20
        for i in range(len(scriptnames)//menulength+1):
            subscriptnames = scriptnames[i*menulength:(i+1)*menulength]
            if not subscriptnames:
                break 
            submenu = Menu(menu,bd=1,activeborderwidth=0)
            menu.add_cascade(label=subscriptnames[0]+"...",menu=submenu)
            for scriptname in subscriptnames:
                callback = CallbackShim(self.InsertScriptName,scriptname)
                submenu.add_command(label=scriptname,command=callback)
        return menu 

    def BuildMainFrame(self): 
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master,activeborderwidth=0,bd=0)
        self.master.config(menu=menu)
  
        filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="File", underline=0,  menu=filemenu)
        filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand)
        filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand)
        filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)
  
        self.output_to_file = StringVar()
        self.output_to_file.set('n')
 
        scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu,modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu)
 
        editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Edit",underline=0,  menu=editmenu)
        editmenu.add_cascade(label="Insert script",menu=scriptmenu)
        editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input", command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output", command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n')
        editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w')
        editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a')
        editmenu.add_command(label="Output file...", command=self.OutputFileCommand)

        runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line", command=self.RunLineCommand)
        runmenu.add_command(label="Run selection", command=self.RunSelectionCommand)
       
        helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand)
        helpmenu.add_command(label="About", underline=0, command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)
        
        self.wordIndex = ['1.0','1.0']
               
        self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9)
        self.suggestionslist.insert(END,"foo")
        self.suggestionslist.pack(side=TOP,fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0,weight=1)
        self.master.columnconfigure(0,weight=1)
        content = Frame(self.master,bd=0,padx=2,pady=2) 
        content.grid(row=0,column=0,sticky=N+S+W+E)
        content.rowconfigure(0,weight=1,minsize=50)
        content.rowconfigure(1,weight=0)
        content.columnconfigure(0,weight=1)

        panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True)
        panes.grid(row=0,column=0,sticky=N+S+W+E)

        frame1 = Frame(panes,bd=0) 
        frame1.grid(row=0,column=0,sticky=N+S+W+E)
        frame1.columnconfigure(0,weight=1)
        frame1.columnconfigure(1,weight=0)
        frame1.rowconfigure(0,weight=1)

        panes.add(frame1,height=300,minsize=20)        

        frame2 = Frame(panes,bd=0) 
        frame2.grid(row=1,column=0,sticky=N+S+W+E)
        frame2.columnconfigure(0,weight=1)
        frame2.columnconfigure(1,weight=0)
        frame2.rowconfigure(0,weight=1)
        
        panes.add(frame2,minsize=20) 
 
        self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)
 
        self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set    

        self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0)
        
        self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set    
      
        self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0,column=0,sticky=N+S+W+E)
        self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_output.grid(row=0,column=0,sticky=N+S+W+E)
        self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_entry.grid(row=1,column=0,sticky=N+S+W+E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
Ejemplo n.º 22
0
# (main program)
top = Tk()
top.tk.eval('package require Tix')
top.title('Hello World')
top.geometry('400x200') 

def hello():
    print('hello')

menubar = Menu(top)

#创建下拉菜单File,然后将其加入到顶级的菜单栏中
filemenu = Menu(menubar,tearoff=0)
filemenu.add_command(label="Open", command=hello)
filemenu.add_command(label="Save", command=hello)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=filemenu)
#显示菜单
top.config(menu=menubar)


#li     = ['C','python','php','html','SQL','java']
#listb  = Listbox(top)          #  创建两个列表组件
#for item in li:                 # 第一个小部件插入数据
 #   listb.insert(0,item)
#listb.pack()                    # 将小部件放置到主窗口中

#lb = Label(top, text = 'Animals in ')
#lb.pack()
Ejemplo n.º 23
0
    def BuildMainFrame(self):
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master, activeborderwidth=0, bd=0)
        self.master.config(menu=menu)

        filemenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="File", underline=0, menu=filemenu)
        filemenu.add_command(label="New",
                             accelerator='Ctrl+N',
                             command=self.NewCommand)
        filemenu.add_command(label="Open...",
                             accelerator='Ctrl+O',
                             command=self.OpenCommand)
        filemenu.add_command(label="Save as...",
                             accelerator='Ctrl+S',
                             command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",
                             accelerator='Ctrl+Q',
                             command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)

        self.output_to_file = StringVar()
        self.output_to_file.set('n')

        scriptmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu, modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename, menu=scriptsubmenu)

        editmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Edit", underline=0, menu=editmenu)
        editmenu.add_cascade(label="Insert script", menu=scriptmenu)
        editmenu.add_command(label="Insert file name",
                             accelerator='Ctrl+F',
                             command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input",
                             command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output",
                             command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file",
                                 variable=self.output_to_file,
                                 value='n')
        editmenu.add_radiobutton(label="Write output to file",
                                 variable=self.output_to_file,
                                 value='w')
        editmenu.add_radiobutton(label="Append output to file",
                                 variable=self.output_to_file,
                                 value='a')
        editmenu.add_command(label="Output file...",
                             command=self.OutputFileCommand)

        runmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line",
                            command=self.RunLineCommand)
        runmenu.add_command(label="Run selection",
                            command=self.RunSelectionCommand)

        helpmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help",
                             underline=0,
                             accelerator='F1',
                             command=self.ShowHelpCommand)
        helpmenu.add_command(label="About",
                             underline=0,
                             command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)

        self.wordIndex = ['1.0', '1.0']

        self.suggestionswindow = Toplevel(bg='#ffffff',
                                          bd=0,
                                          height=50,
                                          width=600,
                                          highlightthickness=0,
                                          takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,
                                       bg='#ffffff',
                                       bd=1,
                                       fg='#336699',
                                       activestyle='none',
                                       highlightthickness=0,
                                       height=9)
        self.suggestionslist.insert(END, "foo")
        self.suggestionslist.pack(side=TOP, fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)
        content = Frame(self.master, bd=0, padx=2, pady=2)
        content.grid(row=0, column=0, sticky=N + S + W + E)
        content.rowconfigure(0, weight=1, minsize=50)
        content.rowconfigure(1, weight=0)
        content.columnconfigure(0, weight=1)

        panes = PanedWindow(content,
                            orient=VERTICAL,
                            bd=1,
                            sashwidth=8,
                            sashpad=0,
                            sashrelief=RAISED,
                            showhandle=True)
        panes.grid(row=0, column=0, sticky=N + S + W + E)

        frame1 = Frame(panes, bd=0)
        frame1.grid(row=0, column=0, sticky=N + S + W + E)
        frame1.columnconfigure(0, weight=1)
        frame1.columnconfigure(1, weight=0)
        frame1.rowconfigure(0, weight=1)

        panes.add(frame1, height=300, minsize=20)

        frame2 = Frame(panes, bd=0)
        frame2.grid(row=1, column=0, sticky=N + S + W + E)
        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(1, weight=0)
        frame2.rowconfigure(0, weight=1)

        panes.add(frame2, minsize=20)

        self.text_input = Text(frame1,
                               bg='#ffffff',
                               bd=1,
                               highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)

        self.input_scrollbar = Scrollbar(frame1,
                                         orient=VERTICAL,
                                         command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set

        self.text_output = Text(frame2,
                                state=DISABLED,
                                bd=1,
                                bg='#ffffff',
                                highlightthickness=0)

        self.output_scrollbar = Scrollbar(frame2,
                                          orient=VERTICAL,
                                          command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set

        self.text_entry = Entry(content,
                                bd=1,
                                bg='#ffffff',
                                state=DISABLED,
                                highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0, column=0, sticky=N + S + W + E)
        self.input_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_output.grid(row=0, column=0, sticky=N + S + W + E)
        self.output_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_entry.grid(row=1, column=0, sticky=N + S + W + E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help",
                                   command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script", menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...",
                                   command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line",
                                   command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection",
                                   command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,
                                             self.output_stream)
Ejemplo n.º 24
0
# pygame.mixer.pre_init(44100, -16, 2, 2048)
# pygame.mixer.init()
# pygame.mixer.music.load("tng_red_alert3.mp3")
# pygame.mixer.music.set_volume(10.0)

# Set up counter display
fnt = font.Font(family='Helvetica', size=300, weight='bold')
txt = StringVar()
lbl = ttk.Label(root,
                textvariable=txt,
                font=fnt,
                foreground="white",
                background="black")
txt.set(iTotal)
lbl.place(relx=0.5, rely=0.5, anchor="center")

# Menu
menu_pop = Menu(root)
menu = Menu(menu_pop, tearoff=0)
menu.config(bg="black", fg="white", relief="raised")
menu.add_command(label="Start/Stop", accelerator="F1", command=go_stop)
menu.add_command(label="Reset", accelerator="F2", command=reset)
menu.add_separator()
menu.add_command(label="Settings", command=settings)
menu.add_separator()
menu.add_command(label="Exit", accelerator="X", command=quit_all)
menu_pop.add_cascade(label="File", menu=menu)

# Start main loop
root.mainloop()
Ejemplo n.º 25
0
    def createWidgets(self):

        tabControl= ttk.Notebook(self.win)

        tab1=ttk.Frame(tabControl)
        tabControl.add(tab1, text='Tab 1')

        tab2 = ttk.Frame(tabControl)
        tabControl.add(tab2, text='Tab 2')

        tab3 = ttk.Frame(tabControl)
        tabControl.add(tab3, text='Tab 3')

        tabControl.pack(expand=1, fill='both')

        tab3=tk.Frame(tab3,bg='blue')
        tab3.pack()
        for orangeColor in range(2):
            canvas = tk.Canvas(tab3, width=150,height=80,highlightthickness=0,bg='orange')
            canvas.grid(row=orangeColor,column=orangeColor)

        # create container to hold all widgets
        self.monty = ttk.LabelFrame(tab1,text=' Monty Python ')
        self.monty.grid(column=0,row=0,padx=8,pady=4)

        self.monty2 = ttk.LabelFrame(tab2,text=' The Snake ')
        self.monty2.grid(column=0,row=0,padx=8,pady=4)

        #Label
        ttk.Label(self.monty,text="Enter a name:").grid(column=0,row=0,sticky='W')

        #add a text box widget
        name = tk.StringVar()
        self.nameEntered = ttk.Entry(self.monty, width=12, textvariable=name)
        self.nameEntered.grid(column=0,row=1,sticky=tk.W)
        tt.createToolTip(self.nameEntered, 'This is an entry control')

        # combo box and label
        ttk.Label(self.monty, text='Choose a number:').grid(column=1, row=0)
        number = tk.StringVar()
        numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number, state='readonly')
        numberChosen['values'] = (1,2,4,42,100)
        numberChosen.grid(column=1, row=1)
        numberChosen.current(0)

        # add a button
        action = ttk.Button(self.monty, text="Click Me!", command=self.clickMe)
        action.grid(column=2, row=1)
        #action.configure(state='disabled')

        #add check boxes
        chVarDis = tk.IntVar()
        check1 = tk.Checkbutton(self.monty2, text='Disabled',variable=chVarDis, state='disabled')
        check1.select()
        check1.grid(column=0,row=4, sticky=tk.W)

        chVarUn = tk.IntVar()
        check2 = tk.Checkbutton(self.monty2, text='UnChecked',variable=chVarUn)
        check2.deselect()
        check2.grid(column=1,row=4,sticky=tk.W)

        chVarEn = tk.IntVar()
        check3 = tk.Checkbutton(self.monty2, text='Enabled',variable=chVarEn)
        check3.select()
        check3.grid(column=2,row=4,sticky=tk.W)

        # Radiobutton list
        colors = ["Blue", "Gold", "Red"]

        #create three radio buttons
        self.radVar=tk.IntVar()
        self.radVar.set(99)
        for col in range(3):
            curRad = 'rad' + str(col)
            curRad = tk.Radiobutton(self.monty2, text=colors[col], variable=self.radVar, value = col, command=self.radCall)
            curRad.grid(column=col, row=5, sticky=tk.W)


        #add a spinbox
        self.spin = Spinbox(self.monty,from_=0,to=10,width=5,bd=8, command=self._spin)
        self.spin.grid(column=0,row=2)

        # add a tooltip
        tt.createToolTip(self.spin,'This is a Spin control.')

        spin2 = Spinbox(self.monty, values=(0,50,100),width=5,bd=10,command=self._spin,relief=tk.RIDGE)
        spin2.grid(column=1,row=2)

        # add scrolled text widget
        scrolW= 50
        scrolH = 3
        self.scr = scrolledtext.ScrolledText(self.monty, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, sticky='WE',columnspan=3)
        #scr.grid(column=0, columnspan=3)
        tt.createToolTip(self.scr,'This is a ScrolledText widget.')

        # container to hold labels
        labelsFrame = ttk.LabelFrame(self.monty, text=' Labels in a Frame ')
        labelsFrame.grid(column=0,row=7,padx=20,pady=40)

        # place labels into the container
        ttk.Label(labelsFrame,text='Label1').grid(column=0,row=0)
        ttk.Label(labelsFrame,text='Label2').grid(column=0,row=1)
        ttk.Label(labelsFrame,text='Label3').grid(column=0,row=2)

        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=8,pady=4)

        # menu commands
        def _quit(self):
            self.win.quit()
            self.win.destroy()
            exit()

        #create menubar
        menuBar=Menu(self.win)
        self.win.config(menu=menuBar)

        # add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label='New')
        fileMenu.add_separator()
        fileMenu.add_command(label='Exit', command=_quit)
        menuBar.add_cascade(label='File',menu=fileMenu)



        helpMenu = Menu(menuBar,tearoff=0)
        helpMenu.add_command(label='About',command=self._msgBox)
        menuBar.add_cascade(label='Help',menu=helpMenu)
Ejemplo n.º 26
0
class CopyToMoveTo:
    """
        Minimalist file manager intended to be used independently
        or alongside Windows Explorer
    """
    def __init__(self, root):
        """
            Setup window geometry, init settings, define widgets + layout
        """
        self.master = root
        self.master.title("CopyTo-MoveTo")
        self.master.iconbitmap(f"{dirname(__file__)}/icon.ico")

        if system() != "Windows":
            self.master.withdraw()
            messagebox.showwarning(
                "Incompatible platform",
                "CopyTo-MoveTo currently supports Windows platforms only.")
            raise SystemExit

        #Settings:
        self.settings_show_hidden = BooleanVar()
        self.settings_include_files = BooleanVar(value=True)
        self.settings_ask_overwrite = BooleanVar()
        self.settings_ask_overwrite.trace("w", self.settings_exclusives)
        self.settings_rename_dupes = BooleanVar(value=True)
        self.settings_rename_dupes.trace("w", self.settings_exclusives)
        self.settings_multiselect = BooleanVar(value=True)
        self.settings_select_dirs = BooleanVar(value=True)
        self.settings_select_dirs.trace("w", self.settings_mutuals)
        self.settings_select_files = BooleanVar(value=True)
        self.settings_select_files.trace("w", self.settings_mutuals)
        self.settings_geometry = None

        self.appdata_dir = getenv("APPDATA") + "/CopyTo-MoveTo"
        self.appdata_path = self.appdata_dir + "/settings.json"
        self.settings = self.init_settings()

        if self.settings:
            self.settings_geometry = self.settings["geometry"]
            self.settings_show_hidden.set(self.settings["show_hidden"])
            self.settings_include_files.set(self.settings["include_files"])
            self.settings_ask_overwrite.set(self.settings["ask_overwrite"])
            self.settings_rename_dupes.set(self.settings["rename_dupes"])
            self.settings_multiselect.set(self.settings["multiselect"])
            self.settings_select_dirs.set(self.settings["select_dirs"])
            self.settings_select_files.set(self.settings["select_files"])

        self.dialog_showing = BooleanVar()
        self.help_showing = BooleanVar()
        self.about_showing = BooleanVar()

        self.master.protocol("WM_DELETE_WINDOW", self.master_close)
        self.master.bind("<Control-w>", self.master_close)

        #Geometry:
        self.master.minsize(width=450, height=200)

        if self.settings_geometry:
            self.master.geometry(self.settings_geometry)
            self.master.update()
        else:
            self.master.geometry("600x400")
            self.master.update_idletasks()
            (width_offset, height_offset) = Ufd.get_offset(self.master)
            self.master.geometry(f"+{width_offset}+{height_offset}")
            self.master.update_idletasks()

        # Menu:
        self.main_menu = Menu(self.master)
        self.master.config(menu=self.main_menu)

        self.file_menu = Menu(self.main_menu, tearoff=0)
        self.settings_menu = Menu(self.main_menu, tearoff=0)
        self.main_menu.add_cascade(label="File", menu=self.file_menu)
        self.main_menu.add_cascade(label="Settings", menu=self.settings_menu)

        self.file_menu.add_command(label="Open Source(s)",
                                   accelerator="Ctrl+O",
                                   command=lambda: self.show_ufd(source=True))
        self.master.bind("<Control-o>",
                         lambda event: self.show_ufd(source=True))

        self.file_menu.add_command(label="Open Destination(s)",
                                   accelerator="Ctrl+K+O",
                                   command=lambda: self.show_ufd(source=False))
        self.master.bind("<Control-k>o",
                         lambda event: self.show_ufd(source=False))

        self.file_menu.add_separator()
        self.file_menu.add_command(label="Help / Commands",
                                   command=self.show_help)
        self.file_menu.add_command(label="About", command=self.show_about)

        #Settings menu:
        self.settings_menu.add_checkbutton(label="Show Hidden Files & Folders",
                                           variable=self.settings_show_hidden,
                                           onvalue=True,
                                           offvalue=False)

        self.settings_menu.add_checkbutton(
            label="Include Files in Tree",
            variable=self.settings_include_files,
            onvalue=True,
            offvalue=False)

        self.settings_menu.add_separator()

        self.settings_menu.add_checkbutton(
            label="Ask Overwrite",
            variable=self.settings_ask_overwrite,
            onvalue=True,
            offvalue=False)

        self.settings_menu.add_checkbutton(label="Rename Duplicates",
                                           variable=self.settings_rename_dupes,
                                           onvalue=True,
                                           offvalue=False)

        self.settings_menu.add_separator()

        self.settings_menu.add_checkbutton(label="Multiselect",
                                           variable=self.settings_multiselect,
                                           onvalue=True,
                                           offvalue=False)

        self.settings_menu.add_checkbutton(label="Select Folders",
                                           variable=self.settings_select_dirs,
                                           onvalue=True,
                                           offvalue=False)

        self.settings_menu.add_checkbutton(label="Select Files",
                                           variable=self.settings_select_files,
                                           onvalue=True,
                                           offvalue=False)

        self.main_menu.add_separator()

        #Menu commands:
        self.main_menu.add_command(label="Swap Selected",
                                   command=self.swap_selected)
        self.master.bind("<Control-s>", lambda event: self.swap_selected())

        self.main_menu.add_command(label="Clear Selected",
                                   command=self.clear_selected)
        self.master.bind("<Control-x>", lambda event: self.clear_selected())

        self.main_menu.add_command(label="Clear All", command=self.clear_all)
        self.master.bind("<Control-Shift-X>", lambda event: self.clear_all())

        self.main_menu.add_separator()

        self.main_menu.add_command(label="COPY",
                                   command=lambda: self._submit(copy=True))
        self.master.bind("<Control-Shift-Return>",
                         lambda event: self._submit(copy=True))

        self.main_menu.add_command(label="MOVE",
                                   command=lambda: self._submit(copy=False))
        self.master.bind("<Control-Return>",
                         lambda event: self._submit(copy=False))

        # Body:
        self.paneview = PanedWindow(self.master,
                                    sashwidth=7,
                                    bg="#cccccc",
                                    bd=0,
                                    orient="vertical")

        self.top_pane = PanedWindow(self.paneview)
        self.bottom_pane = PanedWindow(self.paneview)
        self.paneview.add(self.top_pane)
        self.paneview.add(self.bottom_pane)

        self.label_source = Label(self.top_pane, text="Source(s):")
        self.label_dest = Label(self.bottom_pane, text="Destination(s):")

        self.y_scrollbar_source = Scrollbar(self.top_pane, orient="vertical")
        self.x_scrollbar_source = Scrollbar(self.top_pane, orient="horizontal")
        self.y_scrollbar_dest = Scrollbar(self.bottom_pane, orient="vertical")
        self.x_scrollbar_dest = Scrollbar(self.bottom_pane,
                                          orient="horizontal")

        self.list_box_source = Listbox(
            self.top_pane,
            selectmode="extended",
            yscrollcommand=self.y_scrollbar_source.set,
            xscrollcommand=self.x_scrollbar_source.set)

        self.list_box_dest = Listbox(self.bottom_pane,
                                     selectmode="extended",
                                     yscrollcommand=self.y_scrollbar_dest.set,
                                     xscrollcommand=self.x_scrollbar_dest.set)

        self.x_scrollbar_source.config(command=self.list_box_source.xview)
        self.y_scrollbar_source.config(command=self.list_box_source.yview)
        self.x_scrollbar_dest.config(command=self.list_box_dest.xview)
        self.y_scrollbar_dest.config(command=self.list_box_dest.yview)

        # Layout:
        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)

        self.top_pane.rowconfigure(1, weight=1)
        self.top_pane.columnconfigure(0, weight=1)
        self.bottom_pane.rowconfigure(1, weight=1)
        self.bottom_pane.columnconfigure(0, weight=1)

        self.paneview.paneconfigure(self.top_pane, minsize=100)
        self.paneview.paneconfigure(self.bottom_pane, minsize=100)

        self.paneview.grid(row=0, column=0, sticky="nsew")

        self.label_source.grid(row=0, column=0, sticky="w")
        self.list_box_source.grid(row=1, column=0, sticky="nsew")
        self.y_scrollbar_source.grid(row=1, column=1, sticky="ns")
        self.x_scrollbar_source.grid(row=2, column=0, sticky="ew")

        self.label_dest.grid(row=0, column=0, sticky="w", columnspan=2)
        self.list_box_dest.grid(row=1, column=0, sticky="nsew")
        self.y_scrollbar_dest.grid(row=1, column=1, sticky="ns")
        self.x_scrollbar_dest.grid(row=2, column=0, sticky="ew")

    def __str__(self):
        """Return own address"""

        return f"CopyTo-MoveTo @ {hex(id(self))}"

    def init_settings(self):
        """Called on startup, loads, parses, and returns json settings."""

        if exists(self.appdata_path):
            with open(self.appdata_path, "r") as settings_file:
                settings_json = settings_file.read()

            settings = loads(settings_json)
            return settings
        else:
            return None

    def settings_exclusives(self, *args):
        """
            Callback assigned to settings that are mutually exclusive, 
            to prevent logical/runtime errors or unexpected behavior.
        """

        if args[0] == "PY_VAR2":
            if self.settings_ask_overwrite.get() == 1:
                self.settings_rename_dupes.set(0)
                return

        elif args[0] == "PY_VAR3":
            if self.settings_rename_dupes.get() == 1:
                self.settings_ask_overwrite.set(0)
                return

    def settings_mutuals(self, *args):
        """
            Prevent select folders & select files from being disabled concurrently

            If both are unselected, reselect the one we didn't just deselect on.
        """

        if self.settings_select_dirs.get() == 0 \
        and self.settings_select_files.get() == 0:

            if args[0] == "PY_VAR5":
                self.settings_select_files.set(1)

            elif args[0] == "PY_VAR6":
                self.settings_select_dirs.set(1)

    def master_close(self, event=None):
        """
            Similar to utils.toplevel_close().
            writes settings to the disk as json.
        """

        settings = {
            "geometry": self.master.geometry(),
            "show_hidden": self.settings_show_hidden.get(),
            "include_files": self.settings_include_files.get(),
            "ask_overwrite": self.settings_ask_overwrite.get(),
            "rename_dupes": self.settings_rename_dupes.get(),
            "multiselect": self.settings_multiselect.get(),
            "select_dirs": self.settings_select_dirs.get(),
            "select_files": self.settings_select_files.get(),
        }

        settings_json = dumps(settings)

        if not exists(self.appdata_dir):
            mkdir(self.appdata_dir)

        with open(self.appdata_path, "w+") as settings_file:
            settings_file.write(settings_json)

        if self.dialog_showing.get() == 1:
            self.ufd.cancel()

        self.master.destroy()

    def toplevel_close(self, dialog, boolean):
        """
            This callback flips the value for a given toplevel_showing boolean
            to false, before disposing of the toplevel.
        """

        boolean.set(0)
        dialog.destroy()

    def swap_selected(self):
        """Swap list entries between source & destination"""

        source_selection = list(self.list_box_source.curselection())
        dest_selection = list(self.list_box_dest.curselection())

        for i in reversed(source_selection):
            item = self.list_box_source.get(i)
            self.list_box_source.delete(i)
            self.list_box_dest.insert("0", item)

        for i in reversed(dest_selection):
            item = self.list_box_dest.get(i)
            self.list_box_dest.delete(i)
            self.list_box_source.insert("0", item)

    def clear_selected(self):
        """Removes selected (highlighted) item(s) from a given listbox"""

        source_selection = list(self.list_box_source.curselection())
        dest_selection = list(self.list_box_dest.curselection())

        if source_selection:
            for i in reversed(source_selection):
                self.list_box_source.delete(i)

            self.list_box_source.selection_set(source_selection[0])

        if dest_selection:
            for i in reversed(dest_selection):
                self.list_box_dest.delete(i)

            self.list_box_dest.selection_set(dest_selection[0])

    def clear_all(self):
        """Clears both listboxes in the main UI, resetting the form."""

        self.list_box_source.delete(0, "end")
        self.list_box_dest.delete(0, "end")

    def handled(fn):
        """Filesystem operations are wrapped here for error handling"""
        @wraps(fn)
        def inner(self, *args, **kwargs):
            try:
                fn(self, *args, **kwargs)
                return True
            except (PermissionError, FileNotFoundError) as err:
                self.skipped_err.append(f"{err.args[1]}:\n" +
                                        (" => ".join(args)))
                return False

        return inner

    @handled
    def _copy(self, path, destination):
        """Wrapper for shutil.copy2() || shutil.copytree()"""

        if isfile(path):
            copy2(path, destination)
        else:
            copytree(path, destination)

    @handled
    def _move(self, path, destination):
        """Wrapper for shutil.move()"""

        move(path, destination)

    @handled
    def _delete(self, path):
        """Wrapper for os.remove() || shutil.rmtree()"""

        if isfile(path):
            remove(path)
        elif isdir(path):
            rmtree(path)

    def disabled_ui(fn):
        """Menubar is disabled during operations"""
        @wraps(fn)
        def inner(self, *args, **kwargs):
            self.main_menu.entryconfig("File", state="disabled")
            self.main_menu.entryconfig("Settings", state="disabled")
            self.main_menu.entryconfig("Clear Selected", state="disabled")
            self.main_menu.entryconfig("Clear All", state="disabled")
            self.main_menu.entryconfig("COPY", state="disabled")
            self.main_menu.entryconfig("MOVE", state="disabled")

            fn(self, *args, **kwargs)

            self.main_menu.entryconfig("File", state="normal")
            self.main_menu.entryconfig("Settings", state="normal")
            self.main_menu.entryconfig("Clear Selected", state="normal")
            self.main_menu.entryconfig("Clear All", state="normal")
            self.main_menu.entryconfig("COPY", state="normal")
            self.main_menu.entryconfig("MOVE", state="normal")

        return inner

    def _submit(self, copy):
        """Thread/wrapper for submit() so we don't block the UI during operations"""

        self.thread = Thread(target=self.submit, args=(copy, ), daemon=True)
        self.thread.start()

    @disabled_ui
    def submit(self, copy):
        """
            Move or copy each item in the origin list to the path in the
            destination list. Supports no more than one destination directory
            where copy == False.

            Ask Overwrite and Rename Dupes will alter the way we handle 
            existing data standing in the way. By default, duplicates are 
            renamed with an index. A messagebox can complain to the user
            if shutil raises a PermissionError, and the operation is skipped.
        """

        if (self.list_box_dest.size() > 1) and not copy:
            messagebox.showwarning(
                "Invalid Operation",
                "Move operation only supports a single destination directory.")
            return

        sources = self.list_box_source.get(0, "end")
        destinations = self.list_box_dest.get(0, "end")

        self.skipped_err = []

        for j, destination in enumerate(destinations):

            if isfile(destination):
                self.skipped_err.append(f"Invalid destination: {destination}")
                continue

            for i, source in enumerate(sources):
                self.progress(i, j)

                (_, filename) = split(source)
                future_destination = join(destination + sep, filename)

                if exists(future_destination):
                    if not self.settings_ask_overwrite.get() \
                    and not self.settings_rename_dupes.get():

                        if not self._delete(future_destination):
                            continue

                    if self.settings_ask_overwrite.get():

                        if self.ask_overwrite(future_destination):
                            if not self._delete(future_destination):
                                continue

                        else:
                            continue

                    if self.settings_rename_dupes.get():
                        future_destination = self.name_dupe(future_destination)

                if copy:
                    if not self._copy(source, future_destination):
                        continue
                else:
                    if not self._move(source, future_destination):
                        continue

        self.list_box_source.delete(0, "end")
        self.list_box_dest.delete(0, "end")

        if self.skipped_err:
            messagebox.showerror(title="Error(s)",
                                 message="\n\n".join(self.skipped_err))

    @staticmethod
    def name_dupe(path):
        """
            Renames the file or directory until it doesn't exist
            in the destination with that name anymore, by appending
            the filename with an index wrapped in parenthesis.
            (Windows platforms)
            file.txt => file (1).txt => file (2).txt
        """

        if system() != "Windows":
            raise OSError("For use with Windows filesystems.")

        path_ = path
        (root, filename) = split(path_)

        if isdir(path_):
            title = filename
            ext = None
        else:
            (title, ext) = splitext(filename)

        filecount = 0
        while exists(path_):
            filecount += 1
            new_title = title + " (" + str(filecount) + ")"
            if ext:
                new_title = new_title + ext
            path_ = join(root, new_title)

        return path_

    def ask_overwrite(self, future_destination):
        """Messagebox result returned as truth value"""

        return messagebox.askyesno(
            title="Path Conflict",
            message=f"Overwrite:\n\n{future_destination}?\n\n" \
            f"YES - Overwrite\nNO - Skip"
        )

    def progress(self, i, j):
        """
            Visualize operands in GUI during operations

            i = current source operand index
            j = current destination operand index
        """

        for y, _ in enumerate(self.list_box_source.get(0, "end")):
            if y != i:
                self.list_box_source.itemconfigure(y,
                                                   bg="#FFFFFF",
                                                   fg="#000000")
            else:
                self.list_box_source.itemconfigure(y,
                                                   bg="#cccccc",
                                                   fg="#000000")

        for x, _ in enumerate(self.list_box_dest.get(0, "end")):
            if x != j:
                self.list_box_dest.itemconfigure(x, bg="#FFFFFF", fg="#000000")
            else:
                self.list_box_dest.itemconfigure(x, bg="#cccccc", fg="#000000")

        self.master.update()

    #Toplevels:
    def show_about(self):
        """
            Displays a static dialog that doesn't allow additional
            instances of itself to be created while showing.
        """

        if self.about_showing.get() == 0:
            self.about_showing.set(1)

            try:
                with open(f"{dirname(__file__)}/about.txt", "r") as aboutfile:
                    about_info = aboutfile.read()
            except FileNotFoundError:
                messagebox.showerror("Error", "File not found")
                self.about_showing.set(0)
                return

            else:
                self.about = Toplevel()
                self.about.title("About")
                self.about.iconbitmap(f"{dirname(__file__)}/icon.ico")

                self.about.geometry("600x400")
                self.about.resizable(0, 0)
                self.about.update_idletasks()
                (width_offset, height_offset) = Ufd.get_offset(self.about)
                self.about.geometry(f"+{width_offset-75}+{height_offset-75}")
                self.about.update_idletasks()

                self.about_message = Label(
                    self.about,
                    text=about_info,
                    justify="left",
                    wraplength=(self.about.winfo_width() - 25))

                self.about_message.grid(sticky="nsew")

                self.about.protocol(
                    "WM_DELETE_WINDOW", lambda: self.toplevel_close(
                        self.about, self.about_showing))

    def show_help(self):
        """
            Displays a scrollable dialog that doesn't allow additional
            instances of itself to be created while showing.
        """

        if self.help_showing.get() == 0:
            self.help_showing.set(1)

            try:
                with open(f"{dirname(__file__)}/help.txt", "r") as helpfile:
                    help_info = helpfile.read()
            except FileNotFoundError:
                messagebox.showerror("Error", "File not found")
                self.help_showing.set(0)
                return

            else:
                self.help_window = Toplevel()
                self.help_window.title("Help")
                self.help_window.iconbitmap(f"{dirname(__file__)}/icon.ico")

                self.help_window.geometry("500x300")
                self.help_window.update_idletasks()
                (width_offset,
                 height_offset) = Ufd.get_offset(self.help_window)
                self.help_window.geometry(
                    f"+{width_offset+75}+{height_offset-75}")
                self.help_window.update_idletasks()

                self.message_y_scrollbar = Scrollbar(self.help_window,
                                                     orient="vertical")

                self.help_text = Text(
                    self.help_window,
                    wrap="word",
                    yscrollcommand=self.message_y_scrollbar.set)

                self.help_window.rowconfigure(0, weight=1)
                self.help_window.columnconfigure(0, weight=1)

                self.help_text.grid(row=0, column=0, sticky="nsew")
                self.message_y_scrollbar.grid(row=0, column=1, sticky="nse")

                self.message_y_scrollbar.config(command=self.help_text.yview)

                self.help_text.insert("end", help_info)
                self.help_text.config(state="disabled")

                self.help_window.protocol(
                    "WM_DELETE_WINDOW", lambda: self.toplevel_close(
                        self.help_window, self.help_showing))

    def show_ufd(self, source=True):
        """ Display Ufd w/ appropriate kwargs => Populate GUI w/ result"""

        if self.dialog_showing.get() == 0:
            self.dialog_showing.set(1)

            self.ufd = Ufd(title="Add Items",
                           show_hidden=self.settings_show_hidden.get(),
                           include_files=self.settings_include_files.get(),
                           multiselect=self.settings_multiselect.get(),
                           select_dirs=self.settings_select_dirs.get(),
                           select_files=self.settings_select_files.get(),
                           unix_delimiter=False,
                           stdout=False)

            for result in self.ufd():
                if source:
                    self.list_box_source.insert("end", result)
                else:
                    self.list_box_dest.insert("end", result)

            self.dialog_showing.set(0)
Ejemplo n.º 27
0
file_menu.add_command(label='New',
                      accelerator='Ctrl+N',
                      compound='left',
                      underline=0)
file_menu.add_command(label='Open',
                      accelerator='Ctrl+O',
                      compound='left',
                      underline=0)
file_menu.add_command(label='Save',
                      accelerator='Ctrl+S',
                      compound='left',
                      underline=0)
file_menu.add_command(label='Save as',
                      accelerator='Shift+Ctrl+S',
                      compound='left')
edit_menu.add_separator()
file_menu.add_command(label='Exit', accelerator='Alt+F4', compound='left')

edit_menu.add_command(label='Undo', accelerator='Ctrl+Z', compound='left')
edit_menu.add_command(label='Redo', accelerator='Ctrl+Y', compound='left')
edit_menu.add_separator()
edit_menu.add_command(label='Cut', accelerator='Ctrl+X', compound='left')
edit_menu.add_command(label='Copy', accelerator='Ctrl+C', compound='left')
edit_menu.add_command(label='Paste', accelerator='Ctrl+V', compound='left')
edit_menu.add_separator()
edit_menu.add_command(label='Find', accelerator='Ctrl+F', compound='left')
edit_menu.add_separator()
edit_menu.add_command(label='Select All',
                      accelerator='Ctrl+A',
                      compound='left')
    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Reset Parser",
                             underline=0,
                             command=self.reset,
                             accelerator="Del")
        filemenu.add_command(
            label="Print to Postscript",
            underline=0,
            command=self.postscript,
            accelerator="Ctrl-p",
        )
        filemenu.add_command(label="Exit",
                             underline=1,
                             command=self.destroy,
                             accelerator="Ctrl-x")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(
            label="Edit Grammar",
            underline=5,
            command=self.edit_grammar,
            accelerator="Ctrl-g",
        )
        editmenu.add_command(
            label="Edit Text",
            underline=5,
            command=self.edit_sentence,
            accelerator="Ctrl-t",
        )
        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label="Step",
                             underline=1,
                             command=self.step,
                             accelerator="Space")
        rulemenu.add_separator()
        rulemenu.add_command(label="Match",
                             underline=0,
                             command=self.match,
                             accelerator="Ctrl-m")
        rulemenu.add_command(label="Expand",
                             underline=0,
                             command=self.expand,
                             accelerator="Ctrl-e")
        rulemenu.add_separator()
        rulemenu.add_command(label="Backtrack",
                             underline=0,
                             command=self.backtrack,
                             accelerator="Ctrl-b")
        menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(
            label="Show Grammar",
            underline=0,
            variable=self._show_grammar,
            command=self._toggle_grammar,
        )
        viewmenu.add_separator()
        viewmenu.add_radiobutton(
            label="Tiny",
            variable=self._size,
            underline=0,
            value=10,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Small",
            variable=self._size,
            underline=0,
            value=12,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Medium",
            variable=self._size,
            underline=0,
            value=14,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Large",
            variable=self._size,
            underline=0,
            value=18,
            command=self.resize,
        )
        viewmenu.add_radiobutton(
            label="Huge",
            variable=self._size,
            underline=0,
            value=24,
            command=self.resize,
        )
        menubar.add_cascade(label="View", underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(
            label="Slow Animation",
            underline=0,
            variable=self._animation_frames,
            value=10,
            accelerator="-",
        )
        animatemenu.add_radiobutton(
            label="Normal Animation",
            underline=0,
            variable=self._animation_frames,
            value=5,
            accelerator="=",
        )
        animatemenu.add_radiobutton(
            label="Fast Animation",
            underline=0,
            variable=self._animation_frames,
            value=2,
            accelerator="+",
        )
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        helpmenu.add_command(label="Instructions",
                             underline=0,
                             command=self.help,
                             accelerator="F1")
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)
Ejemplo n.º 29
0
style.configure("black.Horizontal.TProgressbar", background='black')

bar = Progressbar(window, length=200, style='black.Horizontal.TProgressbar')

bar['value'] = 70

bar.grid(column=0, row=10)

from tkinter import Menu

menu = Menu(window)

new_item = Menu(menu, tearoff=0)

new_item.add_command(label='New')
new_item.add_separator()

new_item.add_command(label='Edit')

new_item.add_separator()

new_item.add_command(label='Print')

menu.add_cascade(label='File', menu=new_item)

window.config(menu=menu)

from tkinter import *

from tkinter import messagebox
    def createWidgets(self):
        # Tab Control introduced here --------------------------------------
        tabControl = ttk.Notebook(self.win)  # Create Tab Control

        tab1 = ttk.Frame(tabControl)  # Create a tab
        tabControl.add(tab1, text='Tab 1')  # Add the tab

        tab2 = ttk.Frame(tabControl)  # Add a second tab
        tabControl.add(tab2, text='Tab 2')  # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible
        # ~ Tab Control introduced here -----------------------------------------

        # We are creating a container frame to hold all other widgets
        self.monty = ttk.LabelFrame(tab1, text=' Mighty Python ')
        self.monty.grid(column=0, row=0, padx=8, pady=4)

        # Changing our Label
        ttk.Label(self.monty, text="Enter a name:").grid(column=0,
                                                         row=0,
                                                         sticky='W')

        # Adding a Textbox Entry widget
        self.name = tk.StringVar()
        nameEntered = ttk.Entry(self.monty, width=12, textvariable=self.name)
        nameEntered.grid(column=0, row=1, sticky='W')

        # Adding a Button
        self.action = ttk.Button(self.monty,
                                 text="Click Me!",
                                 command=self.clickMe)
        self.action.grid(column=2, row=1)

        ttk.Label(self.monty, text="Choose a number:").grid(column=1, row=0)
        number = tk.StringVar()
        numberChosen = ttk.Combobox(self.monty, width=12, textvariable=number)
        numberChosen['values'] = (1, 2, 4, 42, 100)
        numberChosen.grid(column=1, row=1)
        numberChosen.current(0)

        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.monty,
                            values=(1, 2, 4, 42, 100),
                            width=5,
                            bd=8,
                            command=self._spin)
        self.spin.grid(column=0, row=2)

        # Using a scrolled Text control
        scrolW = 30
        scrolH = 3
        self.scr = scrolledtext.ScrolledText(self.monty,
                                             width=scrolW,
                                             height=scrolH,
                                             wrap=tk.WORD)
        self.scr.grid(column=0, row=3, sticky='WE', columnspan=3)

        #-------------------------------------------------------------------------
        # Adding another Button
        self.action = ttk.Button(self.monty,
                                 text="Clear Text",
                                 command=self.clearScrol)
        self.action.grid(column=2, row=2)

        # Adding more Feature Buttons
        startRow = 4
        for idx in range(12):
            if idx < 2:
                colIdx = idx
                col = colIdx
            else:
                col += 1
            if not idx % 3:
                startRow += 1
                col = 0

            b = ttk.Button(self.monty, text="Feature " + str(idx + 1))
            b.grid(column=col, row=startRow)

        ###########################
        # Tab Control 2 refactoring  -----------------------------------------
        # We are creating a container frame to hold all other widgets -- Tab2
        self.monty2 = ttk.LabelFrame(tab2, text=' Holy Grail ')
        self.monty2.grid(column=0, row=0, padx=8, pady=4)
        # Creating three checkbuttons
        chVarDis = tk.IntVar()
        check1 = tk.Checkbutton(self.monty2,
                                text="Disabled",
                                variable=chVarDis,
                                state='disabled')
        check1.select()
        check1.grid(column=0, row=0, sticky=tk.W)

        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.monty2,
                                     text="UnChecked",
                                     variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W)

        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.monty2,
                                     text="Toggle",
                                     variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)

        # trace the state of the two checkbuttons
        self.chVarUn.trace(
            'w', lambda unused0, unused1, unused2: self.checkCallback())
        self.chVarEn.trace(
            'w', lambda unused0, unused1, unused2: self.checkCallback())
        # ~ Tab Control 2 refactoring  -----------------------------------------

        # Radiobutton list
        colors = ["Blue", "Gold", "Red"]

        self.radVar = tk.IntVar()

        # Selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = 'rad' + str(col)
            curRad = tk.Radiobutton(self.monty2,
                                    text=colors[col],
                                    variable=self.radVar,
                                    value=col,
                                    command=self.radCall)
            curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            tt.createToolTip(curRad, 'This is a Radiobutton control.')

        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.monty2, text=' Labels in a Frame ')
        labelsFrame.grid(column=0, row=7)

        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text="Label1").grid(column=0, row=0)
        ttk.Label(labelsFrame, text="Label2").grid(column=0, row=1)

        # Add some space around each label
        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=8)

        # Creating a Menu Bar
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label="New")
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self._quit)
        menuBar.add_cascade(label="File", menu=fileMenu)

        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label="About")
        menuBar.add_cascade(label="Help", menu=helpMenu)

        # Change the main windows icon
        self.win.iconbitmap('pyc.ico')

        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')
        print(strData.get())

        # Default tkinter Variable Classes
        intData = tk.IntVar()
        print(intData.get())
        print(tk.DoubleVar())
        print(tk.BooleanVar())

        # It is not necessary to create a tk.StringVar()
        strData = tk.StringVar()
        strData = self.spin.get()
        print("Hello " + strData)

        # Printing the Global works
        print(GLOBAL_CONST)

        # call method
        self.usingGlobal()

        # Place cursor into name Entry
        nameEntered.focus()

        # Add a Tooltip to the Spinbox
        tt.createToolTip(self.spin, 'This is a Spin control.')

        # Add Tooltips to more widgets
        tt.createToolTip(nameEntered, 'This is an Entry control.')
        tt.createToolTip(self.action, 'This is a Button control.')
        tt.createToolTip(self.scr, 'This is a ScrolledText control.')
Ejemplo n.º 31
0
from tkinter import Toplevel, Button, Tk, Menu
top= Tk()
menubar= Menu(top)
file= Menu(menubar,tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save As")
file.add_separator()
file.add_command(label="Page setup")
file.add_command(label="Print")
file.add_separator()
file.add_command(label="Exit",command= top.quit)
menubar.add_cascade(label="File",menu= file)

Edit=Menu(menubar,tearoff=0)
Edit.add_command(label='undo')
Edit.add_separator()
Edit.add_command(label='Cut')
Edit.add_command(label='Copy')
Edit.add_command(label='Paste')
Edit.add_command(label='Delete')
Edit.add_separator()
Edit.add_command(label='Find')
Edit.add_command(label='Find next')
Edit.add_command(label='Replace')
Edit.add_command(label='Delete')
Edit.add_command(label='Goto')
Edit.add_separator()
Edit.add_command(label='Select All')
Edit.add_command(label='Time/Date')
Ejemplo n.º 32
0
# *************************** Create the Window Objects **************************

root = tk.Tk()  # ************ Main (root) Window
root.option_add('*tearOff', False)
root.title('Trim Training Needs Report')
root.geometry('650x350+200+200')
root.minsize(650, 300)
menubar = Menu(root)
root.config(menu=menubar)
file = Menu(menubar)
help_ = Menu(menubar)
menubar.add_cascade(menu=file, label="File")
menubar.add_cascade(menu=help_, label="Help")
file.add_command(label='Open...', command=lambda: get_file())
file.add_separator()
file.add_command(label='Exit', command=lambda: end_prog())
help_.add_command(label='About', command=lambda: about_message())

filename = "No file"
out_path = "No Path"
l_text = tk.StringVar()
result_text = tk.StringVar()
result_text.set("Results: ")
op_text = tk.StringVar()
op_text.set("                   ")
bg_color = '#BED8BC'

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))
mainframe.config(relief=tk.RIDGE, borderwidth=5, style='TFrame')
Ejemplo n.º 33
0
    def __init__(self, topWindow):
        #construct the main (top) window
        Frame.__init__(self, topWindow)
        #self.master  = topWindow

        #set topWindow to XGA resolution
        topWindow.geometry('%dx%d' % (1024, 768))
        #topWindow.minsize(1152,864)

        #definte winow title
        topWindow.title("RadarWorld1")

        #define the ratio of the columns and rows, grid geom. manager will bu used
        topWindow.columnconfigure(0, weight=20)
        topWindow.columnconfigure(1, weight=80)
        topWindow.rowconfigure(0, weight=90)
        topWindow.rowconfigure(1, weight=3)
        topWindow.rowconfigure(2, weight=1)

        #define left side frame INSIDE row=col=0 to place the controls
        #Two Columns and as many rows as needed
        leftSideControlsFrame = LabelFrame(topWindow,
                                           bd=3,
                                           relief=GROOVE,
                                           text="Radar Controls")
        leftSideControlsFrame.grid(row=0, column=0, sticky=W + E + N + S)
        leftSideControlsFrame.columnconfigure(0, weight=1)
        leftSideControlsFrame.rowconfigure(0, weight=1)
        leftSideControlsFrame.rowconfigure(1, weight=1)
        leftSideControlsFrame.rowconfigure(2, weight=98)

        #define right side frame inside row=col=1 to place the controls
        rightSideControlsFrame = Frame(topWindow)
        rightSideControlsFrame.grid(row=0, column=1, sticky=W + E + N + S)
        rightSideControlsFrame.columnconfigure(
            0, weight=1)  # an empty column must be defined for the widgets

        #build the topwindow
        self.grid(sticky=W + E + N + S)

        #* * * * * * define the Ui elements * * * * * *
        # Menubar:
        menubar = Menu(topWindow)
        topWindow.config(menu=menubar)
        # Menubar - File Menu:
        fileMenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Open", command=MainWindow.doNothing)
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=MainWindow.quit)
        # Menubar - Edit Menu:
        editMenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Edit", menu=editMenu)
        editMenu.add_command(label="Settings", command=MainWindow.doNothing)
        # Menubar - Help Menu:
        helpMenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Help", menu=helpMenu)
        helpMenu.add_command(label="About", command=MainWindow.helpMenu_About)

        # - - - - - Left side elements (controls) - - - - - -
        spaceHolder = Label(leftSideControlsFrame,
                            text="Avaiable Interfaces:",
                            bd=1,
                            relief=FLAT,
                            anchor=W)
        spaceHolder.grid(row=0, column=0, padx=10, pady=0, sticky=W + N + E)

        self.serialPortCmbBox = Combobox(
            leftSideControlsFrame, values=serialSystemClass.getSerialPorts())
        self.serialPortCmbBox.current(0)
        self.serialPortCmbBox.grid(row=1,
                                   column=0,
                                   padx=0,
                                   pady=0,
                                   columnspan=2,
                                   sticky=W + E + N + S)
        self.serialPortCmbBox.bind('<<ComboboxSelected>>',
                                   self.on_serialPortCmbBox_select)

        # - - - - - Right side elements (graph) - - - - - - -
        canvasForGraph = FigureCanvasTkAgg(
            FigureRightSide, master=rightSideControlsFrame
        )  #create canvas for figure int the frame
        canvasForGraph.get_tk_widget().grid(sticky=S + W + N + E)

        # Log Window:
        self.scrolled_text = ScrolledText(topWindow, height=5)
        self.scrolled_text.configure(font='TkFixedFont')
        self.scrolled_text.tag_config('INFO', foreground='black')
        #self.scrolled_text.insert(END, "hello")

        # Status bar:
        self.statusbarText = StringVar()
        self.statusBar = Label(topWindow,
                               textvariable=self.statusbarText,
                               bd=5,
                               relief=SUNKEN,
                               anchor=N + E,
                               fg="blue4",
                               bg="gray80")
        self.statusBar.grid(row=2, column=0, sticky=W + E + N + S)
        # Clock:
        self.clockText = StringVar()
        self.clock = Label(topWindow,
                           textvariable=self.clockText,
                           bd=10,
                           relief=SUNKEN,
                           anchor=N + W,
                           fg="green",
                           bg="yellow")
        self.clock.grid(row=2, column=1, sticky=W + E + N + S)
Ejemplo n.º 34
0
    def __init__(self, parent):

        Menu.__init__(self, parent)

        self.parent = parent

        menu_file = Menu(self, tearoff=0)
        menu_file.add_command(compound='left',
                              image=icons['actions']['new']['generic'], label='New...', command=new_file)
        menu_file.add_command(compound='left',
                              image=icons['actions']['open']['file'], label='Open...', command=open_files)
        menu_file.add_command(compound='left',
                              image=icons['actions']['open']['folder'], label='Open Folder...', command=open_folder)
        menu_file.add_command(compound='left',
                              image=icons['actions']['open']['mc_folder'],
                              label='Open Minecraft Save Folder...', command=open_mc_dir)
        menu_file.add_separator()
        menu_file.add_command(compound='left', image=icons['actions']['save'], label='Save...', command=save_files)
        menu_file.add_command(compound='left', image=icons['actions']['refresh'],
                              label='Refresh', command=refresh_files)
        menu_file.add_separator()
        menu_file.add_command(compound='left', image=icons['actions']['exit'], label='Exit', command=root.quit)

        menu_edit = Menu(self, tearoff=0)
        menu_edit.add_command(compound='left', image=icons['actions']['copy'], label='Copy')
        menu_edit.add_command(compound='left', image=icons['actions']['cut'], label='Cut')
        menu_edit.add_command(compound='left', image=icons['actions']['paste'], label='Paste')
        menu_edit.add_separator()
        menu_edit.add_command(compound='left', image=icons['actions']['rename'], label='Rename')
        menu_edit.add_command(compound='left', image=icons['actions']['edit'], label='Edit')
        menu_edit.add_command(compound='left', image=icons['actions']['delete'], label='Delete')
        menu_edit.add_separator()
        menu_edit.add_command(compound='left', image=icons['actions']['move']['up'], label='Move Up')
        menu_edit.add_command(compound='left', image=icons['actions']['move']['down'], label='Move Down')

        menu_search = Menu(self, tearoff=0)
        menu_search.add_command(compound='left', image=icons['actions']['search'], label='Find')
        menu_search.add_command(compound='left', image=icons['actions']['move']['right'], label='Find Next')
        menu_search.add_separator()
        menu_search.add_command(compound='left', image=icons['actions']['replace'], label='Replace')
        menu_search.add_separator()
        menu_search.add_command(compound='left', image=icons['actions']['chunk_find'], label='Chunk Finder')

        menu_help = Menu(self, tearoff=0)
        menu_help.add_command(compound='left', image=icons['about'], label='About')

        self.add_cascade(label='File', menu=menu_file)
        self.add_cascade(label='Edit', menu=menu_edit)
        self.add_cascade(label='Search', menu=menu_search)
        self.add_cascade(label='Help', menu=menu_help)
    save_bank()
    root.destroy()
    sys.exit()


def sound_off():
    """Switch sound effects off from drop down menu."""
    Glo.sound_fx = False


def sound_on():
    """Switch sound effects on from drop down menu."""
    Glo.sound_fx = True


# Drop-down menu.
MENU_BAR = Menu(root)
FILE_MENU = Menu(MENU_BAR, tearoff=0)
MENU_BAR.add_cascade(label='Menu', menu=FILE_MENU)
FILE_MENU.add_command(label='Sound fx ON', command=sound_on)
FILE_MENU.add_command(label='Sound fx OFF', command=sound_off)
FILE_MENU.add_command(label='About', command=about_menu)
FILE_MENU.add_separator()
FILE_MENU.add_command(label='Visit blog', command=visit_blog)
FILE_MENU.add_command(label='Exit', command=exit_app)
root.config(menu=MENU_BAR)

start_game()

root.mainloop()
Ejemplo n.º 36
0
 def _init_menu(self):
     file_menu = Menu(self, tearoff=0)
     file_menu.add_command(label="Delete cache", command=self._cache_handler.purge_all_caches)
     file_menu.add_separator()
     file_menu.add_command(label="Exit", command=self.master.quit)
     self.add_cascade(label="File", menu=file_menu)
    def create_widgets(self):
        tabControl = ttk.Notebook(self.win)  # Create Tab Control

        tab1 = ttk.Frame(tabControl)  # Create a tab
        tabControl.add(tab1, text='Tab 1')  # Add the tab
        tab2 = ttk.Frame(tabControl)  # Add a second tab
        tabControl.add(tab2, text='Tab 2')  # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible

        # LabelFrame using tab1 as the parent
        mighty = ttk.LabelFrame(tab1, text=' Mighty Python ')
        mighty.grid(column=0, row=0, padx=8, pady=4)

        # Modify adding a Label using mighty as the parent instead of win
        a_label = ttk.Label(mighty, text="Enter a name:")
        a_label.grid(column=0, row=0, sticky='W')

        # Adding a Textbox Entry widget
        self.name = tk.StringVar()
        self.name_entered = ttk.Entry(mighty, width=24, textvariable=self.name)
        self.name_entered.grid(column=0, row=1, sticky='W')

        # Adding a Button
        self.action = ttk.Button(mighty,
                                 text="Click Me!",
                                 command=self.click_me)
        self.action.grid(column=2, row=1)

        ttk.Label(mighty, text="Choose a number:").grid(column=1, row=0)
        number = tk.StringVar()
        self.number_chosen = ttk.Combobox(mighty,
                                          width=14,
                                          textvariable=number,
                                          state='readonly')
        self.number_chosen['values'] = (1, 2, 4, 42, 100)
        self.number_chosen.grid(column=1, row=1)
        self.number_chosen.current(0)

        # Adding a Spinbox widget
        self.spin = Spinbox(mighty,
                            values=(1, 2, 4, 42, 100),
                            width=5,
                            bd=9,
                            command=self._spin)  # using range
        self.spin.grid(column=0, row=2, sticky='W')  # align left

        # Using a scrolled Text control
        scrol_w = 40
        scrol_h = 10  # increase sizes
        self.scrol = scrolledtext.ScrolledText(mighty,
                                               width=scrol_w,
                                               height=scrol_h,
                                               wrap=tk.WORD)
        self.scrol.grid(column=0, row=3, sticky='WE', columnspan=3)

        for child in mighty.winfo_children(
        ):  # add spacing to align widgets within tabs
            child.grid_configure(padx=4, pady=2)

        #=====================================================================================
        # Tab Control 2 ----------------------------------------------------------------------
        self.mighty2 = ttk.LabelFrame(tab2, text=' The Snake ')
        self.mighty2.grid(column=0, row=0, padx=8, pady=4)

        # Creating three checkbuttons
        chVarDis = tk.IntVar()
        check1 = tk.Checkbutton(self.mighty2,
                                text="Disabled",
                                variable=chVarDis,
                                state='disabled')
        check1.select()
        check1.grid(column=0, row=0, sticky=tk.W)

        chVarUn = tk.IntVar()
        check2 = tk.Checkbutton(self.mighty2,
                                text="UnChecked",
                                variable=chVarUn)
        check2.deselect()
        check2.grid(column=1, row=0, sticky=tk.W)

        chVarEn = tk.IntVar()
        check3 = tk.Checkbutton(self.mighty2, text="Enabled", variable=chVarEn)
        check3.deselect()
        check3.grid(column=2, row=0, sticky=tk.W)

        # trace the state of the two checkbuttons
        chVarUn.trace('w',
                      lambda unused0, unused1, unused2: self.checkCallback())
        chVarEn.trace('w',
                      lambda unused0, unused1, unused2: self.checkCallback())

        # First, we change our Radiobutton global variables into a list
        colors = ["Blue", "Gold", "Red"]

        # create three Radiobuttons using one variable
        self.radVar = tk.IntVar()

        # Next we are selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Now we are creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = tk.Radiobutton(self.mighty2,
                                    text=colors[col],
                                    variable=self.radVar,
                                    value=col,
                                    command=self.radCall)
            curRad.grid(column=col, row=1, sticky=tk.W)  # row=6
            # And now adding tooltips
            ToolTip(curRad, 'This is a Radiobutton control')

        # Add a Progressbar to Tab 2
        self.progress_bar = ttk.Progressbar(tab2,
                                            orient='horizontal',
                                            length=286,
                                            mode='determinate')
        self.progress_bar.grid(column=0, row=3, pady=2)

        # Create a container to hold buttons
        buttons_frame = ttk.LabelFrame(self.mighty2, text=' ProgressBar ')
        buttons_frame.grid(column=0, row=2, sticky='W', columnspan=2)

        # Add Buttons for Progressbar commands
        ttk.Button(buttons_frame,
                   text=" Run Progressbar   ",
                   command=self.run_progressbar).grid(column=0,
                                                      row=0,
                                                      sticky='W')
        ttk.Button(buttons_frame,
                   text=" Start Progressbar  ",
                   command=self.start_progressbar).grid(column=0,
                                                        row=1,
                                                        sticky='W')
        ttk.Button(buttons_frame,
                   text=" Stop immediately ",
                   command=self.stop_progressbar).grid(column=0,
                                                       row=2,
                                                       sticky='W')
        ttk.Button(buttons_frame,
                   text=" Stop after second ",
                   command=self.progressbar_stop_after).grid(column=0,
                                                             row=3,
                                                             sticky='W')

        for child in buttons_frame.winfo_children():
            child.grid_configure(padx=2, pady=2)

        for child in self.mighty2.winfo_children():
            child.grid_configure(padx=8, pady=2)

        # Creating a Menu Bar
        menu_bar = Menu(self.win)
        self.win.config(menu=menu_bar)

        # Add menu items
        file_menu = Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="New")
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=self._quit)
        menu_bar.add_cascade(label="File", menu=file_menu)

        # Display a Message Box
        def _msgBox():
            msg.showinfo(
                'Python Message Info Box',
                'A Python GUI created using tkinter:\nThe year is 2019.')

        # Add another Menu to the Menu Bar and an item
        help_menu = Menu(menu_bar, tearoff=0)
        help_menu.add_command(
            label="About", command=_msgBox)  # display messagebox when clicked
        menu_bar.add_cascade(label="Help", menu=help_menu)

        # Change the main windows icon
        self.win.iconbitmap('pyc.ico')

        # It is not necessary to create a tk.StringVar()
        # strData = tk.StringVar()
        strData = self.spin.get()

        # call function
        self.usingGlobal()

        self.name_entered.focus()

        # Add Tooltips -----------------------------------------------------
        # Add a Tooltip to the Spinbox
        ToolTip(self.spin, 'This is a Spinbox control')

        # Add Tooltips to more widgets
        ToolTip(self.name_entered, 'This is an Entry control')
        ToolTip(self.action, 'This is a Button control')
        ToolTip(self.scrol, 'This is a ScrolledText control')
Ejemplo n.º 38
0
class PypeTkPad(object):
    def __init__(self, master, queue, pypeOutput):

        self.queue = queue
        self.pypeOutput = pypeOutput

        self.master = master
        self.master.title('PypePad')
        self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0))
        self.master.minsize(300, 100)
        self.output_file_name = None

        self.BuildMainFrame()
        self.UpdateOutput()

    def NewCommand(self):
        self.ClearAllCommand()

    def OpenCommand(self):
        import tkinter.filedialog
        from tkinter import END
        openfile = tkinter.filedialog.askopenfile()
        if not openfile:
            return
        for line in openfile.readlines():
            self.text_input.insert(END, line)

    def SaveCommand(self):
        import tkinter.filedialog
        from tkinter import END
        saveasfile = tkinter.filedialog.asksaveasfile()
        if not saveasfile:
            return
        alltext = self.text_input.get("1.0", END)
        saveasfile.write(alltext)

    def QuitCommand(self):
        self.master.quit()

    def ClearInputCommand(self):
        from tkinter import END
        self.text_input.delete("1.0", END)

    def ClearOutputCommand(self):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.delete("1.0", END)
        self.text_output["state"] = DISABLED
        self.text_output.see(END)
        self.text_output.update()

    def ClearAllCommand(self):
        self.ClearInputCommand()
        self.ClearOutputCommand()

    def OutputFileCommand(self):
        import tkinter.filedialog
        outputfilename = tkinter.filedialog.asksaveasfilename()
        if sys.platform == 'win32' and len(outputfilename.split()) > 1:
            outputfilename = '"%s"' % outputfilename
        self.output_file_name = outputfilename

    def AboutCommand(self):
        self.OutputText('\n')
        self.OutputText(
            '* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n')
        self.OutputText('\n')

    def UpdateOutput(self):
        if self.pypeOutput:
            text = self.pypeOutput.pop(0)
            self.output_stream.write(text)
        self.master.after(10, self.UpdateOutput)

    def RunPype(self, arguments):
        if not arguments:
            return
        if self.output_to_file.get() is not 'n' and self.output_file_name:
            self.output_stream.output_to_file = True
            self.output_stream.output_file = open(self.output_file_name,
                                                  self.output_to_file.get())
        else:
            self.output_stream.output_to_file = False

        self.queue.append(arguments)

    def GetWordUnderCursor(self):
        from tkinter import CURRENT
        splitindex = self.text_input.index(CURRENT).split('.')
        line = self.text_input.get(splitindex[0] + ".0",
                                   splitindex[0] + ".end")
        wordstart = line.rfind(' ', 0, int(splitindex[1]) - 1) + 1
        wordend = line.find(' ', int(splitindex[1]))
        if wordend == -1:
            wordend = len(line)
        word = line[wordstart:wordend]
        return word

    def GetWordIndex(self):
        startindex = self.text_input.index("insert-1c wordstart")
        endindex = self.text_input.index("insert-1c wordend")
        if self.text_input.get(startindex +
                               '-1c') == '-' and self.text_input.get(
                                   startindex + '-2c') == '-':
            startindex = self.text_input.index("insert-1c wordstart -2c")
        elif self.text_input.get(startindex +
                                 '-1c') == '-' and self.text_input.get(
                                     startindex + '-2c') == ' ':
            startindex = self.text_input.index("insert-1c wordstart -1c")
        self.wordIndex[0] = startindex
        self.wordIndex[1] = endindex
        word = self.text_input.get(self.wordIndex[0], self.wordIndex[1])
        return word

    def GetLogicalLine(self, physicallineid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallineid]]

    def GetLogicalLineRange(self, physicallinefirstid, physicallinelastid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallinefirstid]:indexes[physicallinelastid] +
                     1]

    def GetAllLogicalLines(self):
        return self.GetLogicalLines()[1]

    def GetLogicalLines(self):
        from tkinter import END
        # Python 2 hack to remove the u'...' prefix from unicode literal strings. does not change py3 behavior
        physicallines = [
            str(line) for line in self.text_input.get("1.0", END).split('\n')
        ]
        lines = []
        indexes = [0] * len(physicallines)
        lineid = 0
        previousline = ""
        join = 0
        for line in physicallines:
            if line.startswith('#'):
                if join:
                    indexes[lineid] = indexes[lineid - 1]
            elif join:
                if line.endswith('\\'):
                    lines[-1] = lines[-1] + " " + line[:-1]
                    join = 1
                else:
                    lines[-1] = lines[-1] + " " + line
                    join = 0
                indexes[lineid] = indexes[lineid - 1]
            else:
                if line.endswith('\\'):
                    join = 1
                    lines.append(line[:-1])
                else:
                    lines.append(line)
                    join = 0
                if lineid > 0:
                    indexes[lineid] = indexes[lineid - 1] + 1
            lineid += 1
        return indexes, lines

    def GetLineUnderCursor(self):
        from tkinter import INSERT
        currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1
        return self.GetLogicalLine(currentlineid)

    def RunAllCommand(self):
        lines = self.GetAllLogicalLines()
        for line in lines:
            if line and line.strip():
                self.RunPype(line)

    def RunLineCommand(self):
        line = self.GetLineUnderCursor()
        if line and line.strip():
            self.RunPype(line)

    def RunSelectionCommand(self):
        from tkinter import TclError, SEL_FIRST, SEL_LAST
        try:
            firstlineid = int(
                self.text_input.index(SEL_FIRST).split('.')[0]) - 1
            lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1
            lines = self.GetLogicalLineRange(firstlineid, lastlineid)
            for line in lines:
                self.RunPype(line)
        except TclError:
            pass

    def GetSuggestionsList(self, word):
        list = []
        try:
            from vmtk import vmtkscripts
            from vmtk import pypes
        except ImportError:
            return None
        if word.startswith('--'):
            list = ['--pipe', '--help']
        elif word.startswith('-'):
            optionlist = []
            scriptindex = self.text_input.search('vmtk',
                                                 self.wordIndex[0],
                                                 backwards=1)
            moduleName = self.text_input.get(scriptindex,
                                             scriptindex + ' wordend')
            try:
                module = importlib.import_module('vmtk.' + moduleName)
                # Find the principle class to instantiate the requested action defined inside the requested writerModule script.
                # Returns a single member list (containing the principle class name) which satisfies the following criteria:
                #   1) is a class defined within the script
                #   2) the class is a subclass of pypes.pypescript
                scriptObjectClasses = [
                    x for x in dir(module) if isclass(getattr(module, x))
                    and issubclass(getattr(module, x), pypes.pypeScript)
                ]
                scriptObjectClassName = scriptObjectClasses[0]
                scriptObject = getattr(module, scriptObjectClassName)
                scriptObject = scriptObject()
                members = scriptObject.InputMembers + scriptObject.OutputMembers
                for member in members:
                    optionlist.append('-' + member.OptionName)
                list = [option for option in optionlist if option.count(word)]
            except:
                return list
        else:
            list = [
                scriptname for scriptname in vmtkscripts.__all__
                if scriptname.count(word)
            ]
            for index, item in enumerate(list):
                # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
                if 'vmtk.' == item[0:5]:
                    splitList = item.split('.')
                    list[index] = splitList[1]
                else:
                    continue
        return list

    def FillSuggestionsList(self, word):
        from tkinter import END
        self.suggestionslist.delete(0, END)
        suggestions = self.GetSuggestionsList(word)
        for suggestion in suggestions:
            self.suggestionslist.insert(END, suggestion)

    def ReplaceTextCommand(self, word):
        self.text_input.delete(self.wordIndex[0], self.wordIndex[1])
        self.text_input.insert(self.wordIndex[0], word)
        self.text_input.focus_set()

    def ShowHelpCommand(self):
        word = self.GetWordUnderCursor()
        self.OutputText(word)
        if word:
            self.RunPype(word + ' --help')
        else:
            self.OutputText('Enter your vmtk Pype above and Run.\n')

    def AutoCompleteCommand(self):
        word = self.GetWordIndex()
        self.suggestionswindow.withdraw()
        if word:
            self.FillSuggestionsList(word)
            self.suggestionswindow.geometry(
                "%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),
                                 self.text_output.winfo_rooty()))
            self.suggestionswindow.deiconify()
            self.suggestionswindow.lift()

    def InsertScriptName(self, scriptname):
        from tkinter import INSERT
        self.text_input.insert(INSERT, scriptname + ' ')

    def InsertFileName(self):
        from tkinter import INSERT
        import tkinter.filedialog
        openfilename = tkinter.filedialog.askopenfilename()
        if not openfilename:
            return
        if len(openfilename.split()) > 1:
            openfilename = '"%s"' % openfilename
        self.text_input.insert(INSERT, openfilename + ' ')

    def KeyPressHandler(self, event):
        if event.keysym == "Tab":
            self.AutoCompleteCommand()
            self.suggestionslist.focus_set()
            self.suggestionslist.selection_set(0)
            return "break"
        else:
            self.text_input.focus_set()

    def TopKeyPressHandler(self, event):
        from tkinter import ACTIVE, INSERT
        if event.keysym in ['Down', 'Up']:
            self.suggestionslist.focus_set()
        elif event.keysym == "Return":
            word = self.suggestionslist.get(ACTIVE)
            self.ReplaceTextCommand(word)
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
        elif len(event.keysym) == 1:
            self.suggestionswindow.withdraw()
            self.text_input.insert(INSERT, event.keysym)
            self.text_input.focus_set()
        else:
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()

    def NewHandler(self, event):
        self.NewCommand()

    def OpenHandler(self, event):
        self.OpenCommand()

    def SaveHandler(self, event):
        self.SaveCommand()

    def InsertFileNameHandler(self, event):
        self.InsertFileName()
        return "break"

    def QuitHandler(self, event):
        self.QuitCommand()

    def ShowHelpHandler(self, event):
        self.ShowHelpCommand()

    def RunKeyboardHandler(self, event):
        from tkinter import SEL_FIRST, TclError
        try:
            self.text_input.index(SEL_FIRST)
            self.RunSelectionCommand()
        except TclError:
            self.RunLineCommand()
        return "break"

    def RunAllHandler(self, event):
        self.RunAllCommand()

    def PopupHandler(self, event):
        try:
            self.popupmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popupmenu.grab_release()

    def OutputText(self, text):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.insert(END, text)
        self.text_output["state"] = DISABLED

    def BuildScriptMenu(self, parentmenu, modulename):
        from tkinter import Menu
        menu = Menu(parentmenu, bd=1, activeborderwidth=0)
        try:
            module = importlib.import_module('vmtk.' + modulename)
        except ImportError:
            return None
        scriptnames = [scriptname for scriptname in getattr(module, '__all__')]
        for index, scriptname in enumerate(scriptnames):
            # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
            if 'vmtk.' == scriptname[0:5]:
                splitList = scriptname.split('.')
                scriptnames[index] = splitList[1]
            else:
                continue
        menulength = 20
        for i in range(len(scriptnames) // menulength + 1):
            subscriptnames = scriptnames[i * menulength:(i + 1) * menulength]
            if not subscriptnames:
                break
            submenu = Menu(menu, bd=1, activeborderwidth=0)
            menu.add_cascade(label=subscriptnames[0] + "...", menu=submenu)
            for scriptname in subscriptnames:
                callback = CallbackShim(self.InsertScriptName, scriptname)
                submenu.add_command(label=scriptname, command=callback)
        return menu

    def BuildMainFrame(self):
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master, activeborderwidth=0, bd=0)
        self.master.config(menu=menu)

        filemenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="File", underline=0, menu=filemenu)
        filemenu.add_command(label="New",
                             accelerator='Ctrl+N',
                             command=self.NewCommand)
        filemenu.add_command(label="Open...",
                             accelerator='Ctrl+O',
                             command=self.OpenCommand)
        filemenu.add_command(label="Save as...",
                             accelerator='Ctrl+S',
                             command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",
                             accelerator='Ctrl+Q',
                             command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)

        self.output_to_file = StringVar()
        self.output_to_file.set('n')

        scriptmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu, modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename, menu=scriptsubmenu)

        editmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Edit", underline=0, menu=editmenu)
        editmenu.add_cascade(label="Insert script", menu=scriptmenu)
        editmenu.add_command(label="Insert file name",
                             accelerator='Ctrl+F',
                             command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input",
                             command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output",
                             command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file",
                                 variable=self.output_to_file,
                                 value='n')
        editmenu.add_radiobutton(label="Write output to file",
                                 variable=self.output_to_file,
                                 value='w')
        editmenu.add_radiobutton(label="Append output to file",
                                 variable=self.output_to_file,
                                 value='a')
        editmenu.add_command(label="Output file...",
                             command=self.OutputFileCommand)

        runmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line",
                            command=self.RunLineCommand)
        runmenu.add_command(label="Run selection",
                            command=self.RunSelectionCommand)

        helpmenu = Menu(menu, tearoff=0, bd=1, activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help",
                             underline=0,
                             accelerator='F1',
                             command=self.ShowHelpCommand)
        helpmenu.add_command(label="About",
                             underline=0,
                             command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)

        self.wordIndex = ['1.0', '1.0']

        self.suggestionswindow = Toplevel(bg='#ffffff',
                                          bd=0,
                                          height=50,
                                          width=600,
                                          highlightthickness=0,
                                          takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,
                                       bg='#ffffff',
                                       bd=1,
                                       fg='#336699',
                                       activestyle='none',
                                       highlightthickness=0,
                                       height=9)
        self.suggestionslist.insert(END, "foo")
        self.suggestionslist.pack(side=TOP, fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)
        content = Frame(self.master, bd=0, padx=2, pady=2)
        content.grid(row=0, column=0, sticky=N + S + W + E)
        content.rowconfigure(0, weight=1, minsize=50)
        content.rowconfigure(1, weight=0)
        content.columnconfigure(0, weight=1)

        panes = PanedWindow(content,
                            orient=VERTICAL,
                            bd=1,
                            sashwidth=8,
                            sashpad=0,
                            sashrelief=RAISED,
                            showhandle=True)
        panes.grid(row=0, column=0, sticky=N + S + W + E)

        frame1 = Frame(panes, bd=0)
        frame1.grid(row=0, column=0, sticky=N + S + W + E)
        frame1.columnconfigure(0, weight=1)
        frame1.columnconfigure(1, weight=0)
        frame1.rowconfigure(0, weight=1)

        panes.add(frame1, height=300, minsize=20)

        frame2 = Frame(panes, bd=0)
        frame2.grid(row=1, column=0, sticky=N + S + W + E)
        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(1, weight=0)
        frame2.rowconfigure(0, weight=1)

        panes.add(frame2, minsize=20)

        self.text_input = Text(frame1,
                               bg='#ffffff',
                               bd=1,
                               highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)

        self.input_scrollbar = Scrollbar(frame1,
                                         orient=VERTICAL,
                                         command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set

        self.text_output = Text(frame2,
                                state=DISABLED,
                                bd=1,
                                bg='#ffffff',
                                highlightthickness=0)

        self.output_scrollbar = Scrollbar(frame2,
                                          orient=VERTICAL,
                                          command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set

        self.text_entry = Entry(content,
                                bd=1,
                                bg='#ffffff',
                                state=DISABLED,
                                highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0, column=0, sticky=N + S + W + E)
        self.input_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_output.grid(row=0, column=0, sticky=N + S + W + E)
        self.output_scrollbar.grid(row=0, column=1, sticky=N + S + W + E)
        self.text_entry.grid(row=1, column=0, sticky=N + S + W + E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help",
                                   command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script", menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...",
                                   command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line",
                                   command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection",
                                   command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,
                                             self.output_stream)
Ejemplo n.º 39
0
class mainWindow(ttk.Frame):
    def __init__(self, root, crawler=None):
        ttk.Frame.__init__(self)

        self.root = root
        self.crawler = crawler
        self.tab_parent = ttk.Notebook()
        self.tab_crawl = CrawlTab(self,
                                  crawler,
                                  freeze_tabs=self.freeze_tabs,
                                  unfreeze_tabs=self.unfreeze_tabs)
        self.tab_settings = SettingsTab(crawler)
        self.tab_exclusions = ExclusionsTab(crawler)
        self.tab_extractions = ExtractionsTab(crawler)

        self.tab_parent.add(self.tab_crawl, text="Crawl")
        self.tab_parent.add(self.tab_settings, text="Settings")
        self.tab_parent.add(self.tab_exclusions, text="Exclusions")
        self.tab_parent.add(self.tab_extractions, text="Extractions")
        self.tab_parent.pack(expand=1, fill="both")
        self.master.title(Defaults.window_title)

        self.menubar = Menu(self)

        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="New", command=self.new_crawl)
        self.filemenu.add_command(label="Load Crawl", command=self.load_crawl)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Export View",
                                  command=self.export_view)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        self.modemenu = Menu(self.menubar, tearoff=0)
        self.modemenu.add_command(label="Spider", command=self.spider_mode)
        self.modemenu.add_command(label="List", command=self.list_mode)
        self.menubar.add_cascade(label="Mode", menu=self.modemenu)

        self.viewmenu = Menu(self.menubar, tearoff=0)
        self.viewmenu.add_command(label='All Crawl Data',
                                  command=self.show_crawl_output)

        self.inlinks_menu = Menu(self.viewmenu, tearoff=0)
        self.status_codes_menu = Menu(self.viewmenu, tearoff=0)
        self.content_types_menu = Menu(self.viewmenu, tearoff=0)
        self.crawl_status_menu = Menu(self.viewmenu, tearoff=0)

        self.viewmenu.add_cascade(label='Internal Links',
                                  menu=self.inlinks_menu)
        self.viewmenu.add_cascade(label='Status Codes',
                                  menu=self.status_codes_menu)
        self.viewmenu.add_cascade(label='Content Types',
                                  menu=self.content_types_menu)
        self.viewmenu.add_cascade(label='Crawl Status',
                                  menu=self.crawl_status_menu)
        self.menubar.add_cascade(label='View', menu=self.viewmenu)

        self.aboutmenu = Menu(self.menubar, tearoff=0)
        self.aboutmenu.add_command(label="About", command=self.show_about)
        self.menubar.add_cascade(label="Help", menu=self.aboutmenu)

        inlinks_labels = [
            'Redirects (3xx)', 'Client Error (4xx)', 'Server Error (5xx)'
        ]
        generate_menu(self.inlinks_menu, inlinks_labels,
                      self.view_broken_inlinks)

        status_codes_labels = [
            'OK (200)', 'Redirects (3xx)', 'Client Error (4xx)',
            'Server Error (5xx)'
        ]
        generate_menu(self.status_codes_menu, status_codes_labels,
                      self.view_status_codes)

        content_types_labels = [
            'HTML', 'Image', 'CSS', 'Font', 'JSON', 'XML', 'JavaScript'
        ]
        generate_menu(self.content_types_menu, content_types_labels,
                      self.view_content_types)

        crawl_status_labels = [
            'OK', 'Not OK', 'Canonicalised', 'Blocked By Robots', 'Noindex'
        ]
        generate_menu(self.crawl_status_menu, crawl_status_labels,
                      self.view_crawl_status)

        self.about_window = None
        self.root.config(menu=self.menubar)

        if self.crawler.settings.get('CHECK_FOR_UPDATES', True):
            Thread(target=self.request_current_version).start()

    def show_crawl_output(self):
        self.tab_crawl.load_crawl_to_outputtable(None, 'crawl')
        self.tab_crawl.viewed_table = 'crawl'
        self.tab_crawl.filters = []

    def load_crawl(self, db_file=None):
        files = [('Greenflare DB', f'*{Defaults.file_extension}'),
                 ('All files', '.*')]

        if not db_file:
            db_file = fd.askopenfilename(filetypes=files)
        # Don't do anything if user does not select a file
        if not db_file:
            return

        try:
            self.crawler.load_crawl(db_file)

            if self.crawler.settings["MODE"] == "Spider":
                self.master.title(
                    f"{self.crawler.settings['ROOT_DOMAIN']} - {Defaults.window_title}"
                )
            elif self.crawler.settings["MODE"] == "List":
                self.tab_crawl.show_list_mode()

            self.update_gui()
            self.tab_crawl.freeze_input()
            self.tab_crawl.button_clear['state'] = 'enabled'
            self.show_crawl_output()
            self.tab_crawl.update_bottom_stats()
        except Exception as e:
            messagebox.showerror(
                title='Error - Invalid database',
                message=f'Could not load {db_file} as it is invalid!')
            print(e)

    def new_crawl(self):
        self.crawler.reset_crawl()
        self.crawler.settings = Defaults.settings.copy()
        self.tab_crawl.reset()

    def export_view(self):
        files = [('CSV files', '*.csv')]
        export_file = fd.asksaveasfilename(filetypes=files)

        if not export_file:
            return

        if not export_file.endswith(".csv"):
            export_file += ".csv"
        if path.isfile(export_file):
            remove(export_file)

        data = [
            self.tab_crawl.treeview_table.item(child)['values']
            for child in self.tab_crawl.treeview_table.get_children()
        ]

        export_to_csv(export_file, self.tab_crawl.treeview_table['columns'],
                      data)

    def spider_mode(self):
        self.crawler.settings['MODE'] = 'Spider'
        self.tab_crawl.reset()

    def list_mode(self):
        lm_wnd = ListModeWindow(crawler=self.crawler,
                                crawl_tab=self.tab_crawl,
                                root=self.root)

    def show_about(self):
        if not self.about_window:
            self.about_window = AboutWindow()
        elif self.about_window.winfo_exists() == 0:
            self.about_window = AboutWindow()
        else:
            pass

    def view_broken_inlinks(self, label):
        if '3xx' in label:
            table = 'broken_inlinks_3xx'
        elif '4xx' in label:
            table = 'broken_inlinks_4xx'
        elif '5xx' in label:
            table = 'broken_inlinks_5xx'

        try:
            self.tab_crawl.viewed_table = table
            self.tab_crawl.filters = []
            self.tab_crawl.load_crawl_to_outputtable(None, table)
        except Exception as e:
            print('ERROR: view_broken_inlinks failed!')
            print(e)

    def view_status_codes(self, label):
        if '200' in label:
            table = 'status_codes_200'
        elif '3xx' in label:
            table = 'status_codes_3xx'
        elif '4xx' in label:
            table = 'status_codes_4xx'
        elif '5xx' in label:
            table = 'status_codes_5xx'

        try:
            self.tab_crawl.viewed_table = table
            self.tab_crawl.filters = []
            self.tab_crawl.load_crawl_to_outputtable(None, table)
            self.tab_crawl.reset_filter_window()
        except Exception as e:
            print('ERROR: view_status_codes failed!')
            print(e)

    def view_content_types(self, label):
        content_type = label.lower()
        table = 'content_type_' + content_type

        try:
            self.tab_crawl.viewed_table = table
            self.tab_crawl.filters = []
            self.tab_crawl.load_crawl_to_outputtable(None, table)
        except Exception as e:
            print('ERROR: view_content_types failed!')
            print(e)

    def view_crawl_status(self, label):
        table_mapping = {
            'OK': 'crawl_status_ok',
            'Not OK': 'crawl_status_not_ok',
            'Canonicalised': 'crawl_status_canonicalised',
            'Blocked By Robots': 'crawl_status_blocked_by_robots',
            'Noindex': 'crawl_status_noindex'
        }

        table = table_mapping[label]

        try:
            self.tab_crawl.viewed_table = table
            self.tab_crawl.filters = []
            self.tab_crawl.load_crawl_to_outputtable(None, table)
        except Exception as e:
            print('ERROR: view_crawl_status failed!')
            print(e)

    def request_current_version(self):
        self.crawler.init_crawl_headers()
        self.crawler.init_session()

        response = self.crawler.crawl_url(Defaults.latest_release_url)

        if isinstance(response, str):
            return

        if response.ok:

            latest_ver = response.text
            if version.parse(latest_ver) > version.parse(Defaults.version):
                UpdateWindow('New Version Available!', latest_ver)

    def update_gui(self):
        self.tab_crawl.update()
        self.tab_settings.update()
        self.tab_exclusions.update()
        self.tab_extractions.update()

    def freeze_tabs(self):
        self.tab_parent.tab(self.tab_settings, state='disabled')
        self.tab_parent.tab(self.tab_exclusions, state='disabled')
        self.tab_parent.tab(self.tab_extractions, state='disabled')

    def unfreeze_tabs(self):
        self.tab_parent.tab(self.tab_settings, state='normal')
        self.tab_parent.tab(self.tab_exclusions, state='normal')
        self.tab_parent.tab(self.tab_extractions, state='normal')

    # @run_in_background_with_window([], title='Stopping crawl ...', msg='Waiting for crawl to finish ...')
    def on_closing(self):
        self.crawler.end_crawl_gracefully()
        self.master.destroy()

    def open_file_on_macos(self, *args):
        for f in args:
            if f.endswith(Defaults.file_extension):
                self.load_crawl(db_file=f)
            break
Ejemplo n.º 40
0
class DrumMachine:
    def __init__(self, root):
        self.root = root
        self.root.title(PROGRAM_NAME)
        self.all_patterns = [None] * MAX_NUMBER_OF_PATTERNS
        self.current_pattern_index = 0
        self.loop = True
        self.now_playing = False
        self.beats_per_minute = INITIAL_BEATS_PER_MINUTE
        self.drum_load_entry_widget = [None] * MAX_NUMBER_OF_DRUM_SAMPLES
        self.root.protocol('WM_DELETE_WINDOW', self.exit_app)
        self.init_all_patterns()
        self.init_gui()

    def get_current_pattern_dict(self):
        return self.all_patterns[self.current_pattern_index]

    def get_bpu(self):
        return self.get_current_pattern_dict()['bpu']

    def set_bpu(self):
        self.get_current_pattern_dict()['bpu'] = int(self.bpu_widget.get())

    def get_number_of_units(self):
        return self.get_current_pattern_dict()['number_of_units']

    def set_number_of_units(self):
        self.get_current_pattern_dict()['number_of_units'] = int(
            self.number_of_units_widget.get())

    def get_list_of_drum_files(self):
        return self.get_current_pattern_dict()['list_of_drum_files']

    def get_drum_file_path(self, drum_index):
        return self.get_list_of_drum_files()[drum_index]

    def set_drum_file_path(self, drum_index, file_path):
        self.get_list_of_drum_files()[drum_index] = file_path

    def get_is_button_clicked_list(self):
        return self.get_current_pattern_dict()['is_button_clicked_list']

    def set_is_button_clicked_list(self, num_of_rows, num_of_columns):
        self.get_current_pattern_dict()['is_button_clicked_list'] = [
            [False] * num_of_columns for x in range(num_of_rows)
        ]

    def set_beats_per_minute(self):
        self.get_current_pattern_dict(
        )['beats_per_minute'] = self.beats_per_minute_widget.get()

    def init_all_patterns(self):
        self.all_patterns = [{
            'list_of_drum_files': [None] * MAX_NUMBER_OF_DRUM_SAMPLES,
            'number_of_units':
            INITIAL_NUMBER_OF_UNITS,
            'bpu':
            INITIAL_BPU,
            'is_button_clicked_list':
            self.init_is_button_clicked_list(
                MAX_NUMBER_OF_DRUM_SAMPLES,
                INITIAL_NUMBER_OF_UNITS * INITIAL_BPU)
        } for k in range(MAX_NUMBER_OF_PATTERNS)]

    def init_is_button_clicked_list(self, num_of_rows, num_of_columns):
        return [[False] * num_of_columns for x in range(num_of_rows)]

    def load_project(self):
        file_path = filedialog.askopenfilename(filetypes=[
            ('Explosion Beat File', '*.ebt')
        ],
                                               title='Load Project')
        if not file_path:
            return
        pickled_file_object = open(file_path, "rb")
        try:
            self.all_patterns = pickle.load(pickled_file_object)
        except EOFError:
            messagebox.showerror(
                "Error", "Explosion Beat file seems corrupted or invalid !")
        pickled_file_object.close()
        try:
            self.change_pattern()
            self.root.title(os.path.basename(file_path) + PROGRAM_NAME)
        except:
            messagebox.showerror(
                "Error",
                "An unexpected error occurred trying to process the beat file")

    def save_project(self):
        saveas_file_name = filedialog.asksaveasfilename(
            filetypes=[('Explosion Beat File', '*.ebt')],
            title="Save project as...")
        if saveas_file_name is None:
            return
        pickle.dump(self.all_patterns, open(saveas_file_name, "wb"))
        self.root.title(os.path.basename(saveas_file_name) + PROGRAM_NAME)

    def show_about(self):
        messagebox.showinfo(
            PROGRAM_NAME, "Tkinter GUI Application\n Development Blueprints")

    def exit_app(self):
        self.now_playing = False
        if messagebox.askokcancel("Quit", "Really quit?"):
            self.root.destroy()

    def display_pattern_name(self):
        self.current_pattern_name_widget.config(state='normal')
        self.current_pattern_name_widget.delete(0, 'end')
        self.current_pattern_name_widget.insert(
            0, 'Pattern {}'.format(self.current_pattern_index))
        self.current_pattern_name_widget.config(state='readonly')

    def on_pattern_changed(self):
        self.change_pattern()

    def change_pattern(self):
        self.current_pattern_index = int(self.pattern_index_widget.get())
        self.display_pattern_name()
        self.create_left_drum_loader()
        self.display_all_drum_file_names()
        self.create_right_button_matrix()
        self.display_all_button_colors()

    def on_number_of_units_changed(self):
        self.set_number_of_units()
        self.set_is_button_clicked_list(MAX_NUMBER_OF_DRUM_SAMPLES,
                                        self.find_number_of_columns())
        self.create_right_button_matrix()

    def on_bpu_changed(self):
        self.set_bpu()
        self.set_is_button_clicked_list(MAX_NUMBER_OF_DRUM_SAMPLES,
                                        self.find_number_of_columns())
        self.create_right_button_matrix()

    def on_open_file_button_clicked(self, drum_index):
        def event_handler():
            file_path = filedialog.askopenfilename(defaultextension=".wav",
                                                   filetypes=[
                                                       ("Wave Files", "*.wav"),
                                                       ("OGG Files", "*.ogg")
                                                   ])
            if not file_path:
                return
            self.set_drum_file_path(drum_index, file_path)
            self.display_all_drum_file_names()

        return event_handler

    def display_all_drum_file_names(self):
        for i, drum_name in enumerate(self.get_list_of_drum_files()):
            self.display_drum_name(i, drum_name)

    def display_drum_name(self, text_widget_num, file_path):
        if file_path is None:
            return
        drum_name = os.path.basename(file_path)
        self.drum_load_entry_widget[text_widget_num].delete(0, END)
        self.drum_load_entry_widget[text_widget_num].insert(0, drum_name)

    def play_in_thread(self):
        self.thread = threading.Thread(target=self.play_pattern)
        self.thread.start()

    def on_play_button_clicked(self):
        self.start_play()
        self.toggle_play_button_state()

    def start_play(self):
        self.init_pygame()
        self.play_in_thread()

    def on_stop_button_clicked(self):
        self.stop_play()
        self.toggle_play_button_state()

    def stop_play(self):
        self.now_playing = False

    def init_pygame(self):
        pygame.mixer.pre_init(44100, -16, 1, 512)
        pygame.init()

    def play_sound(self, sound_filename):
        if sound_filename is not None:
            pygame.mixer.Sound(sound_filename).play()

    def get_column_from_matrix(self, matrix, i):
        return [row[i] for row in matrix]

    def toggle_play_button_state(self):
        if self.now_playing:
            self.play_button.config(state="disabled")
        else:
            self.play_button.config(state="normal")

    def play_pattern(self):
        self.now_playing = True
        self.toggle_play_button_state()
        while self.now_playing:
            play_list = self.get_is_button_clicked_list()
            num_columns = len(play_list[0])
            for column_index in range(num_columns):
                column_to_play = self.get_column_from_matrix(
                    play_list, column_index)
                for i, item in enumerate(column_to_play):
                    if item:
                        sound_filename = self.get_drum_file_path(i)
                        self.play_sound(sound_filename)
                time.sleep(self.time_to_play_each_column())
                if not self.now_playing: break
            if not self.loop: break
        self.now_playing = False
        self.toggle_play_button_state()

    def time_to_play_each_column(self):
        beats_per_second = self.beats_per_minute / 60
        time_to_play_each_column = 1 / beats_per_second
        return time_to_play_each_column

    def on_loop_button_toggled(self):
        self.loop = self.loopbutton.instate(['selected'])

    def on_beats_per_minute_changed(self):
        self.beats_per_minute = int(self.beats_per_minute_widget.get())

    def get_button_value(self, row, col):
        return self.all_patterns[
            self.current_pattern_index]['is_button_clicked_list'][row][col]

    def find_number_of_columns(self):
        return int(self.number_of_units_widget.get()) * int(
            self.bpu_widget.get())

    def process_button_clicked(self, row, col):
        self.set_button_value(row, col, not self.get_button_value(row, col))
        self.display_button_color(row, col)

    def set_button_value(self, row, col, bool_value):
        self.all_patterns[self.current_pattern_index][
            'is_button_clicked_list'][row][col] = bool_value

    def on_button_clicked(self, row, col):
        def event_handler():
            self.process_button_clicked(row, col)

        return event_handler

    def display_all_button_colors(self):
        number_of_columns = self.find_number_of_columns()
        for r in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            for c in range(number_of_columns):
                self.display_button_color(r, c)

    def display_button_color(self, row, col):
        bpu = int(self.bpu_widget.get())
        original_color = COLOR_1 if ((col // bpu) % 2) else COLOR_2
        button_color = BUTTON_CLICKED_COLOR if self.get_button_value(
            row, col) else original_color
        self.buttons[row][col].config(background=button_color)

    def create_play_bar(self):
        playbar_frame = Frame(self.root, height=15)
        start_row = MAX_NUMBER_OF_DRUM_SAMPLES + 10
        playbar_frame.grid(row=start_row,
                           columnspan=13,
                           sticky=W + E,
                           padx=15,
                           pady=10)
        self.play_icon = PhotoImage(file="images/play.gif")
        self.play_button = ttk.Button(playbar_frame,
                                      text='Play',
                                      image=self.play_icon,
                                      compound='left',
                                      command=self.on_play_button_clicked)
        self.play_button.grid(row=start_row, column=1, padx=2)
        ttk.Button(playbar_frame,
                   text='Stop',
                   command=self.on_stop_button_clicked).grid(row=start_row,
                                                             column=3,
                                                             padx=2)
        ttk.Separator(playbar_frame, orient='vertical').grid(row=start_row,
                                                             column=5,
                                                             sticky="ns",
                                                             padx=5)
        self.loopbutton = ttk.Checkbutton(playbar_frame,
                                          text='Loop',
                                          command=self.on_loop_button_toggled)
        self.loopbutton.grid(row=start_row, column=16, padx=5)
        self.loopbutton.state(['selected'])
        ttk.Separator(playbar_frame, orient='vertical').grid(row=start_row,
                                                             column=20,
                                                             sticky="ns",
                                                             padx=5)
        Label(playbar_frame, text='Beats Per Minute').grid(row=start_row,
                                                           column=25)
        self.beats_per_minute_widget = Spinbox(
            playbar_frame,
            from_=MIN_BEATS_PER_MINUTE,
            to=MAX_BEATS_PER_MINUTE,
            width=5,
            increment=5.0,
            command=self.on_beats_per_minute_changed)
        self.beats_per_minute_widget.grid(row=start_row, column=30)
        self.beats_per_minute_widget.delete(0, "end")
        self.beats_per_minute_widget.insert(0, INITIAL_BEATS_PER_MINUTE)
        ttk.Separator(playbar_frame, orient='vertical').grid(row=start_row,
                                                             column=35,
                                                             sticky="ns",
                                                             padx=5)
        photo = PhotoImage(file='images/signature.gif')
        label = Label(playbar_frame, image=photo)
        label.image = photo
        label.grid(row=start_row, column=50, padx=1, sticky='w')

    def create_right_button_matrix(self):
        right_frame = Frame(self.root)
        right_frame.grid(row=10,
                         column=6,
                         sticky=W + E + N + S,
                         padx=15,
                         pady=4)
        self.buttons = [[None for x in range(self.find_number_of_columns())]
                        for x in range(MAX_NUMBER_OF_DRUM_SAMPLES)]
        for row in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            for col in range(self.find_number_of_columns()):
                self.buttons[row][col] = Button(right_frame,
                                                command=self.on_button_clicked(
                                                    row, col))
                self.buttons[row][col].grid(row=row, column=col)
                self.display_button_color(row, col)

    def create_left_drum_loader(self):
        left_frame = Frame(self.root)
        left_frame.grid(row=10, column=0, columnspan=6, sticky=W + E + N + S)
        open_file_icon = PhotoImage(file='images/openfile.gif')
        for i in range(MAX_NUMBER_OF_DRUM_SAMPLES):
            open_file_button = Button(
                left_frame,
                image=open_file_icon,
                command=self.on_open_file_button_clicked(i))
            open_file_button.image = open_file_icon
            open_file_button.grid(row=i, column=0, padx=5, pady=4)
            self.drum_load_entry_widget[i] = Entry(left_frame)
            self.drum_load_entry_widget[i].grid(row=i,
                                                column=4,
                                                padx=7,
                                                pady=4)

    def create_top_bar(self):
        topbar_frame = Frame(self.root, height=25)
        topbar_frame.grid(row=0, columnspan=12, rowspan=10, padx=5, pady=5)

        Label(topbar_frame, text='Pattern Number:').grid(row=0, column=1)
        self.pattern_index_widget = Spinbox(topbar_frame,
                                            from_=0,
                                            to=MAX_NUMBER_OF_PATTERNS - 1,
                                            width=5,
                                            command=self.on_pattern_changed)
        self.pattern_index_widget.grid(row=0, column=2)
        self.current_pattern_name_widget = Entry(topbar_frame)
        self.current_pattern_name_widget.grid(row=0, column=3, padx=7, pady=2)

        Label(topbar_frame, text='Number of Units:').grid(row=0, column=4)
        self.number_of_units_widget = Spinbox(
            topbar_frame,
            from_=1,
            to=MAX_NUMBER_OF_UNITS,
            width=5,
            command=self.on_number_of_units_changed)
        self.number_of_units_widget.delete(0, "end")
        self.number_of_units_widget.insert(0, INITIAL_NUMBER_OF_UNITS)
        self.number_of_units_widget.grid(row=0, column=5)
        Label(topbar_frame, text='BPUs:').grid(row=0, column=6)
        self.bpu_widget = Spinbox(topbar_frame,
                                  from_=1,
                                  to=MAX_BPU,
                                  width=5,
                                  command=self.on_bpu_changed)
        self.bpu_widget.grid(row=0, column=7)
        self.bpu_widget.delete(0, "end")
        self.bpu_widget.insert(0, INITIAL_BPU)
        self.display_pattern_name()

    def create_top_menu(self):
        self.menu_bar = Menu(self.root)
        self.file_menu = Menu(self.menu_bar, tearoff=0)
        self.file_menu.add_command(label="Load Project",
                                   command=self.load_project)
        self.file_menu.add_command(label="Save Project",
                                   command=self.save_project)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit", command=self.exit_app)
        self.menu_bar.add_cascade(label="File", menu=self.file_menu)
        self.about_menu = Menu(self.menu_bar, tearoff=0)
        self.about_menu.add_command(label="About", command=self.show_about)
        self.menu_bar.add_cascade(label="About", menu=self.about_menu)
        self.root.config(menu=self.menu_bar)

    def init_gui(self):
        self.create_top_menu()
        self.create_top_bar()
        self.create_left_drum_loader()
        self.create_right_button_matrix()
        self.create_play_bar()
Ejemplo n.º 41
0
    def init(self):
        self.root = tk.Tk()
        self.root.title(self.title)
        #Menu
        menu_bar = Menu(self.root)
        self.root.config(menu=menu_bar)

        file_menu = Menu(menu_bar, tearoff=0)
        file_menu.add_command(label="New", command=lambda: self.menu_new())
        file_menu.add_command(label="Clear", command=lambda: self.menu_clear())
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=lambda: self.myExit())
        menu_bar.add_cascade(label="Files", menu=file_menu)

        opt_menu = Menu(menu_bar, tearoff=0)
        opt_menu.add_command(label="Debug On",
                             command=lambda: self.menu_option1())
        opt_menu.add_separator()
        opt_menu.add_command(label="Debug Off",
                             command=lambda: self.menu_option2())
        menu_bar.add_cascade(label="Options", menu=opt_menu)

        shell_menu = Menu(menu_bar, tearoff=0)
        shell_menu.add_command(label="Shell",
                               command=lambda: self.menu_shell())
        menu_bar.add_cascade(label="Shell", menu=shell_menu)

        help_menu = Menu(menu_bar, tearoff=0)
        help_menu.add_command(label="Help", command=lambda: self.menu_help())
        menu_bar.add_cascade(label="Help", menu=help_menu)

        #window
        self.root.minsize(100, 100)
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        # Frame
        frame1 = tk.Frame(self.root)
        frame1.rowconfigure(0, weight=1)
        frame1.columnconfigure(0, weight=1)
        frame1.grid(sticky=(tk.N, tk.W, tk.S, tk.E))

        ##Button
        #button1 = tk.Button(frame1, text='OK', command=self.button_click)
        #button1.grid(row=0, column=0, columnspan=2, sticky=(tk.N,tk.E))

        # Text
        f = Font(family='Helvetica', size=11)
        self.txt = tk.Text(frame1)
        self.txt.configure(font=f)
        self.txt.insert(1.0, "[START]\n")
        #self.txt.grid(row=1, column=0, sticky=(tk.N,tk.W,tk.S,tk.E))
        self.txt.grid(row=0, column=0, sticky=(tk.N, tk.W, tk.S, tk.E))

        # Scrollbar
        scrollbar = tk.Scrollbar(frame1,
                                 orient=tk.VERTICAL,
                                 command=self.txt.yview)
        self.txt['yscrollcommand'] = scrollbar.set
        #scrollbar.grid(row=1,column=1,sticky=(tk.N,tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
Ejemplo n.º 42
0
    def createWidgets(self):
        # Tab Control introduced here --------------------------------------
        tabControl = ttk.Notebook(self.win)     # Create Tab Control

        tab1 = ttk.Frame(tabControl)            # Create a tab
#         tabControl.add(tab1, text='MySQL')    # Add the tab -- COMMENTED OUT FOR CH08

        tab2 = ttk.Frame(tabControl)            # Add a second tab
        tabControl.add(tab2, text='Widgets')    # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible
        # ~ Tab Control introduced here -----------------------------------------

        # We are creating a container frame to hold all other widgets
        self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ')
        self.mySQL.grid(column=0, row=0, padx=8, pady=4)

        # Creating a Label
        ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W')

        # Adding a Textbox Entry widget
        book = tk.StringVar()
        self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book)
        self.bookTitle.grid(column=0, row=1, sticky='W')

        # Adding a Textbox Entry widget
        book1 = tk.StringVar()
        self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1)
        self.bookTitle1.grid(column=0, row=2, sticky='W')

        # Adding a Textbox Entry widget
        book2 = tk.StringVar()
        self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2)
        self.bookTitle2.grid(column=0, row=3, sticky='W')

        # Creating a Label
        ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber.grid(column=1, row=1, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber1.grid(column=1, row=2, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber2.grid(column=1, row=3, sticky='W')

        # Adding a Button
        self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.callBacks.insertQuote)
        self.action.grid(column=2, row=1)

        # Adding a Button
        self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.callBacks.getQuote)
        self.action1.grid(column=2, row=2)

        # Adding a Button
        self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.callBacks.modifyQuote)
        self.action2.grid(column=2, row=3)

        # Add some space around each widget
        for child in self.mySQL.winfo_children():
            child.grid_configure(padx=2, pady=4)


        quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ')
        quoteFrame.grid(column=0, row=1, padx=8, pady=4)

        # Using a scrolled Text control
        quoteW  = 40; quoteH = 6
        self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD)
        self.quote.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Add some space around each widget
        for child in quoteFrame.winfo_children():
            child.grid_configure(padx=2, pady=4)

        #======================================================================================================
        # Tab Control 2
        #======================================================================================================
        # We are creating a container frame to hold all other widgets -- Tab2
        self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL)
        self.widgetFrame.grid(column=0, row=0, padx=8, pady=4)

        # Creating three checkbuttons
        self.chVarDis = tk.IntVar()
        self.check1 = tk.Checkbutton(self.widgetFrame, text=self.i18n.disabled, variable=self.chVarDis, state='disabled')
        self.check1.select()
        self.check1.grid(column=0, row=0, sticky=tk.W)

        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.widgetFrame, text=self.i18n.unChecked, variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W )

        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.widgetFrame, text=self.i18n.toggle, variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)

        # trace the state of the two checkbuttons
        self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())
        self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())

        # Radiobutton list
        colors = self.i18n.colors

        self.radVar = tk.IntVar()

        # Selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            self.curRad = 'rad' + str(col)
            self.curRad = tk.Radiobutton(self.widgetFrame, text=colors[col], variable=self.radVar, value=col, command=self.callBacks.radCall)
            self.curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            tt.createToolTip(self.curRad, 'This is a Radiobutton control.')

        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.widgetFrame, text=self.i18n.labelsFrame)
        labelsFrame.grid(column=0, row=7, pady=6)

        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0, row=0)
        self.lbl2 = tk.StringVar()
        self.lbl2.set(self.i18n.label2)
        ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1)

        # Add some space around each label
        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=6, pady=1)

        number = tk.StringVar()
        self.combo = ttk.Combobox(self.widgetFrame, width=12, textvariable=number)
        self.combo['values'] = (1, 2, 4, 42, 100)
        self.combo.grid(column=1, row=7, sticky=tk.W)
        self.combo.current(0)
        self.combo.bind('<<ComboboxSelected>>', self.callBacks._combo)

        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.widgetFrame, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self.callBacks._spin)
        self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1)

        # Using a scrolled Text control
        scrolW  = 40; scrolH = 1
        self.scr = scrolledtext.ScrolledText(self.widgetFrame, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Adding a TZ Button
        self.allTZs = ttk.Button(self.widgetFrame, text=self.i18n.timeZones, command=self.callBacks.allTimeZones)
        self.allTZs.grid(column=0, row=9, sticky='WE')

        # Adding local TZ Button
        self.localTZ = ttk.Button(self.widgetFrame, text=self.i18n.localZone, command=self.callBacks.localZone)
        self.localTZ.grid(column=1, row=9, sticky='WE')

        # Adding getTime TZ Button
        self.dt = ttk.Button(self.widgetFrame, text=self.i18n.getTime, command=self.callBacks.getDateTime)
        self.dt.grid(column=2, row=9, sticky='WE')


        # Create Manage Files Frame ------------------------------------------------
        mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles)
        mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5)

        # Button Callback
        def getFileName():
            print('hello from getFileName')
            fDir  = path.dirname(__file__)
            fName = fd.askopenfilename(parent=self.win, initialdir=fDir)
            print(fName)
            self.fileEntry.config(state='enabled')
            self.fileEntry.delete(0, tk.END)
            self.fileEntry.insert(0, fName)

            if len(fName) > self.entryLen:
                self.fileEntry.config(width=len(fName) + 3)

        # Add Widgets to Manage Files Frame
        lb = ttk.Button(mngFilesFrame, text=self.i18n.browseTo, command=getFileName)
        lb.grid(column=0, row=0, sticky=tk.W)

        #-----------------------------------------------------
        file = tk.StringVar()
        self.entryLen = scrolW - 4
        self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file)
        self.fileEntry.grid(column=1, row=0, sticky=tk.W)

        #-----------------------------------------------------
        logDir = tk.StringVar()
        self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir)
        self.netwEntry.grid(column=1, row=1, sticky=tk.W)


        def copyFile():
            import shutil
            src = self.fileEntry.get()
            file = src.split('/')[-1]
            dst = self.netwEntry.get() + '\\'+ file
            try:
                shutil.copy(src, dst)
                mBox.showinfo('Copy File to Network', 'Succes: File copied.')
            except FileNotFoundError as err:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err))
            except Exception as ex:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex))

        cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile)
        cb.grid(column=0, row=1, sticky=tk.E)

        # Add some space around each label
        for child in mngFilesFrame.winfo_children():
            child.grid_configure(padx=6, pady=6)

        # Creating a Menu Bar ==========================================================
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label=self.i18n.new)
        fileMenu.add_separator()
        fileMenu.add_command(label=self.i18n.exit, command=self.callBacks._quit)
        menuBar.add_cascade(label=self.i18n.file, menu=fileMenu)

        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label=self.i18n.about)
        menuBar.add_cascade(label=self.i18n.help, menu=helpMenu)

        # Change the main windows icon
        self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico')

        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')

        # It is not necessary to create a tk.StringVar()
        strData = tk.StringVar()
        strData = self.spin.get()

        # Place cursor into name Entry
        self.bookTitle.focus()

        # Add a Tooltip to the Spinbox
        tt.createToolTip(self.spin, 'This is a Spin control.')

        # Add Tooltips to more widgets
        tt.createToolTip(self.bookTitle, 'This is an Entry control.')
        tt.createToolTip(self.action, 'This is a Button control.')
        tt.createToolTip(self.scr,    'This is a ScrolledText control.')
Ejemplo n.º 43
0
class Application(object):

    def __init__(self):

        self.master = Tk()
        self.master.geometry(newGeometry = '300x300')
        # Fenêtre tkinter

        self.menu = Menu(self.master)

        self.filemenu = Menu(self.menu,
                             tearoff = 0)
        self.filemenu.add_command(label = "Open", command = self.open)
        self.filemenu.add_separator()
        self.filemenu.add_command(label = "Exit", command = self.master.destroy)
        self.menu.add_cascade(label = "File",
                              menu = self.filemenu)

        self.master.config(menu = self.menu)
        # On crée un menu

        self.canvas = Canvas(master=self.master,
                             width=200,
                             height=200,
                             bg='#cccccc')

        self.canvas.place(x=150,
                          y=100,
                          anchor='center')

        Label(master=self.master,
              text='Image',
              font='YuMinchoDemibold',
              foreground='white',
              background='#535353').place(x=120,
                                          y=190)

    def open(self):

        self.image_path = askopenfilename(initialdir = os.path.dirname(os.path.join(os.getcwd(), __file__)),
                                          filetypes = (("png files",".png"),
                                                       ("jpg files",".jpg"),
                                                       ("all files (risk)", ".")),
                                          defaultextension = ".png",
                                          title = "Open picture file")
        # on demande le fichier à ouvrir

        if self.image_path == "":
            # Si l'utilisateur choisit annuler
            return None
        else:
            pass

        self.pyimage = PhotoImage(file = self.image_path)
        print(self.image_path)
        self.PILimage = pil.open(self.image_path)

        if self.PILimage.size[0] > 200 or\
           self.PILimage.size[1] > 200:

            if self.PILimage.size[0] >= self.PILimage.size[1]:
                x = 200
                pourcentage = int(((200*100)/self.PILimage.size[0]))
                y = self.PILimage.size[1] - (self.PILimage.size[1]* (100 - pourcentage) /100)
            else:
                y = 200
                pourcentage = int(((200 * 100) / self.PILimage.size[1]))
                x = self.PILimage.size[0] - (self.PILimage.size[0] * (100 - pourcentage) / 100)

            Label(master = self.master,
                  text = 'Image resized \nfor view ({}%)'.format(pourcentage),
                  font = 'YuMinchoDemibold 6',
                  fg = 'black').place(x=190,y=200)
            print('cc3')
            self.PILimage.resize((int(x),int(y)), pil.BILINEAR).save("tmp.png")
            self.pyimage = PhotoImage(file="tmp.png")
            os.remove('tmp.png')
            # On redimensionne l'image pour la preview

        self.image_tag = self.canvas.create_image(100,
                                                  100,
                                                  anchor = 'center',
                                                  image = self.pyimage)
        # On affiche l'image

        Label(master = self.master,
              text = 'Image original size:',
              font = 'YuMinchoDemibold 7',
              relief = 'groove').place(x = 20, y = 230)
        Label(master=self.master,
              text='({},{})'.format(self.PILimage.size[0],self.PILimage.size[1]),
              font='YuMinchoDemibold 8').place(x=37, y=250)

        Label(master=self.master,
              text='Choisir taille thumbnail:',
              font='YuMinchoDemibold 7',
              relief='groove').place(x=140, y=230)

        liste_valeurs = (30,50,100)

        self.taille_var = IntVar()
        self.menu_taille = OptionMenu(self.master,
                                      self.taille_var,
                                      *liste_valeurs)
        self.menu_taille.place(x=140, y=250)

        Button(master = self.master,
               text = 'Créer Thumbnail',
               font = 'YuMinchoDemibold 8',
               command = self.create_thumbnail).place(x=300,y=300,anchor='se')

    def create_thumbnail(self):

        if self.PILimage.size[0] >= self.PILimage.size[1]:
            x = self.taille_var.get()
            pourcentage = int(((x*100)/self.PILimage.size[0]))
            y = int(self.PILimage.size[1] - (self.PILimage.size[1] * (100-pourcentage)/100))
        else:
            y = self.taille_var.get()
            pourcentage = int(((y * 100) / self.PILimage.size[1]))
            x = int(self.PILimage.size[0] - (self.PILimage.size[0] * (100-pourcentage)/100))
        # On récupère les valeurs

        name = self.image_path.split('/')[-1].split(".")
        name = name[0] + 'THUMBNAIL.' + name[1]
        self.PILimage.resize((x,y),pil.BILINEAR).save(name)
Ejemplo n.º 44
0
ttk.Label(labelsFrame,text='Label2').grid(column=0,row=1)
ttk.Label(labelsFrame,text='Label3').grid(column=0,row=2)

for child in labelsFrame.winfo_children():
    child.grid_configure(padx=8,pady=4)

# menu commands
def _quit():
    win.quit()
    win.destroy()
    exit()

#create menubar
menuBar=Menu(win)
win.config(menu=menuBar)

# add menu items
fileMenu = Menu(menuBar, tearoff=0)
fileMenu.add_command(label='New')
fileMenu.add_separator()
fileMenu.add_command(label='Exit', command=_quit)
menuBar.add_cascade(label='File',menu=fileMenu)

helpMenu = Menu(menuBar,tearoff=0)
helpMenu.add_command(label='About')
menuBar.add_cascade(label='Help',menu=helpMenu)

nameEntered.focus()

win.mainloop()
    def createWidgets(self):    
        # Tab Control introduced here --------------------------------------
        tabControl = ttk.Notebook(self.win)     # Create Tab Control
        
        tab1 = ttk.Frame(tabControl)            # Create a tab 
        tabControl.add(tab1, text='MySQL')      # Add the tab 
        
        tab2 = ttk.Frame(tabControl)            # Add a second tab
        tabControl.add(tab2, text='Widgets')      # Make second tab visible
        
        tabControl.pack(expand=1, fill="both")  # Pack to make visible
        # ~ Tab Control introduced here -----------------------------------------
        
        # We are creating a container frame to hold all other widgets
        self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ')
        self.mySQL.grid(column=0, row=0, padx=8, pady=4)        
        
        # Creating a Label
        ttk.Label(self.mySQL, text="Book Title:").grid(column=0, row=0, sticky='W')
   
        # Adding a Textbox Entry widget
        book = tk.StringVar()
        self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book)
        self.bookTitle.grid(column=0, row=1, sticky='W')     

        # Adding a Textbox Entry widget
        book1 = tk.StringVar()
        self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1)
        self.bookTitle1.grid(column=0, row=2, sticky='W')  
        
        # Adding a Textbox Entry widget
        book2 = tk.StringVar()
        self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2)
        self.bookTitle2.grid(column=0, row=3, sticky='W')  
        
        # Creating a Label
        ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W')
        
        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber.grid(column=1, row=1, sticky='W')     
 
        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber1.grid(column=1, row=2, sticky='W')    
        
        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber2.grid(column=1, row=3, sticky='W')           
       
        # Adding a Button
        self.action = ttk.Button(self.mySQL, text="Insert Quote", command=self.insertQuote)   
        self.action.grid(column=2, row=1)

        # Adding a Button
        self.action1 = ttk.Button(self.mySQL, text="Get Quotes", command=self.getQuote)   
        self.action1.grid(column=2, row=2)
        
        # Adding a Button
        self.action2 = ttk.Button(self.mySQL, text="Mody Quote", command=self.modifyQuote)   
        self.action2.grid(column=2, row=3)
                
        # Add some space around each widget
        for child in self.mySQL.winfo_children(): 
            child.grid_configure(padx=2, pady=4)
            

        quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ')
        quoteFrame.grid(column=0, row=1, padx=8, pady=4)    

        # Using a scrolled Text control    
        quoteW  = 40; quoteH = 6
        self.quote = scrolledtext.ScrolledText(quoteFrame, width=quoteW, height=quoteH, wrap=tk.WORD)
        self.quote.grid(column=0, row=8, sticky='WE', columnspan=3)   

        # Add some space around each widget
        for child in quoteFrame.winfo_children(): 
            child.grid_configure(padx=2, pady=4)
                            
        #======================================================================================================               
        # Tab Control 2 
        #======================================================================================================
        # We are creating a container frame to hold all other widgets -- Tab2
        self.mySQL2 = ttk.LabelFrame(tab2, text=WIDGET_LABEL)
        self.mySQL2.grid(column=0, row=0, padx=8, pady=4)
        
        # Creating three checkbuttons
        self.chVarDis = tk.IntVar()
        self.check1 = tk.Checkbutton(self.mySQL2, text="Disabled", variable=self.chVarDis, state='disabled')
        self.check1.select()
        self.check1.grid(column=0, row=0, sticky=tk.W)               
        
        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.mySQL2, text="UnChecked", variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W )                  
         
        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.mySQL2, text="Toggle", variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)                 
     
        # trace the state of the two checkbuttons
        self.chVarUn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())    
        self.chVarEn.trace('w', lambda unused0, unused1, unused2 : self.checkCallback())   
        
        # Radiobutton list
        colors = ["Blue", "Gold", "Red"]
        
        self.radVar = tk.IntVar()
        
        # Selecting a non-existing index value for radVar
        self.radVar.set(99)    
        
        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            curRad = 'rad' + str(col)  
            curRad = tk.Radiobutton(self.mySQL2, text=colors[col], variable=self.radVar, value=col, command=self.radCall)
            curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)
            # And now adding tooltips
            tt.createToolTip(curRad, 'This is a Radiobutton control.')
            
        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.mySQL2, text=' Labels within a Frame ')
        labelsFrame.grid(column=0, row=7, pady=6)
         
        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text="Choose a number:").grid(column=0, row=0)
        ttk.Label(labelsFrame, text="Label 2").grid(column=0, row=1)
        
        # Add some space around each label
        for child in labelsFrame.winfo_children(): 
            child.grid_configure(padx=6, pady=1)
            
        number = tk.StringVar()
        self.combo = ttk.Combobox(self.mySQL2, width=12, textvariable=number)
        self.combo['values'] = (1, 2, 4, 42, 100)
        self.combo.grid(column=1, row=7, sticky=tk.W)
        self.combo.current(0)       
        self.combo.bind('<<ComboboxSelected>>', self._combo) 
             
        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.mySQL2, values=(1, 2, 4, 42, 100), width=5, bd=8, command=self._spin) 
        self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1)
        
        # Using a scrolled Text control    
        scrolW  = 40; scrolH = 1
        self.scr = scrolledtext.ScrolledText(self.mySQL2, width=scrolW, height=scrolH, wrap=tk.WORD)
        self.scr.grid(column=0, row=8, sticky='WE', columnspan=3)      
                
        # Create Manage Files Frame ------------------------------------------------
        mngFilesFrame = ttk.LabelFrame(tab2, text=' Manage Files: ')
        mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5)
        
        # Button Callback
        def getFileName():
            print('hello from getFileName')
            fDir  = path.dirname(__file__)
            fName = fd.askopenfilename(parent=self.win, initialdir=fDir)
            print(fName)
            self.fileEntry.config(state='enabled')
            self.fileEntry.delete(0, tk.END)
            self.fileEntry.insert(0, fName)
            
            if len(fName) > self.entryLen:
                self.fileEntry.config(width=len(fName) + 3)
                        
        # Add Widgets to Manage Files Frame
        lb = ttk.Button(mngFilesFrame, text="Browse to File...", command=getFileName)     
        lb.grid(column=0, row=0, sticky=tk.W) 
        
        #-----------------------------------------------------        
        file = tk.StringVar()
        self.entryLen = scrolW - 4
        self.fileEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=file)
        self.fileEntry.grid(column=1, row=0, sticky=tk.W)
              
        #-----------------------------------------------------
        logDir = tk.StringVar()
        self.netwEntry = ttk.Entry(mngFilesFrame, width=self.entryLen, textvariable=logDir)
        self.netwEntry.grid(column=1, row=1, sticky=tk.W) 

        
        def copyFile():
            import shutil   
            src = self.fileEntry.get()
            file = src.split('/')[-1]  
            dst = self.netwEntry.get() + '\\'+ file
            try:
                shutil.copy(src, dst)   
                mBox.showinfo('Copy File to Network', 'Succes: File copied.')     
            except FileNotFoundError as err:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(err))
            except Exception as ex:
                mBox.showerror('Copy File to Network', '*** Failed to copy file! ***\n\n' + str(ex))   
        
        cb = ttk.Button(mngFilesFrame, text="Copy File To :   ", command=copyFile)     
        cb.grid(column=0, row=1, sticky=tk.E) 
                
        # Add some space around each label
        for child in mngFilesFrame.winfo_children(): 
            child.grid_configure(padx=6, pady=6)            
            
        # Creating a Menu Bar ==========================================================
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)
        
        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label="New")
        fileMenu.add_separator()
        fileMenu.add_command(label="Exit", command=self._quit)
        menuBar.add_cascade(label="File", menu=fileMenu)
        
        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label="About")
        menuBar.add_cascade(label="Help", menu=helpMenu)
        
        # Change the main windows icon
        self.win.iconbitmap(r'C:\Python34\DLLs\pyc.ico')
        
        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')
        
        # It is not necessary to create a tk.StringVar() 
        strData = tk.StringVar()
        strData = self.spin.get()
        
        # Place cursor into name Entry
        self.bookTitle.focus()        
      
        # Add a Tooltip to the Spinbox
        tt.createToolTip(self.spin, 'This is a Spin control.')         
        
        # Add Tooltips to more widgets
        tt.createToolTip(self.bookTitle, 'This is an Entry control.')  
        tt.createToolTip(self.action, 'This is a Button control.')                      
        tt.createToolTip(self.scr,    'This is a ScrolledText control.')   
Ejemplo n.º 46
0
class SpaceCatSimulator:
    def __init__(self, master: Tk):

        self.conf = Config()
        self.lang = Language(self.conf.get("lang"))

        self.master = master
        self.master.resizable(height=False, width=False)
        self.master.geometry("510x520")
        if not is_linux:  # Linux does not support .ico files.
            self.master.iconbitmap("resources/spacecat.ico")
        self.master.title(self.lang.title)

        self.MEMORY_SIZE = 256
        self.REGISTER_SIZE = 16
        self.ROW_SIZE = 16
        self.STDOUT_REGISTER_INDICES = [15]

        self.file_path: Optional[str] = None
        self.current_tick: TICK = TICK.LOW
        self.clicked_cells: List[CellEntry] = []

        self.__machine: Simulator = Simulator(self.MEMORY_SIZE,
                                              self.REGISTER_SIZE,
                                              self.STDOUT_REGISTER_INDICES)
        self.__memory_values: List[Cell] = self.__machine.return_memory(
        )  # Memory from previous turn.
        self.__register_values: List[Cell] = self.__machine.return_registers(
        )  # Registers from previous turn.
        self.__define_gui()

    def __define_gui(self):
        self.memory_canvas = Frame(self.master)
        self.register_canvas = Frame(self.master)
        self.monitor_canvas = Frame(self.master)
        self.buttons_frame = Frame(self.master, bd=1, relief=RAISED)
        self.prev_run_cell = 0

        self.cells = [
            CellEntry(index_of=i,
                      register_type="M",
                      list_of=self.__machine.return_memory(),
                      monitor_callback=self.__check_monitor,
                      master=self.memory_canvas,
                      width=3) for i in range(self.MEMORY_SIZE)
        ]
        for cell in self.cells:
            cell.bind("<Button-1>", self.on_click)

        self.registers = [
            CellEntry(index_of=i,
                      register_type="R",
                      list_of=self.__machine.return_registers(),
                      monitor_callback=self.__check_monitor,
                      master=self.register_canvas,
                      width=3) for i in range(self.REGISTER_SIZE)
        ]
        for register in self.registers:
            register.bind("<Button-1>", self.on_click)
        self.__populate_canvases()

        self.__run = Button(master=self.buttons_frame,
                            text=self.lang.run,
                            relief=FLAT,
                            command=self.__run_machine)
        self.__step_button = Button(master=self.buttons_frame,
                                    text=self.lang.step,
                                    relief=FLAT,
                                    command=self.__step)
        self.__editor = Button(master=self.buttons_frame,
                               text=self.lang.editor,
                               relief=FLAT)
        self.__disassemble = Button(master=self.buttons_frame,
                                    text=self.lang.disassemble,
                                    relief=FLAT,
                                    command=self.__dis)
        self.__edit_button = Button(master=self.buttons_frame,
                                    text=self.lang.edit,
                                    relief=FLAT,
                                    command=self.__edit)

        self.__run.grid(row=0, column=0)
        self.__step_button.grid(row=0, column=1)
        self.__editor.grid(row=0, column=2)
        self.__disassemble.grid(row=0, column=3)
        self.__edit_button.grid(row=0, column=4)

        self.menubar = Menu(self.master, relief=RAISED)
        self.file_menu = Menu(self.menubar)
        self.emulator_menu = Menu(self.menubar)
        self.speed = Menu(self.menubar)
        self.speed.add_command(label=self.lang.fast,
                               command=lambda: self.__change_tick(TICK.LOW))
        self.speed.add_command(label=self.lang.medium,
                               command=lambda: self.__change_tick(TICK.MEDIUM))
        self.speed.add_command(label=self.lang.slow,
                               command=lambda: self.__change_tick(TICK.HIGH))
        self.file_menu.add_command(label=self.lang.open,
                                   command=self.open_file)
        self.file_menu.add_command(label=self.lang.save_state,
                                   command=self.__save)
        self.file_menu.add_command(label=self.lang.language_change,
                                   command=self.__language_selection)
        self.file_menu.add_separator()
        self.file_menu.add_command(label=self.lang.exit,
                                   command=lambda: quit())
        self.menubar.add_cascade(label=self.lang.file, menu=self.file_menu)
        self.emulator_menu.add_cascade(label=self.lang.speed, menu=self.speed)
        self.menubar.add_cascade(label=self.lang.simulator,
                                 menu=self.emulator_menu)
        self.master.config(menu=self.menubar)

        self.bottom_bar = Label(
            self.master,
            text=f"{self.lang.decimal}: \t{self.lang.hex}: "
            f"\t{self.lang.float}: \t{self.lang.bin}: ",
            relief=RAISED)

        self.buttons_frame.pack(fill="x", side=TOP)
        self.memory_canvas.pack()
        self.register_canvas.pack()
        self.monitor_canvas.pack(fill="x")
        self.bottom_bar.pack(fill="x", side=BOTTOM)

    def __on_edit(self, entry):
        index = entry.index_of
        if entry.register_type == "R":
            self.__machine.return_registers()[index].value = int(entry.get(),
                                                                 base=16)
        elif entry.register_type == "M":
            self.__machine.return_memory()[index].value = int(entry.get(),
                                                              base=16)

    def __change_tick(self, tick_speed: TICK) -> None:
        """
        Set the machine speed
        :param tick_speed: Speed of the machine in ticks.
        :return: None.
        """
        self.current_tick = tick_speed

    def __save(self) -> None:
        """
        Save the state of the machine.
        :return:
        """
        save_file_name: str = filedialog.asksaveasfilename(
            title=self.lang.save_as,
            filetypes=[(self.lang.prog, ".prg"), (self.lang.svm, ".svm")])
        if save_file_name == "":
            return None
        if save_file_name.endswith(".prg"):
            with open(save_file_name, "wb") as file:
                file.write(self.__machine.dump_program_memory())
        elif save_file_name.endswith(".svm"):
            with open(save_file_name, "wb") as file:
                file.write(self.__machine.dump_program_svm_state())
        else:
            with open(save_file_name + ".prg", "wb") as file:
                file.write(self.__machine.dump_program_memory())
            showwarning(self.lang.warn_title, self.lang.warn_message)

    def __edit(self) -> None:
        """
        Open a NeutronKitty editor to edit the file.
        :return:
        """
        if self.file_path:
            from NeutronKitty import NeutronKitty
            neutron_kitty = NeutronKitty(Tk(),
                                         file_path=self.file_path,
                                         svm=self)

    def __dis(self) -> None:
        """
        Disassemble the file and open a NeutronKitty to edit and see the results.
        :return:
        """
        values = []
        for i in range(0, len(self.__memory_values), 2):
            values.append(
                str(self.__memory_values[i]) +
                str(self.__memory_values[i + 1]))
        dis_ = disassemble(values)
        commands = filter(lambda x: x != "", dis_)
        string = '\n'.join(commands)
        from NeutronKitty import NeutronKitty
        neutron_kitty = NeutronKitty(Tk(), string)

    def __check_monitor(self):
        new_text = self.monitor["text"] + self.__machine.return_stdout()
        self.monitor["text"] = new_text.split("\n")[-1]

    def __sync_machine(self):
        """
        Sync the machine's registers with the entry fields in case modified
        :return:
        """
        print(self.clicked_cells)
        for clicked in self.clicked_cells:
            index = clicked.index_of

    def __run_machine(self):
        """
        Run the machine.
        :return:
        """
        self.__step()
        try:
            self.master.after(self.current_tick.value, self.__run_machine)
        except StopIteration:
            pass

    def __step(self):
        """
        Take a step in the program.
        :return:
        """
        try:
            memory_cells, register_cells = self.__machine.__next__()
            #            self.__sync_machine()
            self.__update_view(memory_cells, register_cells)
            self.__check_monitor()
        except StopIteration:
            pass

    def open_file(self, file_name=None):
        """
        Open a file to load to the memory.
        :return:
        """
        if not file_name:
            file_name: str = filedialog.askopenfilename(
                title=self.lang.select,
                filetypes=((self.lang.asm, "*.asm"), (self.lang.prog, "*.prg"),
                           (self.lang.svm, "*.svm")))
        if file_name.endswith(".asm"):
            self.file_path = file_name
            assembler: Assembler = Assembler.instantiate(
                open(file_name, "r").read(), 256)
            self.__machine.load_memory(assembler.memory)
        elif file_name.endswith(".prg"):
            self.__machine.parse_program_memory(open(file_name, "rb").read())
            self.__reset_ir_pc()
            self.__machine.reset_special_registers()
        elif file_name.endswith(".svm"):
            self.__machine.parse_program_state(open(file_name, "rb").read())
            self.__load_special_registers()
        self.__update_view(self.__machine.return_memory(),
                           self.__machine.return_registers())

    def on_click(self, event: Event):
        """
        When clicked over an event.
        :param event:
        :return:
        """
        value = event.widget.get()
        self.clicked_cells.append(event.widget)
        real_val = int(value, base=16)
        self.bottom_bar["text"] = f"{self.lang.decimal}: {real_val:03}" \
                                  f"\t{self.lang.hex}: {real_val:02X}" \
                                  f"\t{self.lang.float}: {OctalFloat(format(real_val, '02X')).__float__():.3f}" \
                                  f"\t{self.lang.bin}: {real_val:08b}"

    def __populate_canvases(self):
        """
        Populate the canvases by drawing entry fields into them.
        :return:
        """
        for i in range(1, self.ROW_SIZE + 1):
            Label(master=self.memory_canvas, text=f"{i - 1:X}").grid(row=0,
                                                                     column=i)
            Label(master=self.memory_canvas, text=f"{i - 1:X}_").grid(row=i,
                                                                      column=0)
            Label(master=self.register_canvas,
                  text=f"{i - 1:X}").grid(row=0, column=i)
        for i, cell in enumerate(self.cells):
            cell.grid(row=i // self.ROW_SIZE + 1, column=i % self.ROW_SIZE + 1)
        Label(master=self.register_canvas, text="R_").grid(row=1, column=0)
        for i, register in enumerate(self.registers):
            register.grid(row=1, column=i + 1)
        Label(master=self.register_canvas, text="PC: ").grid(row=2,
                                                             column=4,
                                                             columnspan=2)
        self.pc = Entry(master=self.register_canvas, width=3)
        self.pc.grid(row=2, column=6)
        Label(master=self.register_canvas, text="IR: ").grid(row=2,
                                                             column=7,
                                                             columnspan=2)
        self.ir = Entry(master=self.register_canvas, width=6)
        self.ir.grid(row=2, column=9, columnspan=2)
        Button(master=self.register_canvas,
               text="∅",
               command=self.__reset_ir_pc).grid(row=2, column=11)
        self.monitor = Label(self.monitor_canvas, text="", width=1000)
        self.monitor.config(bg="black", fg="green", font=("fixedsys", 15))
        self.monitor.pack(fill="x")
        self.__load_memory_to_view()

    def __reset_ir_pc(self) -> None:
        """
        Reset the instruction register and the pc
        :return:
        """
        self.__machine.reset_special_registers()
        self.__load_special_registers()

    def __load_memory_to_view(self):
        """
        Load the self.memory to view
        :return:
        """
        for i, memory_value in enumerate(self.__memory_values):
            entry_field = self.cells[i]
            entry_field.delete(0, END)
            entry_field.insert(0, str(memory_value))
        for j, register_value in enumerate(self.__register_values):
            register_field = self.registers[j]
            register_field.delete(0, END)
            register_field.insert(0, register_value)
        self.__load_special_registers()

    def __update_view(self, new_memory: List[Cell], new_registers: List[Cell]):
        """
        Update the view without explicitly reloading the view.
        :param new_memory: New memory to be loaded.
        :param new_registers: New registers to be loaded.
        :return:
        """
        register_differences = get_difference(self.__register_values,
                                              new_registers)
        memory_differences = get_difference(self.__memory_values, new_memory)
        self.__memory_values = deepcopy(new_memory)
        self.__register_values = deepcopy(new_registers)
        for change_index, new_value in memory_differences.items():
            self.cells[change_index].set(str(new_value))
        for change_index, new_value in register_differences.items():
            self.registers[change_index].set(str(new_value))
        self.__load_special_registers()
        self.cells[self.__machine.PC]["background"] = "Green"
        self.cells[self.prev_run_cell]["background"] = "White"
        self.prev_run_cell = self.__machine.PC

    def __load_special_registers(self):
        """
        Load the special registers
        :return:
        """
        self.pc.delete(0, END)
        self.pc.insert(0, f"{self.__machine.PC:02X}")
        self.ir.delete(0, END)
        self.ir.insert(0, str(self.__machine.IR))

    def __language_selection(self) -> None:
        """
        Open a window to select the language
        :return:
        """
        lang = {"en": "English", "tr": "Türkçe"}
        lang_rev = {"English": "en", "Türkçe": "tr"}
        langs = ["English", "Türkçe"]
        language_selector = Toplevel(self.master)
        Label(master=language_selector,
              text=self.lang.language_change).grid(row=0, column=0)
        language_selection = StringVar(language_selector)
        language_selection.set(lang[self.conf.get("lang")])
        language_sel = OptionMenu(language_selector, language_selection,
                                  *langs)
        language_sel.grid(row=1, column=0)

        def __set_language():
            self.conf.set("lang", lang_rev[language_selection.get()])
            showwarning(title=self.lang.restart_title,
                        message=self.lang.restart_message)

        approve_button = Button(master=language_selector,
                                text=self.lang.save,
                                command=__set_language)
        approve_button.grid(row=0, column=1, rowspan=2, sticky=W + E + S + N)
Ejemplo n.º 47
0
class GranMenu(GranSelector):
    def __init__(self, parent: Widget, chart_manager, color):
        GranSelector.__init__(self, parent, chart_manager, color)
        self.gran_var = StringVar()
        self.menubutton = Menubutton(
            self,
            textvariable=self.gran_var,
            font=Fonts.FIXED_14,
            width=10,
            background=color,
            foreground=color.contrast,
            bd=0,
            pady=6,
        )
        self.menu = Menu(
            self.menubutton,
            background=color,
            foreground=color.contrast,
            font=Fonts.FIXED_14,
            tearoff=False,
        )
        self.menubutton["menu"] = self.menu
        for item in self.MENU_LAYOUT:
            if item is None:
                self.menu.add_separator()
            else:
                self.menu.add_command(
                    label=item.name, command=partial(self.gran_callback, item)
                )
        grid(self.menubutton, 0, 0)

    def set_gran(self, gran: Optional[Gran]):
        if gran is None:
            self.gran_var.set("gran")
            self.menubutton.config(foreground="grey")
        else:
            self.gran_var.set(gran.name)
            self.menubutton.config(foreground=self.color.contrast)

    def gran_callback(self, gran: Gran):
        self.apply_gran(gran)

    MENU_LAYOUT = (
        Gran.M,
        Gran.W,
        Gran.D,
        None,
        Gran.H12,
        Gran.H8,
        Gran.H6,
        Gran.H4,
        Gran.H3,
        Gran.H2,
        Gran.H1,
        None,
        Gran.M30,
        Gran.M15,
        Gran.M10,
        Gran.M5,
        Gran.M4,
        Gran.M2,
        Gran.M1,
    )
    """
Ejemplo n.º 48
0
def mainwindow():
    window = Tk()
    window.title("Welcome.............!!!!!!!!")
    window.geometry('650x500')
    menu = Menu(window)
    #tearoff is used foe floating members in menu
    #NEW
    filemenu = Menu(menu, tearoff=0)
    menu.add_cascade(label='New', menu=filemenu)
    filemenu.add_command(label='Student', command=studentwindow)
    filemenu.add_separator()
    filemenu.add_command(label='Faculty', command=facultywindow)
    filemenu.add_separator()
    filemenu.add_command(label='Exit', command=quit)
    window.config(menu=menu)
    #EDIT
    editmenu = Menu(menu, tearoff=0)
    menu.add_cascade(label='Edit', menu=editmenu)
    editmenu.add_command(label='Marks', )
    editmenu.add_separator()
    editmenu.add_command(label='Attendence')
    editmenu.add_command(label='Profile')
    window.config(menu=menu)

    #OPEN
    opnmenu = Menu(menu, tearoff=0)
    menu.add_cascade(label='Open', menu=opnmenu)
    opnmenu.add_command(label='Notepad', command=notepad1)
    opnmenu.add_separator()
    opnmenu.add_command(label='Paint', command=MsPaint)
    opnmenu.add_separator()
    opnmenu.add_command(label='Calculator', command=clc)
    opnmenu.add_separator()
    opnmenu.add_command(label='Camera', command=cmra)
    window.config(menu=menu)
    window.mainloop()
Ejemplo n.º 49
0
class Note_book:
    def __init__(self):
        self.__root = Tk()
        self.__root.title('Untitled - Text Editor')
        self.__root.geometry('640x320')
        ##ICON
        try:
            self.__root.wm_iconbitmap("note.ico")
        except:
            print("'note.ico' was not found in root directory.")

        self.__textArea = Text(self.__root, undo=True)

        self.__edited = False
        self.__filename = None

        self.__menubar = Menu(self.__root)
        self.__root.config(menu=self.__menubar)

        self.__fileMenu = Menu(self.__menubar, tearoff=0)
        ###FILE MENU
        self.__fileMenu.add_command(label='New', command=self.__new)
        self.__fileMenu.add_command(label='Open', command=self.__open)
        self.__fileMenu.add_separator()
        self.__fileMenu.add_command(label='Save', command=self.__save)
        self.__fileMenu.add_command(label='Save as', command=self.__saveas)
        self.__fileMenu.add_separator()
        self.__fileMenu.add_command(label='Exit', command=self.__exit)
        ##FILE submenu options
        self.__menubar.add_cascade(label='File', menu=self.__fileMenu)

        ###EDIT MENU
        self.__editMenu = Menu(self.__menubar, tearoff=0)
        ##EDIT submenu options
        self.__editMenu.add_command(label='Undo',
                                    command=self.__textArea.edit_undo)
        self.__editMenu.add_command(label='Redo',
                                    command=self.__textArea.edit_redo)
        self.__editMenu.add_separator()
        self.__editMenu.add_command(label="Cut", command=self.__cut)
        self.__editMenu.add_command(label="Copy", command=self.__copy)
        self.__editMenu.add_command(label="Paste", command=self.__paste)
        self.__menubar.add_cascade(label='Edit', menu=self.__editMenu)

        self.__helpMenu = Menu(self.__menubar, tearoff=0)
        ###help options
        self.__helpMenu.add_command(label="About", command=self.__about)
        self.__helpMenu.add_command(label="Go to my Github",
                                    command=self.__help)
        self.__helpMenu.add_command(label="Feedback", command=self.__feedback)
        self.__menubar.add_cascade(label="Options", menu=self.__helpMenu)

        self.__root.grid_rowconfigure(0, weight=1)
        self.__root.grid_columnconfigure(0, weight=1)

        self.__textArea.grid(sticky=N + E + S + W)
        self.__scrollbar = Scrollbar(self.__textArea)

        ##scrollbar auto adjusting
        self.__scrollbar.pack(side=RIGHT, fill=Y)
        self.__scrollbar.config(command=self.__textArea.yview)
        self.__textArea.config(yscrollcommand=self.__scrollbar.set)

        ####menu shortcuts
        self.__root.bind('<Control-n>', lambda event: self.__new())
        self.__root.bind('<Control-o>', lambda event: self.__open())
        self.__root.bind('<Control-s>', lambda event: self.__save())
        self.__root.bind('<Control-Shift-s>', lambda event: self.__saveas())

        self.__root.mainloop()

    ####options fmethods
    def __about(self):
        dbox("About - Text Editor",
             "Created by:\nRamdayal Munda\n\nVersion 1.0")

    def __help(self):
        opensite("https://github.com/RDayalMunda/first")

    def __feedback(self):
        dbox(
            "Feedback?",
            "\nThis option is not available yet.\nPlease wait for further update."
        )

    ##edit menu methods
    def __cut(self):
        print('cutting')
        print('self.__menubar= ', self.__menubar)
        print('self.__editmenu= ', self.__editmenu)
        self.__textArea.event_generate("<<Cut>>")

    def __copy(self):
        print('copying')
        self.__textArea.event_generate("<<Copy>>")

    def __paste(self):
        print('pasting')
        self.__textArea.event_generate("<<Paste>>")


##file menu methods
##NEW FILE

    def __new(self):
        print(self.__filename)
        self.__filename = None
        self.__root.title('Untitled - Text Editor')
        self.__textArea.delete(1.0, END)
        print('newed')

    ##OPEN EXISTING FILE
    def __open(self):
        self.__filename = askopenfilename(defaultextension='.txt',
                                          filetypes=[('All Files', '*.*'),
                                                     ('Text Documents',
                                                      '*.txt*')])
        if self.__filename == '':
            self.__filename = None
        else:
            self.__root.title(basename(self.__filename) + " -Text Editor")
            self.__textArea.delete(1.0, END)
            file = open(self.__filename, "r")
            self.__textArea.insert(1.0, file.read())
            file.close()

    ###SAVE NEW FILE OR OVERWRITE IT
    def __save(self):
        if self.__filename == None:
            self.__saveas()
        else:
            text = self.__textArea.get('1.0', 'end-1c')
            file = open(self.__filename, 'w')
            file.write(text)
            file.close()
            print('saved')

    def __saveas(self):
        self.__filename = asksaveasfilename(initialfile='Untitled.txt',
                                            defaultextension='.txt',
                                            filetypes=[('Text Documents',
                                                        '*.txt*'),
                                                       ('All Files', '*.*')])
        if self.__filename == '':
            self.__filename = None
        else:
            file = open(self.__filename, 'w')
            file.write(self.__textArea.get(1.0, END))
            file.close
            self.__root.title(basename(self.__filename) + " -Text Editor")
            print('saved as')

    def __exit(self):
        print('exitted')
        self.__root.destroy()
Ejemplo n.º 50
0
class GUI:
 # Metodo que contiene la definicion de la interfaz grafica 
    def __init__(self):
        self.window = Tk()
        
        self.txtEntrada = Entry(self.window,width=10)
        self.txtConsola = Entry(self.window,width=10)
        self.txtrecorrido=Entry(self.window,width=10)
        self.txtTOKEN=Entry(self.window,width=10)
        # Propiedades de la ventana
        self.window.title("Proyecto 1 - MYNOR SABAN")
        self.window.geometry('1600x1000')
        self.window.configure(bg = '#9ACFEF')
              

        # propiedades del menu 
        self.menu = Menu(self.window)
        self.file_item = Menu(self.menu)  #Menu File
        self.file_item.add_command(label='Open File', command=self.abrirFile)
        self.file_item.add_separator()
        self.file_item.add_command(label='Analyze')
        self.file_item.add_separator()
        self.file_item.add_command(label='Exit')
 
        self.report_item = Menu(self.menu)    # menu Reports
        self.report_item.add_separator()
        self.report_item.add_command(label='Errors')
        self.report_item.add_separator()
        self.report_item.add_command(label='Tree')
        
        self.menu.add_cascade(label='File', menu=self.file_item)
        self.menu.add_cascade(label='Reports', menu=self.report_item) 
        self.window.config(menu=self.menu)
        
        # propiedades del textarea
        self.txtEntrada = scrolledtext.ScrolledText(self.window,width=80,height=25)   # textArea Entrada
        self.txtEntrada.place(x=50, y = 50)
        #ent = txtEntrada.get("1.0","10.10")
        #print("ent: ",ent)
        self.lbl1 = Label(self.window, text="RECORRIDO:")  #label 
        self.lbl1.place(x=800, y =35)
        self.txtrecorrido = scrolledtext.ScrolledText(self.window,width=50,height=20)   # textArea Entrada
        self.txtrecorrido.place(x=800, y =50)
        self.lbl2 = Label(self.window, text="TOKENS:")  #label 
        self.lbl2.place(x=800, y =400)
        self.txtTOKEN = scrolledtext.ScrolledText(self.window,width=50,height=15)   # textArea Entrada
        self.txtTOKEN.place(x=800, y = 425)

        self.lbl = Label(self.window, text="Console:")  #label 
        self.lbl.place(x=50, y = 465)
        self.txtConsola = scrolledtext.ScrolledText(self.window,width=80,height=10)   # textArea consola
        self.txtConsola.place(x=50, y = 490)
        self.btn = Button(self.window, text="JS", bg="black", fg="white", command=self.Analyze)    #btn Analyze
        self.btn1 = Button(self.window, text="CSS", bg="black", fg="white", command=self.anaCSS) 
        self.btn.place(x=400, y = 460)
        self.btn1.place(x=350, y = 460)
        # Dispara la interfaz
        self.window.mainloop()


    def Analyze(self):
        entrada = self.txtEntrada.get("1.0", END) #fila 1 col 0 hasta fila 2 col 10
        miScanner = ANALIZADORJS()
        retorno = miScanner.analizar(entrada)
        print("\nIMPRESION DE ERRORES\n")
        miScanner.imprimirErrores()
        self.txtConsola.insert("1.0", retorno)
        toke=miScanner.imprimirtoken()
        self.txtTOKEN.insert("1.0",toke)
        record=miScanner.imprimirtra()
        self.txtrecorrido.insert("1.0",record)
        miScanner.generarGrafo()

    def anaCSS(self):
        """entrada = self.txtEntrada.get("1.0", END)
        analiza= Scanner()
        retorno =analiza.analizar(entrada)
        self.txtConsola.insert("1.0", retorno)
        token =analiza.imprimirTokens()
        self.txtTOKEN.insert("1.0",token)"""
        entrada= self.txtEntrada.get("1.0",END)
        analiza=  analizadorCSS()
        retorno =analiza.analizar(entrada)
        self.txtConsola.insert("1.0", retorno)
        token =analiza.imprimirTokens()
        self.txtTOKEN.insert("1.0",token)
        recor =analiza.imprimirRecorrido()
        self.txtrecorrido.insert("1.0",recor)
        print("Errores")
        analiza.imprimirErrores()
        analiza.generarGrafo()
        

    # Dispara el Filechooser
    def abrirFile(self):
        nameFile=filedialog.askopenfilename(title = "Seleccione archivo",filetypes = (("js files","*.js"), ("html files","*.html"),("css files","*.css"),("All Files","*.*")))
        if nameFile!='':
            archi1=open(nameFile, "r", encoding="utf-8")
            contenido=archi1.read()
            archi1.close()
            self.txtEntrada.delete("1.0", END)
            self.txtEntrada.insert("1.0", contenido) 
    
    def seleccionar(self,lenguaje):
        cadena = ""
        if (lenguaje.get()):
            print("selecciono css")
        else:
            print(" no css")
Ejemplo n.º 51
0
    def BuildMainFrame(self): 
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master,activeborderwidth=0,bd=0)
        self.master.config(menu=menu)
  
        filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="File", underline=0,  menu=filemenu)
        filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand)
        filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand)
        filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)
  
        self.output_to_file = StringVar()
        self.output_to_file.set('n')
 
        scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu,modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu)
 
        editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Edit",underline=0,  menu=editmenu)
        editmenu.add_cascade(label="Insert script",menu=scriptmenu)
        editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input", command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output", command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n')
        editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w')
        editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a')
        editmenu.add_command(label="Output file...", command=self.OutputFileCommand)

        runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line", command=self.RunLineCommand)
        runmenu.add_command(label="Run selection", command=self.RunSelectionCommand)
       
        helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand)
        helpmenu.add_command(label="About", underline=0, command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)
        
        self.wordIndex = ['1.0','1.0']
               
        self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9)
        self.suggestionslist.insert(END,"foo")
        self.suggestionslist.pack(side=TOP,fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0,weight=1)
        self.master.columnconfigure(0,weight=1)
        content = Frame(self.master,bd=0,padx=2,pady=2) 
        content.grid(row=0,column=0,sticky=N+S+W+E)
        content.rowconfigure(0,weight=1,minsize=50)
        content.rowconfigure(1,weight=0)
        content.columnconfigure(0,weight=1)

        panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True)
        panes.grid(row=0,column=0,sticky=N+S+W+E)

        frame1 = Frame(panes,bd=0) 
        frame1.grid(row=0,column=0,sticky=N+S+W+E)
        frame1.columnconfigure(0,weight=1)
        frame1.columnconfigure(1,weight=0)
        frame1.rowconfigure(0,weight=1)

        panes.add(frame1,height=300,minsize=20)        

        frame2 = Frame(panes,bd=0) 
        frame2.grid(row=1,column=0,sticky=N+S+W+E)
        frame2.columnconfigure(0,weight=1)
        frame2.columnconfigure(1,weight=0)
        frame2.rowconfigure(0,weight=1)
        
        panes.add(frame2,minsize=20) 
 
        self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)
 
        self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set    

        self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0)
        
        self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set    
      
        self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0,column=0,sticky=N+S+W+E)
        self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_output.grid(row=0,column=0,sticky=N+S+W+E)
        self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_entry.grid(row=1,column=0,sticky=N+S+W+E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
Ejemplo n.º 52
0
    def __init__(self, master):

        with open('config.json', 'r') as file:
            self.config = json.load(file)

        master.title('My Journal')
        master.configure(background=self.config['master'])
        master.resizable(False, False)

        # TODO
        # add checklist

        style = ttk.Style()
        style.configure('TEntry',
                        foreground=self.config['entry']['foreground'],
                        fieldbackground=self.config['entry']['background'],
                        font=(self.config['entry']['font'],
                              self.config['entry']['font_size']
                              )
                        )
        style.configure('main.TLabel',
                        background=self.config['label']['background'],
                        foreground=self.config['label']['foreground'],
                        font=(self.config['label']['font'],
                              self.config['label']['font_size']
                              )
                        )

        ttk.Label(master, text='Location: ', style='main.TLabel').grid(
            row=1, column=0, padx=2, pady=3)
        
        self.location_entry = ttk.Entry(master, width=100)
        self.location_entry.grid(row=1, column=2, padx=2, pady=3)

        self.refresh_location_button = HoverButton(master, text="Refresh",
                                                   background=self.config['button']['background'],
                                                   foreground=self.config['button']['foreground'],
                                                   command=lambda: self.refresh_location())
        self.refresh_location_button.grid(row=1, column=3,  padx=2, pady=3)

        # self.text_frame = ttk.Frame(master, width=100, height=100)
        # self.text_frame.grid(row=2, column=0, columnspan=2)

        self.text_entry = Text(
            master, height=30, wrap='word',
            background=self.config['text_field']['background'],
            foreground=self.config['text_field']['foreground'],
            font=(self.config['text_field']['font'],
                  self.config['text_field']['font_size'])

        )

        self.text_entry.grid(row=2, column=0, columnspan=4,
                             sticky='NESW', padx=2, pady=5)

        self.submit_button = HoverButton(master, text="Submit",
                                         background=self.config['button']['background'],
                                         foreground=self.config['button']['foreground'],
                                         command=lambda: self.submit())

        self.submit_button.grid(
            row=3, column=0, sticky='NE', padx=2, pady=5)

        self.clear_button = HoverButton(master, text="Clear",
                                        background=self.config['button']['background'],
                                        foreground=self.config['button']['foreground'],
                                        command=lambda: self.clear())
        self.clear_button.grid(row=3, column=1, sticky='NW', padx=10, pady=5)

        self.about_button = HoverButton(master, text="About",
                                        background=self.config['button']['background'],
                                        foreground=self.config['button']['foreground'],
                                        command=lambda: self.show_help())
        self.about_button.grid(row=3, column=2, sticky='NE', padx=10, pady=5)

        self.customise_button = HoverButton(master, text="Customise Colors",
                                            background=self.config['button']['background'],
                                            foreground=self.config['button']['foreground'],
                                            command=lambda: self.customize(master))
        self.customise_button.grid(
            row=3, column=3, sticky='NE', padx=10, pady=5)

        menubar = Menu(master)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(
            label='    Submit', command=lambda: self.submit(), accelerator='Ctrl+Enter')
        filemenu.add_separator()
        filemenu.add_command(
            label='    Exit', command=lambda: master.quit(), accelerator='Ctrl+X')
        menubar.add_cascade(label='File', menu=filemenu)

        master.config(menu=menubar)

        self.refresh()
        # self.refresh_location()

        # keyboard bindings
        master.bind('<Control-Return>', lambda e: self.submit())
        master.bind('<Control-x>', lambda e: master.quit())
        self.text_entry.focus()
Ejemplo n.º 53
0
optionDropDown = Menu(mainMenuBar, tearoff=0)

# Add the File cascade to the mainMenuBar
mainMenuBar.add_cascade(label="File", menu=fileDropDown)
mainMenuBar.add_cascade(label="Options", menu=optionDropDown)

# Variable for alphabetical char list order
charABCOrder = tk.IntVar()
charABCOrder.set(0)

# Add options to the mainFileDropDown Cascade
fileDropDown.add_command(label="Open", command=palEdit.openFileCmd)
fileDropDown.add_command(label="Save As...",
                         command=palEdit.saveFileCmd,
                         state="disabled")
fileDropDown.add_separator()
fileDropDown.add_command(label="Quit", command=root.quit)

# Add options to the Options Cascade
optionDropDown.add_checkbutton(label="Show Characters Alphabetically",
                               onvalue=1,
                               offvalue=0,
                               variable=charABCOrder,
                               command=updateCharList)

# Bind MouseOver events
fileDropDown.bind("<<MenuSelect>>", mOver_File)
optionDropDown.bind("<<MenuSelect>>", mOver_Options)

#######################
##### MAIN WINDOW #####
Ejemplo n.º 54
0
    def init_menu(self):
        """加载菜单"""

        # 创建菜单栏
        self.menubar = Menu(self.root)

        # 将菜单栏添加到窗口
        self.root.config(menu=self.menubar)

        # 文件下拉菜单
        filemenu = Menu(self.menubar, tearoff=0)
        filemenu.add_command(label="新建", command=self.file_new)
        filemenu.add_command(label="打开", command=self.file_open)
        filemenu.add_command(label="保存", command=self.file_save)
        filemenu.add_command(label="另存为", command=self.file_save)
        filemenu.add_separator()
        filemenu.add_command(label="退出", command=self.root.quit)

        # 用户下拉菜单
        usermenu = Menu(self.menubar, tearoff=0)
        usermenu.add_command(label="用户列表", command=self.master.open_user_list)
        usermenu.add_command(label="用户添加", command=self.master.open_user_add)
        usermenu.add_command(label="用户详情窗口", command=self.master.open_user_info)

        # 文章下拉菜单
        articlemenu = Menu(self.menubar, tearoff=0)
        articlemenu.add_command(label="文章查询", command=self.master.open_content_list)
        articlemenu.add_command(label="文章添加", command=self.master.open_content_add)
        articlemenu.add_command(label="文章统计", command=self.master.open_content_count)

        # 数据下拉菜单
        datamenu = Menu(self.menubar, tearoff=0)
        datamenu.add_command(label="下载", command=self.master.open_download)
        datamenu.add_command(label="上传", command=self.master.open_upload)
        datamenu.add_command(label="同步", command=self.master.open_synchronize)
        datamenu.add_command(label="备份", command=self.master.open_backup)

        # 窗口下拉菜单
        window_menu = Menu(self.menubar)
        window_menu.add_command(label="最大化")
        window_menu.add_command(label="最小化")
        window_menu.add_separator()
        window_menu.add_command(label="窗口置顶", command=self.master.window_to_top)
        window_menu.add_command(label="取消置顶", command=self.master.window_not_top)
        window_menu.add_separator()
        window_menu.add_command(label="主界面", command=self.master.open_home)
        window_menu.add_command(label="切换到: 用户")
        window_menu.add_command(label="切换到: 文章列表")

        # 帮助下拉菜单
        helpmenu = Menu(self.menubar, tearoff=0)
        helpmenu.add_command(label="欢迎使用", command=self.help_about)
        helpmenu.add_command(label="文档", command=self.help_about)
        helpmenu.add_command(label="版权声明", command=self.help_about)
        helpmenu.add_command(label="隐私声明", command=self.help_about)
        helpmenu.add_separator()
        helpmenu.add_command(label="联系我们", command=self.master.open_ontact)
        helpmenu.add_command(label="关于", command=self.master.open_about)

        # 将下拉菜单加到菜单栏
        self.menubar.add_cascade(label="文件", menu=filemenu)
        self.menubar.add_cascade(label="用户", menu=usermenu)
        self.menubar.add_cascade(label="文章", menu=articlemenu)
        self.menubar.add_cascade(label="数据", menu=datamenu)
        self.menubar.add_cascade(label="窗口", menu=window_menu)
        self.menubar.add_cascade(label="帮助", menu=helpmenu)
Ejemplo n.º 55
0
    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match', underline=0,
                             command=self.match, accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand', underline=0,
                             command=self.expand, accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack', underline=0,
                             command=self.backtrack, accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=10, accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=5, accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=2, accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)
Ejemplo n.º 56
0
#按钮事件
def clicked1():
    print('new1')


def clicked2():
    print('new2')


#菜单
menu = Menu(window)
#第一个主菜单项
new_item1 = Menu(menu, tearoff=0)  #去掉虚线
new_item1.add_command(label='New1', command=clicked1)
new_item1.add_separator()
new_item1.add_command(label='Edit1')
new_item1.add_separator()
new_item1.add_command(label='hello1')
menu.add_cascade(label='File1', menu=new_item1)

#第二个主菜单项
new_item2 = Menu(menu, tearoff=0)  #去掉虚线
new_item2.add_command(label='New2', command=clicked2)
new_item2.add_separator()
new_item2.add_command(label='Edit2')
new_item2.add_separator()
new_item2.add_command(label='hello2')
menu.add_cascade(label='File2', menu=new_item2)

#第三个主菜单项
Ejemplo n.º 57
0
# Exit GUI cleanly
def _quit():
    win.quit()
    win.destroy()
    exit()


# Creating a Menu Bar
menu_bar = Menu(win)
win.config(menu=menu_bar)

# Add menu items
file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=_quit)
menu_bar.add_cascade(label="File", menu=file_menu)


# Display a Message Box
def _msgBox():
    msg.showinfo('Python Message Info Box',
                 'A Python GUI created using tkinter:\nThe year is 2017.')


# Add another Menu to the Menu Bar and an item
help_menu = Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About",
                      command=_msgBox)  # display messagebox when clicked
menu_bar.add_cascade(label="Help", menu=help_menu)
Ejemplo n.º 58
0
#for EXIT menu option
def exiting():
    if (messagebox.askyesno("quit?", "This is a python IDE")):
        root.destroy()


#for ABOUT menu option
def about():
    label = messagebox.showinfo("About!!")


# adding menu options
menu = Menu(root)
root.config(menu=menu)
fileMenu = Menu(menu)
menu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="NEW")
fileMenu.add_command(label="OPEN",
                     command=openfile)  # will redirect to open file
fileMenu.add_command(label="SAVE", command=savefile)
fileMenu.add_command(label="SAVE AS")
fileMenu.add_separator()
fileMenu.add_command(label="EXIT", command=exiting)
helpMenu = Menu(menu)
menu.add_cascade(label="Help")
menu.add_cascade(label="About", command=about)

textArea.pack()

root.mainloop()  #to open
Ejemplo n.º 59
0
def CrearMenu(masterRoot):
    global tools
    ########### menu ############
    #Se crea la barra
    barraDeMenu = Menu(masterRoot,
                       tearoff=0,
                       relief=FLAT,
                       font=("Verdana", 12),
                       activebackground='gray59')
    barraDeMenu.config(bg='gray21', fg='white')
    #Se crean los menus que se deseen
    archivo = Menu(barraDeMenu,
                   tearoff=0,
                   bg='gray21',
                   fg='white',
                   activebackground='gray59')
    #Crear las opciones de la opción del menú
    #Se elimino el comando de crear Ventana por problemas con las imagenes

    archivo.add_command(label="Nueva ventana")
    archivo.add_command(label="Abrir query", command=abrir)
    archivo.add_command(label="Abrir un modelo")
    archivo.add_separator()
    archivo.add_command(label="Nueva Query", command=lambda: añadir('Nuevo'))
    archivo.add_command(label="Guardar como...", command=guardarComo)
    archivo.add_command(label="Guardar", command=guardarArchivo)
    archivo.add_command(label="Cerrar pestaña actual", command=cerrarPestaña)
    archivo.add_separator()
    archivo.add_command(label="Salir", command=cerrarVentana)

    #creando el Editar
    editar = Menu(barraDeMenu,
                  tearoff=0,
                  bg='gray21',
                  fg='white',
                  activebackground='gray59')
    #agregando su lista
    editar.add_command(label="Cortar")
    editar.add_command(label="Pegar")
    editar.add_command(label="Copiar")
    editar.add_separator()
    editar.add_command(label="Seleccionar todo")
    editar.add_command(label="Formato")
    editar.add_command(label="Preferencias")

    #se agrega Tools
    tools = Menu(barraDeMenu,
                 tearoff=0,
                 bg='gray21',
                 fg='white',
                 activebackground='gray59')
    #se agrega su lista
    tools.add_command(label="Configuración")
    tools.add_command(label="Utilidades")
    tools.add_command(label="Limpiar consola", command=LimpiarConsola)
    #Temporary tools to test client-server connection
    tools.add_command(label="GET USERS", command=myGET)
    tools.add_command(label="CREATE USER", command=crearUsuario)
    #Log In sera parte de la barra de herramientas
    tools.add_command(label="LOGIN", command=LogIn)

    #se agrega ayuda
    ayuda = Menu(barraDeMenu,
                 tearoff=0,
                 bg='gray21',
                 fg='white',
                 activebackground='gray59')
    #lista de ayuda
    ayuda.add_command(label="Documentación de TytuSQL")
    ayuda.add_command(label="Acerca de TytuSQL")

    #Se agrgan los menús a la barra
    barraDeMenu.add_cascade(label="Archivo", menu=archivo)
    barraDeMenu.add_cascade(label="Editar", menu=editar)
    barraDeMenu.add_cascade(label="Herramientas", menu=tools)
    barraDeMenu.add_cascade(label="Ayuda", menu=ayuda)
    #Se indica que la barra de menú debe estar en la ventana
    return barraDeMenu
Ejemplo n.º 60
0

def About():
    messagebox.showinfo(
        message=
        " TytusDB \n Universidad de San Carlos de Guatemala \n Facultad de Ingenieria \n Ingenieria en Ciencias y Sistemas \n \n Estructuras de Datos \n Diciembre 2020 \n Catedratico M.SC. Luis Fernando Espino Barrios \n Auxiliar Carlos Andree Avalos Soto \n \n Estudiantes: \n Edwin Mauricio Mazariegos \n Edgar Enrique Patzan Yoc \n Gabriel Orlando Ajsivinac Xicay \n Walter Manolo Martinez Mateo \n Karen Elisa Lopez Pinto",
        title="About...")


miAplicacion = Tk()
miAplicacion.minsize(1200, 700)
miAplicacion.maxsize(1200, 700)
menubar = Menu(miAplicacion)
help = Menu(menubar, tearoff=0)
help.add_command(label="About", command=About)
help.add_separator()
help.add_command(label="Grafica Bases de Datos", command=GraficaBasesDatos)
help.add_separator()
help.add_command(label="Exit", command=miAplicacion.quit)
menubar.add_cascade(label="Help", menu=help)
miAplicacion.config(menu=menubar)

treeview = ttk.Treeview(selectmode=tk.BROWSE)
treeview.place(x=10, y=10)
treeview.heading("#0", text="TytusDB - Modo AVL")
treeview.tag_bind("mytag", "<<TreeviewSelect>>", item_selected)

treeRegs = ttk.Treeview(selectmode=tk.BROWSE)
treeRegs.place(x=10, y=410)
treeRegs.tag_configure('par', background='white', foreground='black')
treeRegs.tag_configure('impar', background='black', foreground='white')