Exemplo n.º 1
0
    def __init__(self, parentWindow, title=None, okText=None, cancelText=None, geometry=None):

        tk.Toplevel.__init__( self, parentWindow )
        self.transient( parentWindow )

        self.parentWindow = parentWindow
        if title: self.title( title )

        self.result = None # Used to return an optional result

        if okText is None: okText = _("Ok")
        self.okText = okText
        if cancelText is None: cancelText = _("Cancel")
        self.cancelText = cancelText
        self.makeButtonBox()

        body = Frame( self )
        self.initial_focus = self.makeBody( body ) # Create the widgets in the body
        body.pack( padx=5, pady=5, fill=tk.BOTH, expand=tk.YES )

        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol( 'WM_DELETE_WINDOW', self.cancel ) # Ensure that closing the dialog does a cancel

        self.geometry( geometry if geometry else "+{}+{}".format(parentWindow.winfo_rootx()+50, parentWindow.winfo_rooty()+50) )

        self.parentWindow.parentApp.setStatus( _("Waiting for user input…") )
        self.initial_focus.focus_set()
        self.wait_window( self )
Exemplo n.º 2
0
    def initUI(self, server):
      
        self.parent.title("TrackWise Service Manager")
        self.pack(fill=BOTH, expand = True, padx = 300)
        # self.centerWindow()

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

        fileMenu = Menu(menubar)
        fileMenu.add_command(label = "Exit", command = self.onExit)
        menubar.add_cascade(label = "File", menu = fileMenu)

        svcsMenu = Menu(menubar)
        svcsMenu.add_command(label = "List Service Status", command = self.onStatus)
        svcsMenu.add_command(label = "Stop Services", command = self.onStop)
        svcsMenu.add_command(label = "Start Services", command = self.onStart)
        menubar.add_cascade(label = "Services", menu = svcsMenu)

        # svcs = ['TrackWise Tomcat', 'Web Services Tomcat', 'QMD Tomcat', 'Keystone Intake', 'ID Intake', 'TWC']
        svcs = server.getservices()
        hostname = server.gethostname().strip()
        servertype = server.gettype().strip()

        frame0 = Labelframe(self, text = "Server Details",  borderwidth = 1)
        frame0.grid(column = 0, row = 0, sticky = W)
        
        so = StringVar()
        svroverview = Message(frame0, textvariable = so, anchor = W, width = 300)
        svroverview.grid(column = 0, row = 0)
        sstr = "Server: {}\n".format(hostname)
        sstr += "Server Type: {}".format(servertype)
        so.set(sstr)
        
        
        frame1 = Labelframe(self, text = "Service Status", borderwidth = 1)
        frame1.grid(column = 0, row = 1, sticky = W)


        l = StringVar()
        label1 = Message(frame1, textvariable = l , anchor = W)
        
        svcscount = 0

        lstr = ""

        for i in svcs:
            svcscount += 1 
            lstr += '{} - '.format(i) + ('UP\n' if svcscount % 2 else 'DOWN\n')
      
            
        l.set(lstr)
        label1.pack(side=TOP, padx = 5, pady = 5)   

        frame4 = Frame(self, relief=RAISED, borderwidth = 1)
        frame4.grid(column = 0, row = 2, sticky = W)
        closeButton = Button(frame4, text="Close", command = self.quit)
        closeButton.grid(column = 0, row = 0)
        okButton = Button(frame4, text = "OK")
        okButton.grid(column = 1, row = 0)
Exemplo n.º 3
0
 def add_buttons(self):
     frame = Frame(self)
     frame.pack(fill="x")
     edit = Button(frame, text="Edit", command=self.edit)
     edit.pack(side="right", padx=5, pady=5)
     delete = Button(frame, text="Del", command=self.delete_menu)
     delete.pack(side="right")
Exemplo n.º 4
0
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.grid(sticky=N+E+S+W)

        self.initui()
Exemplo n.º 5
0
    def __init__(self, parent, title=None, okText=None, cancelText=None):

        tk.Toplevel.__init__( self, parent )
        self.transient( parent )

        self.parent = parent
        if title: self.title( title )

        if okText is None: okText = _("Ok")
        self.okText = okText
        if cancelText is None: cancelText = _("Cancel")
        self.cancelText = cancelText

        self.result = None # Used to return an optional result

        body = Frame( self )
        self.initial_focus = self.body( body ) # Create the widgets in the body
        body.pack( padx=5, pady=5 )

        self.buttonbox()

        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol( "WM_DELETE_WINDOW", self.cancel ) # Ensure that closing the dialog does a cancel

        self.geometry( "+{}+{}".format(parent.winfo_rootx()+50, parent.winfo_rooty()+50) )

        self.parent.parentApp.setStatus( _("Waiting for user input...") )
        self.initial_focus.focus_set()
        self.wait_window( self )
Exemplo n.º 6
0
 def __init__(self, parent):
     Frame.__init__(self, parent)
     self.parent = parent
     self.grid()
     self.init_ui()
     self.wallhandler = WallHandler()
     self.reddit = Reddit()
Exemplo n.º 7
0
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent 

        self.music_root = ''
        self.query_path = ''
        self.extractor = Extractor(n_frames=40, 
                                   n_blocks=100, 
                                   learning_rate=0.00053,
                                   verbose=True)

        self.style = Style()
        self.style.theme_use("default")
        
        padx = 2
        pady = 2

        root_select_button = Button(self, text="Select a directory")
        root_select_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        root_select_button.bind("<Button-1>", self.set_music_root)

        analyze_button = Button(self, text="Analyze")
        analyze_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        analyze_button.bind("<Button-1>", self.analyze)

        query_select_button = Button(self, text="Select a file")
        query_select_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        query_select_button.bind("<Button-1>", self.set_query_path)

        search_button = Button(self, text="Search similar songs")
        search_button.pack(fill=tkinter.X, padx=padx, pady=pady)
        search_button.bind("<Button-1>", self.search_music)
 
        self.pack(fill=BOTH, expand=1)
Exemplo n.º 8
0
    def __init__(self, parent, music_filepath):
        Frame.__init__(self, parent)
        self.player = Player(music_filepath)
        
        title = os.path.basename(music_filepath) 

        label = tkinter.Label(self, text=title, width=30)
        label.pack(side=LEFT)

        padx = 10
        #image = tkinter.PhotoImage(file=icon_play)
        play_button = Button(self, text="Play")#image=image)
        play_button.pack(side=LEFT, padx=padx)
        play_button.bind("<Button-1>", self.play)
        
        #image = tkinter.PhotoImage(file=icon_pause)
        #pause_button = Button(self, text="Pause")#image=image)
        #pause_button.pack(side=LEFT, padx=padx)
        #pause_button.bind("<Button-1>", self.pause)
        #self.pausing = False
        
        #image = tkinter.PhotoImage(file=icon_stop)
        stop_button = Button(self, text="Stop")#image=image)
        stop_button.pack(side=LEFT, padx=padx)
        stop_button.bind("<Button-1>", self.stop)
Exemplo n.º 9
0
    def __init__(self, master, origin=(0, 0)):
        Frame.__init__(self, master)
        self.origin = origin
        self.goban = golib.gui.Goban(self)
        self.buttons = Frame(self)
        self.ctx_event = None  # save the event that has originated the context menu
        self.msg = tk.StringVar(value="Hello")
        self.err = tk.StringVar(value="-")
        self.create_menubar()
        self.init_components()

        self.closed = False

        # user input part of the gui, delegated to goban ATM. may become lists later
        self.mousein = self.goban
        self.keyin = self.goban

        # these commands are expected to be set from outside, in an attempt to inject dependency via setter.
        # See 'controller' classes who instantiate some of these commands.
        self.commands = {}
        self.master.protocol("WM_DELETE_WINDOW", lambda: self.execute("close"))
        self.commands["close"] = lambda: self.master.quit()  # this command needs a default value

        # delegate some work to goban
        self.stones_changed = self.goban.stones_changed
        self.highlight = self.goban.highlight
        self.select = self.goban.select
        self.clear = self.goban.clear
Exemplo n.º 10
0
 def __init__(self, master, ordinances=False, **kwargs):
     super(Options, self).__init__(master, **kwargs)
     self.ancestors = IntVar()
     self.ancestors.set(4)
     self.descendants = IntVar()
     self.spouses = IntVar()
     self.ordinances = IntVar()
     self.contributors = IntVar()
     self.start_indis = StartIndis(self)
     self.fid = StringVar()
     btn = Frame(self)
     entry_fid = EntryWithMenu(btn, textvariable=self.fid, width=16)
     entry_fid.bind('<Key>', self.enter)
     label_ancestors = Label(self, text=_('Number of generations to ascend'))
     entry_ancestors = EntryWithMenu(self, textvariable=self.ancestors, width=5)
     label_descendants = Label(self, text=_('Number of generations to descend'))
     entry_descendants = EntryWithMenu(self, textvariable=self.descendants, width=5)
     btn_add_indi = Button(btn, text=_('Add a FamilySearch ID'), command=self.add_indi)
     btn_spouses = Checkbutton(self, text='\t' + _('Add spouses and couples information'), variable=self.spouses)
     btn_ordinances = Checkbutton(self, text='\t' + _('Add Temple information'), variable=self.ordinances)
     btn_contributors = Checkbutton(self, text='\t' + _('Add list of contributors in notes'), variable=self.contributors)
     self.start_indis.grid(row=0, column=0, columnspan=3)
     entry_fid.grid(row=0, column=0, sticky='w')
     btn_add_indi.grid(row=0, column=1, sticky='w')
     btn.grid(row=1, column=0, columnspan=2, sticky='w')
     entry_ancestors.grid(row=2, column=0, sticky='w')
     label_ancestors.grid(row=2, column=1, sticky='w')
     entry_descendants.grid(row=3, column=0, sticky='w')
     label_descendants.grid(row=3, column=1, sticky='w')
     btn_spouses.grid(row=4, column=0, columnspan=2, sticky='w')
     if ordinances:
         btn_ordinances.grid(row=5, column=0, columnspan=3, sticky='w')
     btn_contributors.grid(row=6, column=0, columnspan=3, sticky='w')
     entry_ancestors.focus_set()
Exemplo n.º 11
0
	def __init__(self,parent):
		
		Frame.__init__(self, master=parent)

		canvas = tkinter.Canvas(self, highlightthickness=0)
		self.innerFrame = Frame(canvas)

		myscrollbar = Scrollbar(self, orient="vertical")
		myscrollbar.configure(command=canvas.yview)

		def scrollbarSet(top, bottom):
			# Hides and shows the scroll frame depending on need
			if float(top) > 0 or float(bottom) < 1:
				myscrollbar.grid(row=0, column=1, sticky="NS")
			else:
				pass
				myscrollbar.grid_remove()
			myscrollbar.set(top, bottom)
		canvas.configure(yscrollcommand = scrollbarSet)


		configureFunc = lambda _ :  canvas.configure(scrollregion=canvas.bbox("all"))
		frameID = canvas.create_window((0,0), window=self.innerFrame, anchor='nw')
		self.innerFrame.bind("<Configure>",configureFunc)

		canvas.grid(row=0, column=0, sticky="NSEW")
		myscrollbar.grid(row=0, column=1, sticky="NS")
		self.grid_rowconfigure(0, weight=1)
		self.grid_columnconfigure(0, weight=0)


		#canvas.bind("<Configure>", lambda e : canvas.itemconfig(frameID, width=e.width))
		canvas.bind("<Configure>", lambda e : canvas.configure(width=self.innerFrame.winfo_width()))
Exemplo n.º 12
0
def _replace_dialog(parent):  # htest #
    from tkinter import Toplevel, Text, END, SEL
    from tkinter.ttk import Frame, Button

    top = Toplevel(parent)
    top.title("Test ReplaceDialog")
    x, y = map(int, parent.geometry().split('+')[1:])
    top.geometry("+%d+%d" % (x, y + 175))

    # mock undo delegator methods
    def undo_block_start():
        pass

    def undo_block_stop():
        pass

    frame = Frame(top)
    frame.pack()
    text = Text(frame, inactiveselectbackground='gray')
    text.undo_block_start = undo_block_start
    text.undo_block_stop = undo_block_stop
    text.pack()
    text.insert("insert","This is a sample sTring\nPlus MORE.")
    text.focus_set()

    def show_replace():
        text.tag_add(SEL, "1.0", END)
        replace(text)
        text.tag_remove(SEL, "1.0", END)

    button = Button(frame, text="Replace", command=show_replace)
    button.pack()
Exemplo n.º 13
0
 def __init__(self, master):
     Frame.__init__(self, master, padding="0 0 0 13")
     Separator(self).grid(row=0, columnspan=2, pady="0 9", sticky=EW)
     self.button = Button(self, text="Close", command=master.destroy)
     self.button.grid(row=1, column=0, padx="15", sticky=E)
     self.grid(sticky=EW)
     self.columnconfigure(0, weight=1)
Exemplo n.º 14
0
    def initialize(self):
        self.top = Frame(self.canvas)
        self.top.grid(row=0,column=0, columnspan=3, padx=5, pady=10)

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

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


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


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


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

        self.startBtn = Button(self.canvas, text="Start", command=self.start)
        self.startBtn.grid(row=2, column=2, pady=10)
        self.startBtn = Button(self.canvas, text="Reset", command=self.reset)
        self.startBtn.grid(row=2, column=3, pady=10)
Exemplo n.º 15
0
    def __init__(self, parent):
        self.Data = Data()
        self.getReciepList()

        Frame.__init__(self, parent)

        self.parent = parent

        self.recipeList = None  # Listbox
        self.recipeName = None  # Entry
        self.prepTime = None  # Entry
        self.prepTimeUnit = None  # OptionMenu
        self.cookTime = None  # Entry
        self.cookTimeUnit = None  # OptionMenu
        self.ingredientName = None  # Entry
        self.ingredientQuantity = None  # Entry
        self.ingredientUnit = None  # OptionMenu
        self.ingredientList = None  # Listbox
        self.procedure = None  # Text

        self.recipes = []
        self.ingredients = []
        self.activeRecipeID = {"lst": None, "db": None}  # (listID, dbID)
        self.activeIngredientID = {"lst": None, "db": None}  # (listID, dbID)

        self.initUI()

        self.bind_all("<Control-w>", self.onExit)
        self.bind_all("<Control-s>", self.recipeSave)
Exemplo n.º 16
0
 def ok_cancel_buttons(self):
     button_frame = Frame(self.frame)
     ok_button = Button(button_frame, text="Ok", command=self.save)
     cancel_button = Button(button_frame, text="Cancel", command=self.destroy)
     button_frame.pack(fill="x")
     cancel_button.pack(side="right", padx=5, pady=5)
     ok_button.pack(side="right")
Exemplo n.º 17
0
    def __init__(self, master):
        """Construct a Box frame with parent master.

        Args:
            master: The parent frame.
        """
        Frame.__init__(self, master, style=styles.BOX_FRAME)
        self.position = (0, 0)
        self.binding_tag = 'BoxFrame' + str(Box._counter)
        self.number_text = StringVar(self, '')
        Box._counter += 1

        self.borders = dict()
        for edge in 'nesw':
            self.borders[edge] = Border(self, edge)

        self.inner_frame = Frame(self, width=30, height=30, style=styles.BOX_FRAME)
        self.pencil_marks = _build_3x3_grid(self.inner_frame, Pencil)

        self.label = Label(self.inner_frame, textvariable=self.number_text, style=styles.NUMBER_LABEL)

        _tag_widget(self, self.binding_tag)
        _tag_widget(self.inner_frame, self.binding_tag)
        _tag_widget(self.label, self.binding_tag)
        for mark in self.pencil_marks:
            _tag_widget(mark, self.binding_tag)
            _tag_widget(mark.label, self.binding_tag)
Exemplo n.º 18
0
  def initialize_ui(self):
    default_padding = {'padx': 10, 'pady' : 10}

    customer_frame = Frame(self)
    self.customer_id_label = Label(customer_frame, text = "Customer id:", style="BW.TLabel")
    self.customer_id_label.pack(default_padding, side = LEFT)

    self.customer_id_value = Label(customer_frame,style="BW.TLabel")
    self.customer_id_value["textvariable"] = self.controller.customer_id
    self.customer_id_value.pack(default_padding, side = LEFT)

    customer_frame.pack(expand = True, fill = "x")

    self.take_picture_frame = Frame(self, border = 10)
    
    self.picture_mode = IntVar()
    Radiobutton(self.take_picture_frame, text = "Light", variable = self.picture_mode, value = 1).pack(side = LEFT)
    Radiobutton(self.take_picture_frame, text = "Dark", variable = self.picture_mode, value = 2).pack(side = LEFT)
    
    self.button_take_picture = Button(self.take_picture_frame, text = "Take picture", command = self.take_picture)
    self.button_take_picture.pack(expand = True, fill = "x", side = BOTTOM)

    self.take_picture_frame.pack(expand = True)
    
    self.button_update = Button(self, text = "Update", command = self.controller.run_update_script)
    self.button_update.pack(expand = True, fill = "x")
Exemplo n.º 19
0
    def __init__(self):
        super().__init__()
        self.title('Treepace Tree Transformation GUI Demo')
        self.geometry('640x400')
        self.resizable(False, False)
        self.tree_frame = Frame()
        self.tree_button = Button(self.tree_frame, text="Load tree",
                                  command=self.load)
        self.tree_button.pack(expand=True, fill=BOTH)
        self.tree_text = Text(self.tree_frame, width=20)
        self.tree_text.pack(expand=True, fill=BOTH)
        self.tree_text.insert('1.0', DEFAULT_TREE)
        self.tree_frame.pack(side=LEFT, expand=True, fill=BOTH)
        
        self.program_frame = Frame()
        self.program_button = Button(self.program_frame, text="Transform",
                                     command=self.transform)
        self.program_button.pack(expand=True, fill=BOTH)
        self.program_text = Text(self.program_frame, width=60, height=8)
        self.program_text.pack(expand=True, fill=BOTH)
        self.program_text.insert('1.0', DEFAULT_PROGRAM)
        self.tv = Treeview(self.program_frame)
        self.tv.pack(expand=True, fill=BOTH)
        self.program_frame.pack(side=LEFT, expand=True, fill=BOTH)

        GuiNode.tv = self.tv
        self.load()
Exemplo n.º 20
0
    def __init__(self, parent, i, j, callback_edit, **options):
        Frame.__init__(self, parent, **options)
        # grid layout
        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        # styles
        self.configure(style="case.TFrame")

        self.i = i
        self.j = j
        self.modifiable = True
        self.val = 0 # valeur de la case, 0 = vide
        self.possibilites = [] # possibilites écrites dans la case
        self.callback_edit = callback_edit

        # labels
        self.chiffres = [] # tableau 3x3 de labels permettant d'afficher les chiffres dans la case
        sticky_i = ["n", "ns", "s"]
        sticky_j = ["w", "ew", "e"]
        for i in range(3):
            self.chiffres.append([])
            for j in range(3):
                self.chiffres[i].append(Label(self, text=" ", anchor="center",
                                                  style="case.TLabel", width=1))
                self.chiffres[i][j].grid(row=i, column=j,
                                         sticky=sticky_i[i % 3] + sticky_j[j % 3],
                                         padx=1, pady=1)
Exemplo n.º 21
0
 def __init__(self, parent, title, imageFile, body):
     super(DialogAbout, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.transient(self.parent)
     self.title(title)
     
     frame = Frame(self)
     image = PhotoImage(file=imageFile)
     aboutImage = Label(frame, image=image)
     aboutBody = Label(frame, text=body, wraplength=500)
     okButton = Button(frame, text=_("OK"), command=self.ok)
     okButton.focus_set()
     aboutImage.grid(row=0, column=0, sticky=NW, pady=20, padx=16)
     aboutBody.grid(row=0, column=1, columnspan=2, sticky=EW, pady=3, padx=0)
     okButton.grid(row=1, column=2, sticky=EW, pady=3)
     
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+200,dialogY+200))
     
     self.bind("<Alt-u>", lambda *ignore: okButton.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Exemplo n.º 22
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)
Exemplo n.º 23
0
    def __init__(self, mainWin, options):
        self.mainWin = mainWin
        parent = mainWin.parent
        super(DialogNewFactItemOptions, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("New Fact Item Options"))
        
        frame = Frame(self)

        label(frame, 1, 1, "Entity scheme:")
        self.cellEntityIdentScheme = gridCell(frame, 2, 1, getattr(options,"entityIdentScheme",""), width=50)
        ToolTip(self.cellEntityIdentScheme, text=_("Enter the scheme for the context entity identifier"), wraplength=240)
        label(frame, 1, 2, "Entity identifier:")
        self.cellEntityIdentValue = gridCell(frame, 2, 2, getattr(options,"entityIdentValue",""))
        ToolTip(self.cellEntityIdentValue, text=_("Enter the entity identifier value (e.g., stock ticker)"), wraplength=240)
        label(frame, 1, 3, "Start date:")
        startDate = getattr(options,"startDate",None)
        self.cellStartDate = gridCell(frame, 2, 3, XmlUtil.dateunionValue(startDate) if startDate else "")
        ToolTip(self.cellStartDate, text=_("Enter the start date for the report period (e.g., 2010-01-01)"), wraplength=240)
        label(frame, 1, 4, "End date:")
        endDate = getattr(options,"endDate",None)
        self.cellEndDate = gridCell(frame, 2, 4, XmlUtil.dateunionValue(endDate, subtractOneDay=True) if endDate else "")
        ToolTip(self.cellEndDate, text=_("Enter the end date for the report period (e.g., 2010-12-31)"), wraplength=240)
        label(frame, 1, 5, "Monetary unit:")
        self.cellMonetaryUnit = gridCombobox(frame, 2, 5, getattr(options,"monetaryUnit",""), values=monetaryUnits)
        ToolTip(self.cellMonetaryUnit, text=_("Select a monetary unit (e.g., EUR)"), wraplength=240)
        label(frame, 1, 6, "Monetary decimals:")
        self.cellMonetaryDecimals = gridCell(frame, 2, 6, getattr(options,"monetaryDecimals","2"))
        ToolTip(self.cellMonetaryDecimals, text=_("Enter decimals for monetary items"), wraplength=240)
        label(frame, 1, 7, "Non-monetary decimals:")
        self.cellNonMonetaryDecimals = gridCell(frame, 2, 7, getattr(options,"nonMonetaryDecimals","0"))
        ToolTip(self.cellNonMonetaryDecimals, text=_("Enter decimals for non-monetary items (e.g., stock shares)"), wraplength=240)

        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 24
0
 def __init__(self, lnp, parent):
     #pylint:disable=super-init-not-called
     Frame.__init__(self, parent)
     self.pack(side=TOP, fill=BOTH, expand=Y)
     self.lnp = lnp
     self.create_variables()
     self.create_controls()
     self.read_data()
Exemplo n.º 25
0
 def __init__(self,parent):
     Frame.__init__(self , parent)
     self.enc1 = Encoder(21)
     self.parent = parent
     self.conexion = True#is_connected()
     self.est_pinza = 1
     self.est_subebaja = 1
     self.initUI()
Exemplo n.º 26
0
 def __init__(self, master, train_dir):
     Frame.__init__(self, master)
     self.dir = train_dir
     self.manager = NNManager()
     self.img_list = ImgList(self)
     self.img_list.pack()
     Button(self, text='Histo', command=self.histo).pack()
     Button(self, text='Train', command=self.train).pack()
Exemplo n.º 27
0
 def insert_entry_field(self, txt):
     frame = Frame(self.frame)
     frame.pack(fill="x")
     label = Label(frame, text=txt, width=6)
     label.pack(side="left", anchor="n", padx=5, pady=5)
     entry = Entry(frame)
     entry.pack(fill="x", padx=5, pady=5, expand=True)
     self.entries["Entry"][txt] = entry
Exemplo n.º 28
0
 def __init__(self, parent):
     Frame.__init__(self, parent)
     self.parent = parent
     self.info = {}
     self.window = None
     self.size = (640, 480)
     self.fields = []
     self.init_ui()
Exemplo n.º 29
0
 def __init__(self, parent, *args, **kwargs):
     #pylint:disable=super-init-not-called
     Frame.__init__(self, parent, *args, **kwargs)
     self.parent = parent
     self.pack(side=TOP, fill=BOTH, expand=Y)
     self.create_variables()
     self.create_controls()
     self.read_data()
Exemplo n.º 30
0
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

        self.db = dao('blist') #데이터베이스 관리 클래스 생성
Exemplo n.º 31
0
    vcmd = lf0.register(is_okay)

    entsv = StringVar()
    ent0 = Entry(lf0,
                 validate='key',
                 textvariable=entsv,
                 validatecommand=(vcmd, '%P', '%S', '%i'))
    ent0.bind("<Return>", end_input)
    ent0.grid(row=1, column=0, padx=10)
    ent0.focus()

    mee_lbl = Label(lf0, text=mess_text, style='brown.TLabel')
    mee_lbl.grid(row=2, column=0, pady=10, padx=10)


if __name__ == "__main__":
    root = Tk()
    fra0 = Frame(root)
    fra0.grid()
    LFTEXT = 'Beer Type'
    out_var1 = StringVar()
    MESSTEXT = 'Start with capital letter, use at least 6 characters '\
            '<Return> to confirm'
    entry_string(fra0, LFTEXT, MESSTEXT, out_var1)
    b2 = Button(root,
                text='Click after selection',
                command=lambda: print(out_var1.get()))
    b2.grid(row=2, column=0)
    root.mainloop()
Exemplo n.º 32
0
    def __init__(self):

        super().__init__()
        #self contador numero tab querys

        serverimage = tk.PhotoImage(file="images/server.png")

        #Creacion de ventana
        self.master.title("TytusDB")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(1, weight=1)

        self.lbl = Label(self, text="TytusDB")
        self.lbl.grid(sticky=W, pady=4, padx=5)

        self.nb = CustomNotebook(self)
        self.nb.fm = Frame(self.nb)
        self.nb.fm.pack(fill=BOTH, expand=True)
        self.nb.fm.columnconfigure(1, weight=1)
        self.nb.fm.columnconfigure(3, pad=7)
        self.nb.fm.rowconfigure(3, weight=1)
        self.nb.fm.rowconfigure(5, pad=7)
        self.nb.add(self.nb.fm, text='Query ' + str(self.contadorQuerysTabs))
        self.nb.grid(row=1,
                     column=1,
                     columnspan=2,
                     rowspan=1,
                     padx=5,
                     sticky=E + W + S + N)
        self.nb.fm.area = Text(self.nb.fm, height=30)
        self.nb.fm.area.grid(row=1,
                             column=1,
                             columnspan=2,
                             rowspan=2,
                             padx=5,
                             sticky=E + W + S + N)

        self.lbl2 = Label(self, text="Consola")
        self.lbl2.grid(row=2, column=1)
        #Textbox de la consola, aqui se debe mostrar la data que devuelve el proyecto de compi
        self.areaConsole = Text(self, height=10, state='disabled')
        self.areaConsole.grid(row=3, column=1, padx=5, sticky=E + W)

        # *************************** BARRA DE MENÚ ***************************
        menubar = Menu(self.master)
        self.master.filemenu = Menu(menubar, tearoff=0)
        self.master.filemenu.add_command(label="Nuevo")
        self.master.filemenu.add_command(label="Abrir", command=self.openFile)
        self.master.filemenu.add_command(label="Guardar",
                                         command=self.saveFile)
        self.master.filemenu.add_command(label="Salir",
                                         command=self.master.quit)
        self.master.helpmenu = Menu(menubar, tearoff=0)
        self.master.helpmenu.add_command(label="Documentación")
        self.master.helpmenu.add_command(label="Acerca de...")
        self.master.servermenu = Menu(menubar, tearoff=0)
        self.master.servermenu.add_command(label="Nueva conexión")
        self.master.servermenu.add_command(label="Quitar conexión")
        self.master.herramientasMenu = Menu(menubar, tearoff=0)
        self.master.herramientasMenu.add_command(label="Query Tool",
                                                 command=self.addQueryTool)
        self.master.herramientasMenu.add_command(label="run", command=self.run)
        menubar.add_cascade(label="Archivo", menu=self.master.filemenu)
        menubar.add_cascade(label="Servidor", menu=self.master.servermenu)
        menubar.add_cascade(label="Herramientas",
                            menu=self.master.herramientasMenu)
        menubar.add_cascade(label="Ayuda", menu=self.master.helpmenu)
        self.master.config(menu=menubar)
        # *********************************************************************

        # ******************************* ÁRBOL *******************************
        self.treeview = Treeview(self)
        self.treeview.grid(row=1,
                           column=0,
                           columnspan=1,
                           rowspan=4,
                           padx=5,
                           sticky=E + W + S + N)
        self.serverimage = tk.PhotoImage(file="images/server.png")
        self.databaseimage = tk.PhotoImage(file="images/database.png")
        self.tableimage = tk.PhotoImage(file="images/table.png")
        self.functionimage = tk.PhotoImage(file="images/function.png")
        self.usersimage = tk.PhotoImage(file="images/users.png")
        self.singleuserimage = tk.PhotoImage(file="images/single_user.png")
        self.viewimage = tk.PhotoImage(file="images/view.png")
        self.triggerimage = tk.PhotoImage(file="images/trigger.png")
        servers = self.treeview.insert("",
                                       tk.END,
                                       text=" Servidores",
                                       image=self.serverimage)
        srvr1 = self.treeview.insert(servers,
                                     tk.END,
                                     text=" server_vd2020",
                                     image=self.serverimage)
        dbs = self.treeview.insert(srvr1,
                                   tk.END,
                                   text=" Databases",
                                   image=self.databaseimage)
        dvdrental = self.treeview.insert(dbs,
                                         tk.END,
                                         text=" dvdrental",
                                         image=self.databaseimage)
        funcdvdrental = self.treeview.insert(dvdrental,
                                             tk.END,
                                             text=" Functions",
                                             image=self.functionimage)
        tabldvdrental = self.treeview.insert(dvdrental,
                                             tk.END,
                                             text=" Tables",
                                             image=self.tableimage)
        triggersdvdrental = self.treeview.insert(dvdrental,
                                                 tk.END,
                                                 text="Trigger Functions",
                                                 image=self.triggerimage)
        viewsdvdrental = self.treeview.insert(dvdrental,
                                              tk.END,
                                              text=" Views",
                                              image=self.viewimage)
        sports = self.treeview.insert(dbs,
                                      tk.END,
                                      text=" sports",
                                      image=self.databaseimage)
        funcsports = self.treeview.insert(sports,
                                          tk.END,
                                          text=" Functions",
                                          image=self.functionimage)
        tablsport = self.treeview.insert(sports,
                                         tk.END,
                                         text="Tables",
                                         image=self.tableimage)
        triggersport = self.treeview.insert(sports,
                                            tk.END,
                                            text=" Trigger Functions",
                                            image=self.triggerimage)
        viewsport = self.treeview.insert(sports,
                                         tk.END,
                                         text=" Views",
                                         image=self.viewimage)
        logingrp = self.treeview.insert(srvr1,
                                        tk.END,
                                        text=" Login/Group Roles",
                                        image=self.usersimage)
        usr1 = self.treeview.insert(logingrp,
                                    tk.END,
                                    text=" user1",
                                    image=self.singleuserimage)
        usr2 = self.treeview.insert(logingrp,
                                    tk.END,
                                    text=" user2",
                                    image=self.singleuserimage)
        usr3 = self.treeview.insert(logingrp,
                                    tk.END,
                                    text=" user3",
                                    image=self.singleuserimage)
        usr4 = self.treeview.insert(logingrp,
                                    tk.END,
                                    text=" user4",
                                    image=self.singleuserimage)
Exemplo n.º 33
0
class MainWindow:
    def __init__(self) -> None:
        self.Root = Tk()
        self.App = Frame(self.Root, padding=(5, 2))
        self.UpdatesFrame = LabelFrame(self.App, text='Обновление',
                                       borderwidth=2, relief='sunken', padding=(5, 2))
        self.upd_enabled = BooleanVar()  # Флаг обновлений
        self.upd_unit = StringVar()  # Единица измерения времени
        self.time_units = {Minutes: 'Минут', Hours: 'Часов',
                           Days: 'Дней', Weeks: 'Недель', Months: 'Месяцев'}
        self.size_units = {Bytes: 'Байт', KBytes: 'Кбайт', MBytes:'Мбайт',
                           GBytes:'Гбайт', TBytes:'Тбайт'}  # Список единиц измерения времени
        self.maxfsize = StringVar()  # Максимальный размер файла
        self.size_unit = StringVar()  # Единица измерения информации
        self.units_amount1 = StringVar()  # Количество единиц
        self.quar = BooleanVar()  # False - удалять, True - карантин
        self.quar_path = StringVar() # Расположение карантина
        self.rpt_enabled = BooleanVar()  # Флаг отправки отчета
        self.email = StringVar()  # Адрес отправки
        self.passwd = StringVar() # Пароль исходящего ящика
        self.rpt_unit = StringVar()  # Единица измерения времени
        self.units_amount2 = StringVar()  # Количество единиц

        self.Upd_Label1 = Label(self.UpdatesFrame, text='Проверять обновления антивирусных баз')
        self.Upd_Checkbutton1 = Checkbutton(self.UpdatesFrame, variable=self.upd_enabled)
        self.Upd_Label2 = Label(self.UpdatesFrame, text='Частота проверки:   каждые')
        self.Upd_Spinbox1 = Spinbox(self.UpdatesFrame, textvariable=self.units_amount1,
                                    from_=1, to=999999999, width=4)
        self.Upd_OptionMenu1 = OptionMenu(self.UpdatesFrame, self.upd_unit, *self.time_units.values())
        self.Upd_Button1 = Button(
            self.UpdatesFrame, text='Источники антивирусных сигнатур', command=EntryOptionsWindow('AV_SOURCES', self.Root).main)

        self.ScanFrame = LabelFrame(self.App, text='Сканирование',
                                    borderwidth=2, relief='sunken', padding=(5, 2))
        self.Scn_Label1 = Label(self.ScanFrame, text='Максимальный размер файла:')
        self.Scn_Spinbox1 = Spinbox(self.ScanFrame, textvariable=self.maxfsize,
                                    from_=0, to=999999999, width=8)

        self.Quar_Label = Label(self.ScanFrame, text='При обнаружении угрозы')
        self.Quar_RadButton1 = Radiobutton(self.ScanFrame, text='Удаление', variable=self.quar, value=False)
        self.Quar_RadButton2 = Radiobutton(self.ScanFrame, text='Карантин', variable=self.quar, value=True)

        self.Scn_OptionMenu1 = OptionMenu(self.ScanFrame, self.size_unit, *self.size_units.values())
        self.Scn_Edit_Targets = Button(self.ScanFrame, text='Цели сканирования', command=EntryOptionsWindow('SCAN_TARGETS', self.Root, select_path=True).main)
        self.Scn_Edit_Exceptions = Button(self.ScanFrame, text='Исключения', command=EntryOptionsWindow('SCAN_EXCLUDE', self.Root).main)
        self.Quar_Button1 = Button(self.ScanFrame, text='Расположение карантина',
                                   command=lambda: self.quar_path.set(filedialog.askdirectory()))

        self.ReportFrame = LabelFrame(self.App, text='Отправка отчета',
                                      borderwidth=2, relief='sunken', padding=(5, 2))

        self.Rpt_Label1 = Label(self.ReportFrame, text='Отправлять отчеты о сканировании')
        self.Rpt_Checkbutton1 = Checkbutton(self.ReportFrame, variable=self.rpt_enabled)
        self.Rpt_Label2 = Label(self.ReportFrame, text='Адрес отправки отчетов:')
        self.Rpt_Entry1 = Entry(self.ReportFrame, textvariable=self.email, width=32)
        self.Rpt_Label3 = Label(self.ReportFrame, text='Пароль:')
        self.Rpt_Entry2 = Entry(self.ReportFrame, textvariable=self.passwd, width=32, show='*')
        self.Rpt_Label4 = Label(self.ReportFrame, text='Частота:')
        self.Rpt_Spinbox1 = Spinbox(self.ReportFrame, textvariable=self.units_amount2,
                                    from_=1, to=999999999, width=4)
        self.Rpt_OptionMenu1 = OptionMenu(self.ReportFrame, self.rpt_unit, *self.time_units.values())
        self.Rpt_Button1 = Button(self.ReportFrame, text='Получатели', command=EntryOptionsWindow('SEND_TO', self.Root).main)

        self.Buttons = Frame(self.App, padding=(5, 2))
        self.Button1 = Button(self.Buttons, text='Готово', command=self.save_conf)
        self.Button2 = Button(self.Buttons, text='Отмена', command=self.Root.destroy)

    def main(self) -> None:
        self.upd_unit.set(self.time_units[type(UPDATE_FREQ)])
        self.units_amount1.set(UPDATE_FREQ.value)
        self.upd_enabled.set(CHECK_FOR_UPDATES)
        self.Upd_Checkbutton1.configure(command=(
            lambda: self.__change_state(
                self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1, self.Upd_Button1)
            and self.upd_enabled.set(not self.upd_enabled.get())))
        self.Rpt_Checkbutton1.configure(command=(
            lambda: self.__change_state(
                self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2,
                 self.Rpt_Label4, self. Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1)
                 and self.rpt_enabled.set(not self.rpt_enabled.get())))
        self.maxfsize.set(MAX_FILE_SIZE.value)
        self.size_unit.set(self.size_units[type(MAX_FILE_SIZE)])
        self.quar.set(REMOVE_THREATS)
        self.quar_path.set(QUARANTINE_PATH)
        self.rpt_enabled.set(SEND_SCAN_REPORTS)
        self.email.set(SEND_FROM)
        self.passwd.set(SEND_PASSWD)
        self.rpt_unit.set(self.time_units[type(SEND_FREQ)])
        self.units_amount2.set(SEND_FREQ.value)

        self.App.pack(fill='both', expand=True)
        center_win(self.Root, '500x500')
        self.Root.resizable(False, False)
        self.Root.title('CobraAV Configuration')

        self.UpdatesFrame.place(y=0, height=150, width=490)
        self.__change_state(self.upd_enabled, self.Upd_Label2,
                            self.Upd_Spinbox1, self.Upd_OptionMenu1)

        self.__change_state(self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3,
                            self.Rpt_Entry2, self.Rpt_Label4, self.Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1)

        self.Upd_Label1.place(relx=.01, rely=.05)  # Проверять обновления ?
        self.Upd_Checkbutton1.place(relx=.8, rely=.05)  # Да/Нет

        self.Upd_Label2.place(relx=.01, rely=.3)  # Частота проверки
        self.Upd_Spinbox1.place(relx=.55, rely=.3, width=60)  # Количество
        self.Upd_OptionMenu1.place(relx=.72, rely=.28)  # Единицы измерения
        self.Upd_Button1.place(relx=.01, rely=.65)  # Источники сигнатур

        self.ScanFrame.place(y=150, height=150, width=490)

        self.Scn_Label1.place(relx=.01, rely=.05)  # Максимальный размер файла
        self.Scn_Spinbox1.place(relx=.55, rely=.05, width=60)  # Количество

        self.Quar_Label.place(relx=.01, rely=.35)
        self.Quar_RadButton1.place(relx=.52, rely=.35)  # Переключатель на удаление угрозы
        self.Quar_RadButton2.place(relx=.72, rely=.35)  # Переключатель на добавление вкарантина угрозы
        self.Quar_Button1.place(relx=.56, rely=.65)  # Расположение карантина

        self.Scn_OptionMenu1.place(relx=.72, rely=.014)  # Единицы измерения
        self.Scn_Edit_Targets.place(relx=.01, rely=.65)  # Цели сканирования
        self.Scn_Edit_Exceptions.place(relx=.33, rely=.65)  # Исключения

        self.Rpt_Label1.place(relx=.01, rely=.05)  # Отправлять отчеты ?
        self.Rpt_Checkbutton1.place(relx=.8, rely=.05)  # Да/Нет

        self.ReportFrame.place(y=300, height=150, width=490)
        self.Rpt_Label2.place(relx=.01, rely=.35)  # Адрес отправки отчетов:
        self.Rpt_Entry1.place(relx=.35, rely=.35)  # Ввод адреса отправки отчетов
        self.Rpt_Label3.place(relx=.01, rely=.50) # Пароль:
        self.Rpt_Entry2.place(relx=.35, rely=.50) # Ввод пароля:
        self.Rpt_Label4.place(relx=.01, rely=.75)  # Частота отправки
        self.Rpt_Spinbox1.place(relx=.35, rely=.75, width=60)  # Количество
        self.Rpt_OptionMenu1.place(relx=.52, rely=.72)  # Единицы измерения
        self.Rpt_Button1.place(relx=.72, rely=.74) # Получатели

        self.Buttons.place(y=450, height=50, width=490)
        self.Button1.place(relx=.62, rely=.2) # Кнопка "Готово"
        self.Button2.place(relx=.82, rely=.2) # Кнопка "Отмена"

        self.Root.mainloop()

    @staticmethod
    def __change_state(state: BooleanVar, *args: Widget) -> None:
        for i in args:
            i.configure(state=('disabled', 'normal')[state.get()])

    def save_conf(self) -> None:
        size_units = {v: k for k, v in self.size_units.items()}
        time_units = {v: k for k, v in self.time_units.items()}

        def wrap_list(a: 'list[str]') -> str:
            return '[' + ', '.join(f"r'{i}'" for i in a) + ']'

        def wrap_cls(_unit: Variable, amount: Variable) -> str:
            unit = _unit.get()
            if unit in size_units:
                return size_units[unit].__name__ + f'({amount.get()})'
            elif unit in time_units:
                return time_units[unit].__name__ + f'({amount.get()})'
            else:
                raise NotImplementedError

        with open(CONF_PATH, 'w') as f:
            f.write(
                f"""from libunits import *

CHECK_FOR_UPDATES = {int(self.upd_enabled.get())}  # Check for updates
UPDATE_FREQ = {wrap_cls(self.upd_unit, self.units_amount1)}  # Check interval
MAX_FILE_SIZE = {wrap_cls(self.size_unit, self.maxfsize)}  # Max file size

# Antivirus database sources
AV_SOURCES = {wrap_list(AV_SOURCES)}

# Antivirus database path
DB_PATH = r'{DB_PATH}'

# On threat:
# 0 - quarantine
# 1 - remove
REMOVE_THREATS = {int(self.quar.get())}

# Directories to scan
SCAN_TARGETS = {wrap_list(SCAN_TARGETS)}

# Exclude from scanning
SCAN_EXCLUDE = {wrap_list(SCAN_EXCLUDE)}

# quarantine location
QUARANTINE_PATH = r'{self.quar_path.get() or QUARANTINE_PATH}'

# Send scan reports
SEND_SCAN_REPORTS = {int(self.rpt_enabled.get())}

# Scan reports frequency
SEND_FREQ = {wrap_cls(self.rpt_unit, self.units_amount2)}

# Send from this email
SEND_FROM = r'{self.email.get()}'

# Sender email password
SEND_PASSWD = r'{self.passwd.get()}'

# Send to these emails
SEND_TO = {wrap_list(SEND_TO)}
""")
        self.Root.destroy()
Exemplo n.º 34
0
    def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False, multiselect=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent # parent is cntlrWinMain
        else: # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.treeView.config(selectmode="extended" if multiselect else "browse")
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        self.multiselect = multiselect
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(cntlr, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                
                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    self.packageContainedIXDSes = defaultdict(list)
                    packageContentInstanceCounts = {}
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html", ".xbrl"): # try for suffixes in order of likelihood to have instance
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(suffix):
                                m = reportIxdsPattern.match(potentialInstance) # IXDS
                                if multiselect and m: # only in ixds multiselect mode
                                    _type = "Inline Doc Set"
                                    self.packageContainedIXDSes[m.group(1)].append(potentialInstance)
                                    potentialInstance = m.group(1) # use package name only
                                elif suffix == ".xbrl":
                                    _type = "xBRL-XML Instance"
                                else:
                                    _type = "Inline Instance"
                                if not self.packageContainedInstances or self.packageContainedInstances[-1][0] != potentialInstance:
                                    self.packageContainedInstances.append([potentialInstance, _type])
                                    packageContentInstanceCounts[potentialInstance] = packageContentInstanceCounts.get(potentialInstance, 0) + 1
                                    packageContentTypeCounts[_type] = packageContentTypeCounts.get(_type, 0) + 1
                        if self.packageContainedInstances:
                            break 
                    if self.packageContainedInstances: # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][1] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][1] = "{} {}".format(_type, _dupNo)
                        for _instance, count in packageContentInstanceCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][0] == _instance:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][0] = "{} {}".format(_instance, _dupNo)
                                    
                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return
    
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)
        
        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        
        self.wait_window(self)
Exemplo n.º 35
0
'''
Radio Buttons

Create theme extract for custom widgets, include state selection to view
the result of changing the state using different images and/or different
settings.

'''

from tkinter import Tk, PhotoImage
from tkinter.ttk import Style, Label, Radiobutton, Frame
from RunState import run_state

root = Tk()

fr = Frame(root)
fr.grid(column=0, row=0, sticky='nsew')

img1 = PhotoImage("radio", file='../images/piratz/radio.png')
img2 = PhotoImage("radio-s", file='../images/piratz/radio-s.png')

style = Style()
# both theme_create and theme_settings worked
style.theme_create(
    "yummy",
    parent="clam",
    settings={
        #style.theme_settings('default', {
        # start of theme extract
        'Radiobutton.indicator': {
            "element create": ('image', "radio", ('selected', "radio-s"), {
Exemplo n.º 36
0
class EuchreApp(Tk):
    def __init__(self, title, controller, user_player):
        self.user_player = user_player
        Tk.__init__(self)
        self.title(title)
        self.centerWindow()

        self.w = Frame(self)
        self.w.pack(fill=BOTH, expand=1)
        for x in range(15):
            self.w.columnconfigure(x, weight=1)
        self.w.rowconfigure(3, weight=1)
        self.w.rowconfigure(6, weight=1)
        self.w.rowconfigure(7, weight=1)
        self.w.rowconfigure(8, weight=1)
        self.w.rowconfigure(11, weight=1)

        self.lblTitle = Label(self.w, text="Euchre")
        self.lblTitle.grid(row=0, column=5, columnspan=5)

        # Center Table
        self.btnDeck = Button(self.w, text="Deck", state="disabled")
        self.btnDeck.grid(row=4, column=5, rowspan=5, columnspan=2, sticky=N+S+E+W)
        self.lblTrump = Label(self.w, text="Trump: ")
        self.lblTrump.grid(row=4, column=7, columnspan=3)
        self.lblCurrentPlayer = Label(self.w, text="Current Player: ")
        self.lblCurrentPlayer.grid(row=5, column=7, columnspan=3)
        self.btnP1CardPlayed = Button(self.w, state="disabled")
        self.btnP1CardPlayed.grid(row=8, column=8, sticky=N+S+E+W)
        self.btnP2CardPlayed = Button(self.w, state="disabled")
        self.btnP2CardPlayed.grid(row=7, column=7, sticky=N+S+E+W)
        self.btnP3CardPlayed = Button(self.w, state="disabled")
        self.btnP3CardPlayed.grid(row=6, column=8, sticky=N+S+E+W)
        self.btnP4CardPlayed = Button(self.w, state="disabled")
        self.btnP4CardPlayed.grid(row=7, column=9, sticky=N+S+E+W)
        self.btnNewHand = Button(self.w, text="New Hand", command=lambda: controller.restart_trick())
        self.btnNewHand.grid(row=7, column=8, sticky=N+S+E+W)
        self.btnDeal = Button(self.w, text="Deal", command=lambda:controller.deal())
        self.btnDeal.grid(row=4, column=7, rowspan=5, columnspan=3, sticky=N+S+E+W)

        def player_choose_card_callback_factory(player, card):
            return lambda: controller.player_choose_card(player, card)

        # Player 1 hand
        self.lblPlayer1Title = Label(self.w, text=("You" if user_player else "Player 1"))
        self.lblPlayer1Title.grid(row=9, column=5, columnspan=5)
        self.lblPlayer1Points = Label(self.w, text=("Points: 0"))
        self.lblPlayer1Points.grid(row=10, column=5, columnspan=5)
        self.btnPlayer1Cards = []
        for i in range(5):
            self.btnPlayer1Cards.append(Button(self.w, command=player_choose_card_callback_factory(0, i), state="disabled"))
            self.btnPlayer1Cards[i].grid(row=11, column=5+i, sticky=N+S+E+W)

        # Player 2 hand
        self.lblPlayer2Title = Label(self.w, text="Player 2")
        self.lblPlayer2Title.grid(row=4, column=0, columnspan=5)
        self.lblPlayer2Points = Label(self.w, text="Points: 0")
        self.lblPlayer2Points.grid(row=5, column=0, columnspan=5)
        self.btnPlayer2Cards = []
        for i in range(5):
            self.btnPlayer2Cards.append(Button(self.w, command=player_choose_card_callback_factory(1, i), state="disabled"))
            self.btnPlayer2Cards[i].grid(row=6, column=0+i, rowspan=3, sticky=N+S+E+W)

        # Player 3 hand
        self.lblPlayer3Title = Label(self.w, text="Player 3")
        self.lblPlayer3Title.grid(row=1, column=5, columnspan=5)
        self.lblPlayer3Points = Label(self.w, text="Points: 0")
        self.lblPlayer3Points.grid(row=2, column=5, columnspan=5)
        self.btnPlayer3Cards = []
        for i in range(5):
            self.btnPlayer3Cards.append(Button(self.w, command=player_choose_card_callback_factory(2, i), state="disabled"))
            self.btnPlayer3Cards[i].grid(row=3, column=5+i, sticky=N+S+E+W)

        # Player 4 hand
        self.lblPlayer4Title = Label(self.w, text="Player 4")
        self.lblPlayer4Title.grid(row=4, column=10, columnspan=5)
        self.lblPlayer4Points = Label(self.w, text="Points: 0")
        self.lblPlayer4Points.grid(row=5, column=10, columnspan=5)
        self.btnPlayer4Cards = []
        for i in range(5):
            self.btnPlayer4Cards.append(Button(self.w, command=player_choose_card_callback_factory(3, i), state="disabled"))
            self.btnPlayer4Cards[i].grid(row=6, column=10+i, rowspan=3, sticky=N+S+E+W)

    def centerWindow(self):
        w = 1000
        h = 600

        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()

        x = (sw - w)/2
        y = (sh - h)/2
        self.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def restart_trick(self, dealer):
        self.btnNewHand.grid_remove()
        self.btnDeal.grid()
        self.lblPlayer1Title.config(text=("You" if self.user_player else "Player 1") + (": dealer" if dealer % 4 == 0 else ""))
        self.lblPlayer2Title.config(text="Player 2" + (": dealer" if dealer % 4 == 1 else ""))
        self.lblPlayer3Title.config(text="Player 3" + (": dealer" if dealer % 4 == 2 else ""))
        self.lblPlayer4Title.config(text="Player 4" + (": dealer" if dealer % 4 == 3 else ""))
        self.lblPlayer1Points.config(text="Points: 0")
        self.lblPlayer2Points.config(text="Points: 0")
        self.lblPlayer3Points.config(text="Points: 0")
        self.lblPlayer4Points.config(text="Points: 0")
        for c in self.btnPlayer1Cards:
            c.config(text="")
        for c in self.btnPlayer2Cards:
            c.config(text="")
        for c in self.btnPlayer3Cards:
            c.config(text="")
        for c in self.btnPlayer4Cards:
            c.config(text="")

    def deal(self, trump):
        self.btnDeal.grid_remove()
        self.lblTrump.config(text="Trump: " + str(trump))
        self.new_round()

    def new_round(self):
        self.btnP1CardPlayed.config(text="")
        self.btnP1CardPlayed.grid_remove()
        self.btnP2CardPlayed.config(text="")
        self.btnP2CardPlayed.grid_remove()
        self.btnP3CardPlayed.config(text="")
        self.btnP3CardPlayed.grid_remove()
        self.btnP4CardPlayed.config(text="")
        self.btnP4CardPlayed.grid_remove()

    def update_player_hand(self, player, player_num):
        if player_num == 0:
            for c in self.btnPlayer1Cards:
                c.config(text="")
                c.grid_remove()
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer1Cards[i].grid()
                self.btnPlayer1Cards[i].config(text=str(c.rank) + str(c.suit))
        elif player_num == 1:
            for c in self.btnPlayer2Cards:
                c.config(text="")
                c.grid_remove()
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer2Cards[i].grid()
                if self.user_player:
                    self.btnPlayer2Cards[i].config(text="???")
                else:
                    self.btnPlayer2Cards[i].config(text=str(c.rank) + str(c.suit))
        elif player_num == 2:
            for c in self.btnPlayer3Cards:
                c.config(text="")
                c.grid_remove()
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer3Cards[i].grid()
                if self.user_player:
                    self.btnPlayer3Cards[i].config(text="???")
                else:
                    self.btnPlayer3Cards[i].config(text=str(c.rank) + str(c.suit))
        elif player_num == 3:
            for c in self.btnPlayer4Cards:
                c.config(text="")
                c.grid_remove()
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer4Cards[i].grid()
                if self.user_player:
                    self.btnPlayer4Cards[i].config(text="???")
                else:
                    self.btnPlayer4Cards[i].config(text=str(c.rank) + str(c.suit))
        self.update_player_points(player, player_num)

    def update_player_points(self, player, player_num):
        if player_num == 0:
            self.lblPlayer1Points.config(text="Points: " + str(player.points))
        elif player_num == 1:
            self.lblPlayer2Points.config(text="Points: " + str(player.points))
        elif player_num == 2:
            self.lblPlayer3Points.config(text="Points: " + str(player.points))
        elif player_num == 3:
            self.lblPlayer4Points.config(text="Points: " + str(player.points))

    def activate_player_turn(self, player, player_num):
        if player_num == 0:
            for i, c in enumerate(player.hand.cards):
                if player.valid_cards[i]:
                    self.btnPlayer1Cards[i].config(state="enabled")
        elif player_num == 1:
            for i, c in enumerate(player.hand.cards):
                if player.valid_cards[i]:
                    self.btnPlayer2Cards[i].config(state="enabled")
        elif player_num == 2:
            for i, c in enumerate(player.hand.cards):
                if player.valid_cards[i]:
                    self.btnPlayer3Cards[i].config(state="enabled")
        elif player_num == 3:
            for i, c in enumerate(player.hand.cards):
                if player.valid_cards[i]:
                    self.btnPlayer4Cards[i].config(state="enabled")

    def deactivate_player_turn(self, player, player_num):
        if player_num == 0:
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer1Cards[i].config(state="disabled")
        elif player_num == 1:
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer2Cards[i].config(state="disabled")
        elif player_num == 2:
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer3Cards[i].config(state="disabled")
        elif player_num == 3:
            for i, c in enumerate(player.hand.cards):
                self.btnPlayer4Cards[i].config(state="disabled")

    def update_current_player(self, player_num):
        self.lblCurrentPlayer.config(text="Current Player: " + str(player_num))

    def player_play_card(self, player, player_num, card):
        self.update_player_hand(player, player_num)
        if player_num == 0:
            self.btnP1CardPlayed.grid()
            self.btnP1CardPlayed.config(text=str(card.rank)+str(card.suit))
        elif player_num == 1:
            self.btnP2CardPlayed.grid()
            self.btnP2CardPlayed.config(text=str(card.rank)+str(card.suit))
        elif player_num == 2:
            self.btnP3CardPlayed.grid()
            self.btnP3CardPlayed.config(text=str(card.rank)+str(card.suit))
        elif player_num == 3:
            self.btnP4CardPlayed.grid()
            self.btnP4CardPlayed.config(text=str(card.rank)+str(card.suit))

    def game_over(self):
        self.btnNewHand.grid()
Exemplo n.º 37
0
 def __init__(self, master):
     self.master = master
     self.frame = Frame(self.master)
     self.configure_gui1()
Exemplo n.º 38
0
viewmenu.add_command(label="Difference", command=donothing)
viewmenu.entryconfig("Experimental", state=DISABLED)
viewmenu.entryconfig("Simulations", state=DISABLED)
viewmenu.entryconfig("Difference", state=DISABLED)
# viewmenu.entryconfig(themes, state=DISABLED)

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

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

# Add a couple of tabbed pages.
tabControl = Notebook(root)
tab1 = Frame(tabControl)
# tab2 = Frame(tabControl)

Label(tab1, text="Welcome to GeeksForGeeks").grid(column=0,
                                                  row=0,
                                                  padx=30,
                                                  pady=30)
# Label(tab2, text="Lets dive into the world of computers").grid(column=0, row=0, padx=30, pady=30)
canvas = Canvas(tabControl)
canvas.create_line(15, 25, 200, 25)
canvas.create_line(300, 35, 300, 200, dash=(4, 2))
canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)

tabControl.add(tab1, text='Tab 1')
#tabControl.add(tab2, text='Tab 2')
tabControl.add(canvas, text='Tab 2')
Exemplo n.º 39
0
    def criar_aba_itens(self):
        self.tab_itens = Frame(self.tabControl)
        self.tabControl.add(self.tab_itens, text="Ítens")

        Label(self.tab_itens, text="Produto: ").grid(sticky=W, row=0, padx=5)
        self.cbo_produtos = Combobox(
            self.tab_itens,
            textvariable=self.nome_produto_selecionado,
            state="readonly",
            postcommand=self.atualizar_lista_produtos)
        self.cbo_produtos.bind('<<ComboboxSelected>>', self.mudar_produto)
        self.cbo_produtos.grid(sticky="we",
                               row=1,
                               padx=5,
                               ipady=1,
                               pady=(0, 5),
                               columnspan=4)

        Button(self.tab_itens, text='Novo', command=self.cadastrar_novo_produto) \
            .grid(sticky="we", column=4, row=1, padx=5, pady=(0, 5), columnspan=2)

        Button(self.tab_itens, text='Editar', command=self.editar_produto) \
            .grid(sticky="we", column=6, row=1, padx=5, pady=(0, 5), columnspan=2)

        Label(self.tab_itens, text="DIF. ICMS").grid(sticky=W, row=2, padx=5)
        self.entry_df_icms = Entry(self.tab_itens, textvariable=self.dif_icms)
        self.entry_df_icms.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.dif_icms))
        self.entry_df_icms.grid(sticky="we", row=3, padx=5, columnspan=2)

        Label(self.tab_itens, text="DIF. IPI").grid(sticky=W,
                                                    column=2,
                                                    row=2,
                                                    padx=5)
        self.entry_df_ipi = Entry(self.tab_itens, textvariable=self.dif_ipi)
        self.entry_df_ipi.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.dif_ipi))
        self.entry_df_ipi.grid(sticky="we",
                               column=2,
                               row=3,
                               padx=5,
                               columnspan=2)

        Label(self.tab_itens, text="DIF. PIS").grid(sticky=W,
                                                    column=4,
                                                    row=2,
                                                    padx=5)
        self.entry_df_pis = Entry(self.tab_itens, textvariable=self.dif_pis)
        self.entry_df_pis.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.dif_pis))
        self.entry_df_pis.grid(sticky="we",
                               column=4,
                               row=3,
                               padx=5,
                               columnspan=2)

        Label(self.tab_itens, text="DIF. COFINS").grid(sticky=W,
                                                       column=6,
                                                       row=2,
                                                       padx=5)
        self.entry_df_cofins = Entry(self.tab_itens,
                                     textvariable=self.dif_cofins)
        self.entry_df_cofins.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.dif_cofins))
        self.entry_df_cofins.grid(sticky="we",
                                  column=6,
                                  row=3,
                                  padx=5,
                                  columnspan=2)

        Label(self.tab_itens, text="CFOP").grid(sticky=W, row=4, padx=5)
        self.entry_cfop = Entry(self.tab_itens,
                                textvariable=self.cfop,
                                width=12)
        self.entry_cfop.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.cfop))
        self.entry_cfop.grid(sticky="we", row=5, padx=5, columnspan=2)

        Label(self.tab_itens, text="COD. IMPOSTO").grid(sticky=W,
                                                        column=2,
                                                        row=4,
                                                        padx=5)
        self.entry_df_cofins = Entry(self.tab_itens,
                                     textvariable=self.codigo_imposto)
        self.entry_df_cofins.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.codigo_imposto))
        self.entry_df_cofins.grid(sticky="we",
                                  column=2,
                                  row=5,
                                  padx=5,
                                  columnspan=2)

        Button(self.tab_itens, text='Adicionar', command=self.inserir_item_remessa) \
            .grid(sticky="we", row=6, padx=5, pady=5, columnspan=2)

        Button(self.tab_itens, text='Remover', command=self.eliminar_item_remessas) \
            .grid(sticky="we", column=2, row=6, padx=5, pady=5, columnspan=2)

        self.treeview_itens = Treeview(self.tab_itens,
                                       height=4,
                                       column=("c0", "c1", "c2", "c3", "c4",
                                               "c5", "c6"),
                                       show="headings")
        self.treeview_itens.heading("#1", text="COD. PRODUTO")
        self.treeview_itens.heading("#2", text="ICMS")
        self.treeview_itens.heading("#3", text="IPI")
        self.treeview_itens.heading("#4", text="PIS")
        self.treeview_itens.heading("#5", text="COFINS")
        self.treeview_itens.heading("#6", text="CFOP")
        self.treeview_itens.heading("#7", text="IMPOSTO")

        self.treeview_itens.column("c0", width=120, stretch=NO, anchor=CENTER)
        self.treeview_itens.column("c1", width=70, stretch=NO, anchor=CENTER)
        self.treeview_itens.column("c2", width=70, stretch=NO, anchor=CENTER)
        self.treeview_itens.column("c3", width=70, stretch=NO, anchor=CENTER)
        self.treeview_itens.column("c4", width=70, stretch=NO, anchor=CENTER)
        self.treeview_itens.column("c5", width=70, stretch=NO, anchor=CENTER)
        self.treeview_itens.column("c6", width=70, stretch=NO, anchor=CENTER)

        self.treeview_itens.grid(sticky="we",
                                 row=7,
                                 padx=5,
                                 pady=(5, 0),
                                 columnspan=8)
Exemplo n.º 40
0
    def criar_aba_transporte(self):
        self.tab_transporte = Frame(self.tabControl)
        self.tabControl.add(self.tab_transporte, text="Transporte")

        Label(self.tab_transporte, text='Nome').grid(stick=W, padx=5)
        self.entry_nome = Entry(self.tab_transporte, textvariable=self.nome)
        self.entry_nome.grid(stick="we", row=1, padx=5, columnspan=3, ipady=1)
        self.entry_nome.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.nome))

        frame = Frame(self.tab_transporte)
        frame.grid(row=2, columnspan=3, stick='we', pady=5)
        self.tipo_lacre.set(0)
        self.rb_nao_informar_lacres = Radiobutton(frame,
                                                  text="Sem lacres",
                                                  value=0,
                                                  variable=self.tipo_lacre)
        self.rb_nao_informar_lacres.grid(sticky=W, padx=5)

        self.rb_informar_lacres = Radiobutton(frame,
                                              text="Lacres normal",
                                              value=1,
                                              variable=self.tipo_lacre)
        self.rb_informar_lacres.grid(sticky=W, row=0, column=1, padx=5)

        self.rb_informar_lacres_lona = Radiobutton(frame,
                                                   text="Lacres lona",
                                                   value=2,
                                                   variable=self.tipo_lacre)
        self.rb_informar_lacres_lona.grid(sticky=W, row=0, column=2, padx=5)

        self.inspecao_veiculo.set(1)
        self.cb_inspecao_veiculo = Checkbutton(self.tab_transporte,
                                               text="Inspeção veículo (07)",
                                               onvalue=1,
                                               offvalue=0,
                                               variable=self.inspecao_veiculo)
        self.cb_inspecao_veiculo.grid(sticky=W, row=3, padx=5)

        self.inspecao_produto.set(0)
        self.cb_inspecao_produto = Checkbutton(self.tab_transporte,
                                               text="Inspeção produto (89)",
                                               onvalue=1,
                                               offvalue=0,
                                               variable=self.inspecao_produto)
        self.cb_inspecao_produto.grid(sticky=W, column=1, row=3, padx=5)

        self.remover_a.set(0)
        self.cb_remover_a = Checkbutton(self.tab_transporte,
                                        text="Remover 'A'",
                                        onvalue=1,
                                        offvalue=0,
                                        variable=self.remover_a)
        self.cb_remover_a.grid(sticky=W, column=2, row=3, padx=5)

        Label(self.tab_transporte, text="Ordem/Pedido").grid(sticky=W,
                                                             column=0,
                                                             row=4,
                                                             padx=5)
        self.entry_numero_ordem = Entry(self.tab_transporte,
                                        textvariable=self.numero_ordem)
        self.entry_numero_ordem.grid(sticky="we", column=0, row=5, padx=5)
        self.entry_numero_ordem.config(validate="key",
                                       validatecommand=(self.app_main.register(
                                           NumberUtils.eh_inteiro), '%P'))

        Label(self.tab_transporte, text="Pedido de frete").grid(sticky=W,
                                                                column=1,
                                                                row=4,
                                                                padx=5)
        self.entry_numero_pedido_frete = Entry(
            self.tab_transporte, textvariable=self.numero_pedido_frete)
        self.entry_numero_pedido_frete.grid(sticky="we",
                                            column=1,
                                            row=5,
                                            padx=5,
                                            ipady=1,
                                            columnspan=2)
        self.entry_numero_pedido_frete.config(
            validate="key",
            validatecommand=(self.app_main.register(NumberUtils.eh_inteiro),
                             '%P'))

        Label(self.tab_transporte, text="Tipo frete").grid(sticky=W,
                                                           row=6,
                                                           padx=5)
        self.entry_tipo_frete = Entry(self.tab_transporte,
                                      textvariable=self.tipo_frete)
        self.entry_tipo_frete.grid(sticky="we",
                                   column=0,
                                   row=7,
                                   padx=5,
                                   ipady=1)
        self.entry_tipo_frete.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.tipo_frete))

        Label(self.tab_transporte, text="Destino").grid(sticky=W,
                                                        column=1,
                                                        row=6,
                                                        padx=5)
        self.entry_destino_frete = Entry(self.tab_transporte,
                                         textvariable=self.destino_frete)
        self.entry_destino_frete.grid(sticky="we",
                                      column=1,
                                      row=7,
                                      padx=5,
                                      ipady=1)
        self.entry_destino_frete.bind(
            '<KeyRelease>',
            lambda ev: StringUtils.to_upper_case(ev, self.destino_frete))

        Label(self.tab_transporte, text="Código transportador").grid(sticky=W,
                                                                     column=2,
                                                                     row=6,
                                                                     padx=5)
        self.codigo_transportador = Entry(
            self.tab_transporte, textvariable=self.codigo_transportador)
        self.codigo_transportador.grid(sticky="we",
                                       column=2,
                                       row=7,
                                       padx=5,
                                       ipady=1)
        self.codigo_transportador.config(
            validate="key",
            validatecommand=(self.app_main.register(NumberUtils.eh_inteiro),
                             '%P'))

        Label(self.tab_transporte, text="Docs. Diversos: ").grid(sticky=W,
                                                                 row=8,
                                                                 padx=5,
                                                                 pady=(5, 0))

        self.entry_docs_diversos = Text(self.tab_transporte,
                                        height=4,
                                        width=67)
        self.entry_docs_diversos.grid(sticky=W, row=9, padx=5, columnspan=3)
Exemplo n.º 41
0
 def __init__(self, parent):
     Frame.__init__(self, parent)
     self.parent = parent
     self.initUI()
Exemplo n.º 42
0
    def __init__(self, root,title,fname,const):
        self.root = root
        self.root.geometry("+150+50")
        self.fname =fname
        self.title=title
        self.const=const
        self.root.wm_title(self.title)
        self.sMin1=StringVar()
        self.sMin1.set("80")
        self.sMax1=StringVar()
        self.sMax1.set("220")
        self.sMin2=StringVar()
        self.sMin2.set("300")
        self.sMax2=StringVar()
        self.sMax2.set("400")
        
        frame = Frame(self.root, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH, expand=True)
        frameD1 = Frame(self.root)
        frameD1.pack(fill=BOTH, expand=True)
        frameD2 = Frame(self.root)
        frameD2.pack(fill=BOTH, expand=True)
        
        self.frame1 = Frame(frame)
        self.frame1.pack(fill=X)
        self.fig = Figure(figsize=(7, 6), dpi=100)

        dd=diodecv(self.fname,[float(self.sMin1.get()),float(self.sMax1.get()),float(self.sMin2.get()),float(self.sMax2.get())])

        if "DiodeCV" in fname and "flute" in fname:
            b=fname.split("DiodeCV")[1].split(".t")[0]
        elif "Diode_CV" in fname and "flute" in fname:
            b=fname.split("Diode_CV")[1].split(".t")[0]
        elif "half" in fname and not "flute" in fname:
            b=fname.split("CV")[1].split(".t")[0]

        dirD=os.path.dirname(os.path.abspath(fname))
        if "half" in fname and not "flute" in fname:
            self.img=dirD+"/Diode_half_CV_img"+b+".pdf"
        else:
            self.img=dirD+"/DiodeCV_flute3_img"+b+".pdf"
        self.result=[]
        self.result.append(self.title)
        self.result.append(dd[6])
        self.result.append(dd[7])
        self.result.append("")
        
        line1=np.poly1d(dd[2])
        #x1 = np.linspace(float(self.sMin1.get()),float(self.sMax1.get()), 100)
        line2=np.poly1d(dd[3])
        #x2 = np.linspace(float(self.sMin2.get()),float(self.sMax2.get()), 100)
        x1_l = np.linspace(float(self.sMin1.get()),dd[6]*1.02, 100)
        x2_l = np.linspace(dd[6]*0.9,float(self.sMax2.get()), 100)
        
        self.ax=self.fig.add_subplot(111)
        self.ax.plot(dd[0],dd[1],".",x1_l,line1(x1_l),x2_l,line2(x2_l))
        self.ax.ticklabel_format(axis='y',style='sci',scilimits=(-1,2),useOffset=True,useMathText=True)
        self.ax.set_title(self.title)
        self.ax.set_xlabel("Voltage [V]",loc='right')
        self.ax.set_ylabel("1/Capacitance$^{2}$ [1/pF$^{2}$]",loc='top')
        self.ax.text(0.7,0.2, ("Result:\n%.2f$\pm$%.2f [V]" % (dd[6],dd[7])), fontsize=10,horizontalalignment='center', style='normal', transform=self.ax.transAxes, bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 5})
        
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame1)  # A tk.DrawingArea.
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
        
        self.toolbar = NavigationToolbar2Tk(self.canvas, self.frame1)
        self.toolbar.update()
        self.canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

        self.lem1=Label(frameD1,text="Min1:", anchor=W,justify=LEFT, width=6)
        self.lem1.pack(side=LEFT, padx=5, pady=5)
        self.em1=Entry(frameD1, textvariable=self.sMin1, width=10)
        self.em1.pack(side=LEFT)#, padx=5, pady=5)
        self.em2=Entry(frameD1, textvariable=self.sMin2, width=10)
        self.em2.pack(side=RIGHT)#, padx=5, pady=5)
        self.lem2=Label(frameD1,text="Min2:", anchor=W,justify=LEFT, width=6)
        self.lem2.pack(side=RIGHT, padx=5, pady=5)

        self.leM1=Label(frameD2,text="Max1:", anchor=W,justify=LEFT, width=6)
        self.leM1.pack(side=LEFT, padx=5, pady=5)
        self.eM1=Entry(frameD2, textvariable=self.sMax1, width=10)
        self.eM1.pack(side=LEFT)#, padx=5, pady=5)
        self.eM2=Entry(frameD2, textvariable=self.sMax2, width=10)
        self.eM2.pack(side=RIGHT)#, padx=5, pady=5)
        self.leM2=Label(frameD2,text="Max2:", anchor=W,justify=LEFT, width=6)
        self.leM2.pack(side=RIGHT, padx=5, pady=5)
                
        self.b3=Button(self.root,text='Next',command=self.closeExt)
        self.b3.pack(side=RIGHT, padx=5, pady=5)
        self.b2=Button(self.root,text='Update',command= self.UpdateDiodeCV)
        self.b2.pack(side=RIGHT)

        self.root.wait_window(self.root)
Exemplo n.º 43
0
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="Input Review", font=LARGE_FONT)
        label.pack(pady=10, padx=10)

        input_name = tk.StringVar()

        frame1 = Frame(self)
        frame1.pack(anchor='nw')

        lbl1 = Label(frame1, text="Name", width=8)
        lbl1.pack(side='left', padx=5, pady=5)

        entry1 = Entry(frame1, textvariable=input_name, width=50)
        entry1.pack(side='left', padx=5, expand=True)

        frame2 = Frame(self)
        frame2.pack(anchor='nw', expand=True)

        lbl2 = Label(frame2, text="Review", width=8)
        lbl2.pack(side='left', anchor='nw', padx=5, pady=5)

        txt = tk.Text(frame2, width=50, height=20)
        txt.pack(side='left', pady=5, padx=5, expand=True)

        button1 = tk.Button(frame2, text="Confirm", command=lambda: self.predictReview(input_name, txt.get(1.0, "end-1c"), entry1, txt, frame3, text))
        button1.pack(anchor='n', side='top', padx=5, pady=5)

        button2 = tk.Button(frame2, text="Home", command=lambda: controller.show_frame(StartPage))
        button2.pack(anchor='s', side='bottom', padx=5, pady=5)

        frame3 = Frame(self)
        frame3.pack(anchor='nw', expand=True)

        text = tk.scrolledtext.ScrolledText(frame3, height=10, width=70, wrap='word')
Exemplo n.º 44
0
 def __init__(self, master=None):
     Frame.__init__(self, master)
     self.master.title('Excel2DDLCMod')
     self.master.geometry('600x343')
     self.createWidgets()
Exemplo n.º 45
0
    def __init__(self, title, controller, user_player):
        self.user_player = user_player
        Tk.__init__(self)
        self.title(title)
        self.centerWindow()

        self.w = Frame(self)
        self.w.pack(fill=BOTH, expand=1)
        for x in range(15):
            self.w.columnconfigure(x, weight=1)
        self.w.rowconfigure(3, weight=1)
        self.w.rowconfigure(6, weight=1)
        self.w.rowconfigure(7, weight=1)
        self.w.rowconfigure(8, weight=1)
        self.w.rowconfigure(11, weight=1)

        self.lblTitle = Label(self.w, text="Euchre")
        self.lblTitle.grid(row=0, column=5, columnspan=5)

        # Center Table
        self.btnDeck = Button(self.w, text="Deck", state="disabled")
        self.btnDeck.grid(row=4, column=5, rowspan=5, columnspan=2, sticky=N+S+E+W)
        self.lblTrump = Label(self.w, text="Trump: ")
        self.lblTrump.grid(row=4, column=7, columnspan=3)
        self.lblCurrentPlayer = Label(self.w, text="Current Player: ")
        self.lblCurrentPlayer.grid(row=5, column=7, columnspan=3)
        self.btnP1CardPlayed = Button(self.w, state="disabled")
        self.btnP1CardPlayed.grid(row=8, column=8, sticky=N+S+E+W)
        self.btnP2CardPlayed = Button(self.w, state="disabled")
        self.btnP2CardPlayed.grid(row=7, column=7, sticky=N+S+E+W)
        self.btnP3CardPlayed = Button(self.w, state="disabled")
        self.btnP3CardPlayed.grid(row=6, column=8, sticky=N+S+E+W)
        self.btnP4CardPlayed = Button(self.w, state="disabled")
        self.btnP4CardPlayed.grid(row=7, column=9, sticky=N+S+E+W)
        self.btnNewHand = Button(self.w, text="New Hand", command=lambda: controller.restart_trick())
        self.btnNewHand.grid(row=7, column=8, sticky=N+S+E+W)
        self.btnDeal = Button(self.w, text="Deal", command=lambda:controller.deal())
        self.btnDeal.grid(row=4, column=7, rowspan=5, columnspan=3, sticky=N+S+E+W)

        def player_choose_card_callback_factory(player, card):
            return lambda: controller.player_choose_card(player, card)

        # Player 1 hand
        self.lblPlayer1Title = Label(self.w, text=("You" if user_player else "Player 1"))
        self.lblPlayer1Title.grid(row=9, column=5, columnspan=5)
        self.lblPlayer1Points = Label(self.w, text=("Points: 0"))
        self.lblPlayer1Points.grid(row=10, column=5, columnspan=5)
        self.btnPlayer1Cards = []
        for i in range(5):
            self.btnPlayer1Cards.append(Button(self.w, command=player_choose_card_callback_factory(0, i), state="disabled"))
            self.btnPlayer1Cards[i].grid(row=11, column=5+i, sticky=N+S+E+W)

        # Player 2 hand
        self.lblPlayer2Title = Label(self.w, text="Player 2")
        self.lblPlayer2Title.grid(row=4, column=0, columnspan=5)
        self.lblPlayer2Points = Label(self.w, text="Points: 0")
        self.lblPlayer2Points.grid(row=5, column=0, columnspan=5)
        self.btnPlayer2Cards = []
        for i in range(5):
            self.btnPlayer2Cards.append(Button(self.w, command=player_choose_card_callback_factory(1, i), state="disabled"))
            self.btnPlayer2Cards[i].grid(row=6, column=0+i, rowspan=3, sticky=N+S+E+W)

        # Player 3 hand
        self.lblPlayer3Title = Label(self.w, text="Player 3")
        self.lblPlayer3Title.grid(row=1, column=5, columnspan=5)
        self.lblPlayer3Points = Label(self.w, text="Points: 0")
        self.lblPlayer3Points.grid(row=2, column=5, columnspan=5)
        self.btnPlayer3Cards = []
        for i in range(5):
            self.btnPlayer3Cards.append(Button(self.w, command=player_choose_card_callback_factory(2, i), state="disabled"))
            self.btnPlayer3Cards[i].grid(row=3, column=5+i, sticky=N+S+E+W)

        # Player 4 hand
        self.lblPlayer4Title = Label(self.w, text="Player 4")
        self.lblPlayer4Title.grid(row=4, column=10, columnspan=5)
        self.lblPlayer4Points = Label(self.w, text="Points: 0")
        self.lblPlayer4Points.grid(row=5, column=10, columnspan=5)
        self.btnPlayer4Cards = []
        for i in range(5):
            self.btnPlayer4Cards.append(Button(self.w, command=player_choose_card_callback_factory(3, i), state="disabled"))
            self.btnPlayer4Cards[i].grid(row=6, column=10+i, rowspan=3, sticky=N+S+E+W)
Exemplo n.º 46
0
## GUI Tkinter

_bgcolor = '#d9d9d9'  # X11 color: 'gray85'
_fgcolor = '#000000'  # X11 color: 'black'
_compcolor = '#d9d9d9'  # X11 color: 'gray85'
_ana1color = '#d9d9d9'  # X11 color: 'gray85'
_ana2color = '#d9d9d9'  # X11 color: 'gray85'
styl = Style()
styl.theme_use('clam')
styl.configure('.', background=_bgcolor)
styl.configure('.', foreground=_fgcolor)
styl.configure('.', sliderthickness='20')
styl.configure('.', font="TkDefaultFont")
styl.map('.', background=[('selected', _compcolor), ('active', _ana2color)])

Frame1 = Frame(root)
Frame1.place(relx=0.02, rely=0.02, relheight=0.27, relwidth=0.46)
Frame1.configure(relief=GROOVE)
Frame1.configure(borderwidth="2")
Frame1.configure(relief=GROOVE)
Frame1.configure(width=285)

Checkbutton1 = Checkbutton(Frame1)
Checkbutton1.place(relx=0.07, rely=0.43, relheight=0.22, relwidth=0.34)
Checkbutton1.configure(text='''Profile photo''')
Checkbutton1.configure(variable=check1)

Checkbutton3 = Checkbutton(Frame1)
Checkbutton3.place(relx=0.07, rely=0.7, relheight=0.22, relwidth=0.35)
Checkbutton3.configure(text='''Header photo''')
Checkbutton3.configure(variable=check2)
Exemplo n.º 47
0
class SGraphTK:
    """
    Diese Klasse ist fuer die Einbettung von Matplolib-Darstellungen in einem
    TKinter-Rahmen zustaendig.

    Daten, die von dieser Klassen geplot werden, sind Daten, welche noch keine
    mit irgendwelchem Machinellen Lernen Algorithmus trainiert sind
    """

    def __init__(self, col, row, px, py, master_lf=None):
        """
        Die Klasse besitzt ein Hauptframe für graphische Ansichte (gmaster) und ein inneres Frame (intern_frame_up),
        wobei, das innere Frame für die Visualisierung nicht trainierten Daten zuständig ist.
        :param root: Frame, in welchem der Graph geplot wird
        """
        self.gmaster = master_lf                 # Hauptframe: wird von einer anderen Klasse (Frame) bestimmt
        self.gmaster.grid(column=col, row=row, padx=px, pady=py)
        self.intern_frame = Frame(master=self.gmaster)     # innere Frame für einzelnen Graphen
        self.intern_frame.grid(column=col, row=row, padx=px, pady=py)

        self.canvas = None
        self.frame = None
        pass

    def on_draw_line(self, x, y, xlab, ylab, lincolor=None, linstyle=None):
        """
        ...
        :param x:
        :param y:
        :param xlab:
        :param ylab:
        :param lincolor:
        :param linstyle:
        :param figcol:
        :return:
        """
        fig = plt.Figure(figsize=(4.4, 2.7), dpi=80, facecolor='white', constrained_layout=True)
        ax = fig.add_subplot(111)
        ax.plot(x, y, color=lincolor, linestyle=linstyle)
        ax.set_xlabel(xlab)
        ax.set_ylabel(ylab)
        ax.set_title('Täglicher Stromverbauch')

        return fig

    def put_graph_on_canvas(self, fig): #
        self.canvas = FigureCanvasTkAgg(fig, master=self.intern_frame)
        self.canvas.draw()
        self.canvas.get_tk_widget().grid(column=0, row=0, padx=5, pady=5)
        self.intern_frame.update()

    def on_update_canvas(self, fig):
        self.canvas = None
        self.put_graph_on_canvas(fig)

    def on_draw_scatter(self, x, y, d=None, h=None):
        fig = plt.Figure(figsize=(4.4, 2.7), dpi=80, facecolor='white', constrained_layout=True)
        ax = fig.add_subplot(111)
        sb.scatterplot(x=x, y=y, hue=h, data=d, ax=ax)
        ax.set_xlabel('Tage (in Integer)')
        ax.set_ylabel('Stromverbrauch (in w min)')
        ax.set_title('Wöchentliche Stromverbauch')

        return fig

    # https://stackoverflow.com/questions/31594549/how-do-i-change-the-figure-size-for-a-seaborn-plot
    def on_draw_box(self, x, y, df=None, h=None):
        fig = plt.Figure(figsize=(4.4, 2.7), dpi=80, facecolor='white', constrained_layout=True)
        ax = fig.add_subplot(111)
        sb.boxplot(x=x, y=y, data=df, hue=h, ax=ax)
        ax.set_xlabel('Wochentage')
        ax.set_ylabel('Stromverbrauch (in w min)')
        ax.set_title('Monatlicher Stromverbauch')
        ax.set_xticklabels(labels=x, rotation=15)

        return fig

    def on_draw_bar(self, x, y, h=None, data=None):
        """

        :param x:
        :param y:
        :param data:
        :return:
        """
        fig = plt.Figure(figsize=(4.4, 2.7), dpi=80, facecolor='white', constrained_layout=True)
        ax = fig.add_subplot(111)
        sb.catplot(x=x, y=y, hue=h, data=data, kind='bar', ax=ax)
        ax.set_xlabel('Wochentage')
        ax.set_ylabel('Stromverbrauch (in w min)')
        ax.set_title('Monatlicher Stromverbauch')
        ax.set_xticklabels(labels=x, rotation=15)

        return fig
Exemplo n.º 48
0
    def __init__(self) -> None:
        self.Root = Tk()
        self.App = Frame(self.Root, padding=(5, 2))
        self.UpdatesFrame = LabelFrame(self.App, text='Обновление',
                                       borderwidth=2, relief='sunken', padding=(5, 2))
        self.upd_enabled = BooleanVar()  # Флаг обновлений
        self.upd_unit = StringVar()  # Единица измерения времени
        self.time_units = {Minutes: 'Минут', Hours: 'Часов',
                           Days: 'Дней', Weeks: 'Недель', Months: 'Месяцев'}
        self.size_units = {Bytes: 'Байт', KBytes: 'Кбайт', MBytes:'Мбайт',
                           GBytes:'Гбайт', TBytes:'Тбайт'}  # Список единиц измерения времени
        self.maxfsize = StringVar()  # Максимальный размер файла
        self.size_unit = StringVar()  # Единица измерения информации
        self.units_amount1 = StringVar()  # Количество единиц
        self.quar = BooleanVar()  # False - удалять, True - карантин
        self.quar_path = StringVar() # Расположение карантина
        self.rpt_enabled = BooleanVar()  # Флаг отправки отчета
        self.email = StringVar()  # Адрес отправки
        self.passwd = StringVar() # Пароль исходящего ящика
        self.rpt_unit = StringVar()  # Единица измерения времени
        self.units_amount2 = StringVar()  # Количество единиц

        self.Upd_Label1 = Label(self.UpdatesFrame, text='Проверять обновления антивирусных баз')
        self.Upd_Checkbutton1 = Checkbutton(self.UpdatesFrame, variable=self.upd_enabled)
        self.Upd_Label2 = Label(self.UpdatesFrame, text='Частота проверки:   каждые')
        self.Upd_Spinbox1 = Spinbox(self.UpdatesFrame, textvariable=self.units_amount1,
                                    from_=1, to=999999999, width=4)
        self.Upd_OptionMenu1 = OptionMenu(self.UpdatesFrame, self.upd_unit, *self.time_units.values())
        self.Upd_Button1 = Button(
            self.UpdatesFrame, text='Источники антивирусных сигнатур', command=EntryOptionsWindow('AV_SOURCES', self.Root).main)

        self.ScanFrame = LabelFrame(self.App, text='Сканирование',
                                    borderwidth=2, relief='sunken', padding=(5, 2))
        self.Scn_Label1 = Label(self.ScanFrame, text='Максимальный размер файла:')
        self.Scn_Spinbox1 = Spinbox(self.ScanFrame, textvariable=self.maxfsize,
                                    from_=0, to=999999999, width=8)

        self.Quar_Label = Label(self.ScanFrame, text='При обнаружении угрозы')
        self.Quar_RadButton1 = Radiobutton(self.ScanFrame, text='Удаление', variable=self.quar, value=False)
        self.Quar_RadButton2 = Radiobutton(self.ScanFrame, text='Карантин', variable=self.quar, value=True)

        self.Scn_OptionMenu1 = OptionMenu(self.ScanFrame, self.size_unit, *self.size_units.values())
        self.Scn_Edit_Targets = Button(self.ScanFrame, text='Цели сканирования', command=EntryOptionsWindow('SCAN_TARGETS', self.Root, select_path=True).main)
        self.Scn_Edit_Exceptions = Button(self.ScanFrame, text='Исключения', command=EntryOptionsWindow('SCAN_EXCLUDE', self.Root).main)
        self.Quar_Button1 = Button(self.ScanFrame, text='Расположение карантина',
                                   command=lambda: self.quar_path.set(filedialog.askdirectory()))

        self.ReportFrame = LabelFrame(self.App, text='Отправка отчета',
                                      borderwidth=2, relief='sunken', padding=(5, 2))

        self.Rpt_Label1 = Label(self.ReportFrame, text='Отправлять отчеты о сканировании')
        self.Rpt_Checkbutton1 = Checkbutton(self.ReportFrame, variable=self.rpt_enabled)
        self.Rpt_Label2 = Label(self.ReportFrame, text='Адрес отправки отчетов:')
        self.Rpt_Entry1 = Entry(self.ReportFrame, textvariable=self.email, width=32)
        self.Rpt_Label3 = Label(self.ReportFrame, text='Пароль:')
        self.Rpt_Entry2 = Entry(self.ReportFrame, textvariable=self.passwd, width=32, show='*')
        self.Rpt_Label4 = Label(self.ReportFrame, text='Частота:')
        self.Rpt_Spinbox1 = Spinbox(self.ReportFrame, textvariable=self.units_amount2,
                                    from_=1, to=999999999, width=4)
        self.Rpt_OptionMenu1 = OptionMenu(self.ReportFrame, self.rpt_unit, *self.time_units.values())
        self.Rpt_Button1 = Button(self.ReportFrame, text='Получатели', command=EntryOptionsWindow('SEND_TO', self.Root).main)

        self.Buttons = Frame(self.App, padding=(5, 2))
        self.Button1 = Button(self.Buttons, text='Готово', command=self.save_conf)
        self.Button2 = Button(self.Buttons, text='Отмена', command=self.Root.destroy)
Exemplo n.º 49
0
    def create_widgets(self):
        """Populate object and its widgets."""
        self.variable = {}
        self.label = {}
        self.widget = {}
        self.tab = {}
        self.group = {}
        self.notebook = Notebook(self)
        self.notebook.pack(fill="both", expand=True)

        if self.fields is None:
            return

        for i, (name, desc) in enumerate(self.fields.items()):
            if "tab" not in desc:
                desc["tab"] = "main"

            if desc["tab"] not in self.tab:
                parent = Frame(self.notebook)
                parent.columnconfigure([0, 1],
                                       weight=1,
                                       minsize=self.column_minsize)
                self.notebook.add(parent, text=desc["tab"].capitalize())
                self.tab[desc["tab"]] = parent
            else:
                parent = self.tab[desc["tab"]]

            if "group" in desc:
                if desc["group"] not in self.group:
                    group = LabelFrame(parent, text=desc["group"].capitalize())
                    group.columnconfigure([0, 1],
                                          weight=1,
                                          minsize=self.column_minsize)
                    group.grid(
                        row=i,
                        column=0,
                        columnspan=2,
                        sticky="ew",
                        padx=self.padx,
                        pady=9 * self.pady,
                    )
                    self.group[desc["group"]] = group
                else:
                    group = self.group[desc["group"]]
                parent = group

            if "values" in desc:
                values = list(desc["values"])

            if "type" not in desc:
                # if no type is given, first guess it based on a default value,
                # or infer from the first valid value.
                if "default" in desc and desc["default"] is not None:
                    desc["type"] = type(desc["default"])
                elif "values" in desc:
                    desc["type"] = type([v for v in values
                                         if v is not None][0])
                else:
                    raise ValueError(
                        f"could not infer type, please specify: {desc}")

            if "default" not in desc:
                # if no default is given, use the first value (even if None),
                # or infer from type.
                if "values" in desc:
                    desc["default"] = [v for v in values][0]
                elif "type" in desc:
                    desc["default"] = desc["type"]()
                else:
                    raise ValueError(
                        f"could not infer default, please specify: {desc}")

            if desc["type"] is int or desc["type"] is np.int64:
                self.variable[name] = IntVar(self)
            elif desc["type"] is bool:
                self.variable[name] = BooleanVar(self)
            elif desc["type"] is str:
                self.variable[name] = StringVar(self)
            elif desc["type"] is float:
                self.variable[name] = DoubleVar(self)
                if "values" in desc:
                    values = [np.round(v, 2) for v in values]
            else:
                raise ValueError(f"unknown type '{desc['type']}' for '{name}'")

            if "text" in desc:
                text = desc["text"]
            else:
                text = name.capitalize()

            if "widget" not in desc:
                # TODO(schneiderfelipe): should this be default?
                desc["widget"] = Combobox

            if desc["widget"] is Checkbutton:
                self.widget[name] = desc["widget"](
                    parent, variable=self.variable[name], text=text)
            elif "values" in desc:
                self.widget[name] = desc["widget"](
                    parent, textvariable=self.variable[name], values=values)
            else:
                self.widget[name] = desc["widget"](
                    parent, textvariable=self.variable[name])
            self.widget[name].grid(row=i,
                                   column=1,
                                   sticky="ew",
                                   padx=self.padx,
                                   pady=self.pady)

            if "help" in desc:
                create_tooltip(self.widget[name], desc["help"])

            if desc["widget"] is not Checkbutton:
                self.label[name] = Label(parent, text=text + ":")
                self.label[name].grid(
                    row=i,
                    column=0,
                    sticky="ew",
                    padx=self.padx,
                    pady=self.pady,
                )

            if "visible" not in desc:
                desc["visible"] = True

        self.init_widgets()
Exemplo n.º 50
0
def make_pane(parent: ttk.Frame):
    """Create all the widgets we use."""
    CONFIG_ORDER.sort(key=lambda grp: grp.name)

    parent.columnconfigure(0, weight=1)

    # Need to use a canvas to allow scrolling
    canvas = tk.Canvas(parent, highlightthickness=0)
    canvas.grid(row=0, column=0, sticky='NSEW')
    parent.rowconfigure(0, weight=1)

    scrollbar = ttk.Scrollbar(
        parent,
        orient='vertical',
        command=canvas.yview,
    )
    scrollbar.grid(column=1, row=0, sticky="ns")
    canvas['yscrollcommand'] = scrollbar.set

    utils.add_mousewheel(canvas, canvas, parent)
    canvas_frame = ttk.Frame(canvas)
    canvas.create_window(0, 0, window=canvas_frame, anchor="nw")
    canvas_frame.rowconfigure(0, weight=1)

    sign_button = signage_ui.init_widgets(canvas_frame)
    sign_button.grid(row=0, column=0, sticky='ew')

    for conf_row, config in enumerate(CONFIG_ORDER, start=1):
        frame = ttk.LabelFrame(canvas_frame, text=config.name)
        frame.columnconfigure(0, weight=1)
        frame.grid(row=conf_row, column=0, sticky='nsew')

        row = 0

        widget_count = len(config.widgets) + len(config.multi_widgets)

        # Now make the widgets.
        if config.widgets:
            for row, wid in enumerate(config.widgets):
                wid_frame = ttk.Frame(frame)
                wid_frame.grid(row=row, column=0, sticky='ew')
                wid_frame.columnconfigure(1, weight=1)

                label = ttk.Label(wid_frame, text=wid.name + ': ')
                label.grid(row=0, column=0)
                widget = wid.create_func(wid_frame, wid.values, wid.config)
                widget.grid(row=0, column=1, sticky='e')

                if wid.tooltip:
                    add_tooltip(widget, wid.tooltip)
                    add_tooltip(label, wid.tooltip)
                    add_tooltip(wid_frame, wid.tooltip)

        if config.widgets and config.multi_widgets:
            ttk.Separator(orient='horizontal').grid(
                row=1,
                column=0,
                sticky='ew',
            )

        # Skip if no timer widgets
        if not config.multi_widgets:
            continue

        # Continue from wherever we were.
        for row, wid in enumerate(config.multi_widgets, start=row + 1):
            # If we only have 1 widget, don't add a redundant title.
            if widget_count == 1:
                wid_frame = ttk.Frame(frame)
            else:
                wid_frame = ttk.LabelFrame(frame, text=wid.name)

            wid_frame.grid(row=row, column=0, sticky='ew')
            wid.multi_func(
                wid_frame,
                wid.values,
                wid.config,
            )

            if wid.tooltip:
                add_tooltip(wid_frame, wid.tooltip)

    canvas.update_idletasks()
    canvas.config(
        scrollregion=canvas.bbox('ALL'),
        width=canvas_frame.winfo_reqwidth(),
    )

    def canvas_reflow(e):
        canvas['scrollregion'] = canvas.bbox('all')

    canvas.bind('<Configure>', canvas_reflow)
Exemplo n.º 51
0
class Control(Module):
    '''
    This class provides a clean interface for managing Undo/Redo functionality.
    Implementation relies on storing two lists of actions as stacks, one for Undo
    and one for Redo.  Calling Undo/Redo should pop the corresponding stack and
    execute the inverse of that action, pushing the inverse action to the other
    stack (so its inversion can also be executed).

    Note: both stacks get cleared on
        - change files
        - change frames
        - Dicom.resetZoom()
    '''
    def __init__(self, app):
        info( ' - initializing module: Control' )
        # reference to our main object containing other functionality managers
        self.app = app
        # initialize our stacks
        self.reset()

        # some images for the buttons
        # Source for icons: https://material.io/tools/icons/?style=outline
        # License: Apache Version 2.0 www.apache.org/licenses/LICENSE-2.0.txt
        data_copy = '''R0lGODlhGAAYAPAAAAAAAAAAACH5BAEAAAEALAAAAAAYABgAAAJHjI+pCe3/1oHUSdOunmDvHFTWBYrjUnbMuWIqAqEqCMdt+HI25yrVTZMEcT3NMPXJEZckJdKorCWbU2H0JqvKTBErl+XZFAAAOw'''
        data_paste = '''R0lGODlhGAAYAPAAAAAAAAAAACH5BAEAAAEALAAAAAAYABgAAAJBjI+pq+DAonlPToqza7rv9FlBeJCSOUJpd3EXm7piDKoi+nkqvnttPaMhUAzeiwJMapJDm8U44+kynCkmiM1qZwUAOw'''

        self.img_copy = PhotoImage(data=data_copy)
        self.img_paste = PhotoImage(data=data_paste)

        # bind Ctrl+z to UNDO and Ctrl+Shift+Z to REDO
        if util.get_platform() == 'Linux':
            self.app.bind('<Control-z>', self.undo )
            self.app.bind('<Control-Z>', self.redo )
        else:
            self.app.bind('<Command-z>', self.undo )
            self.app.bind('<Command-Z>', self.redo )
        # also make some buttons and bind them
        self.frame = Frame(self.app.LEFT)#, pady=7)
        self.frame.grid( row=5 )
        self.header = Header(self.frame, text="Points")
        self.selectAllBtn = Button(self.frame, text='⬚', command=self.selectAll, takefocus=0, style="symbol.TButton", width=1.5)
        self.copyBtn = Button(self.frame, image=self.img_copy, command=self.copy, takefocus=0)  # FIXME: add tooltip for "Copy"
        self.pasteBtn = Button(self.frame, image=self.img_paste, command=self.paste, takefocus=0) # FIXME: add tooltip for "Paste"
        self.undoBtn = Button(self.frame, text='↶', command=self.undo, takefocus=0, width=1.5, style="symbol.TButton")
        self.redoBtn = Button(self.frame, text='↷', command=self.redo, takefocus=0, width=1.5, style="symbol.TButton")
        self.updateButtons()
    def push(self, item):
        '''
        add an item to the undo-stack
        and empty out the redo-stack
        '''
        self.uStack.append( item )
        self.rStack = []
        self.updateButtons()
    def reset(self):
        ''' reset our stacks '''
        self.uStack = [] # undo
        self.rStack = [] # redo
    def update(self):
        ''' changing files and changing frames should have the same effect '''
        self.reset()
    def selectAll(self):
        self.app.Trace.selectAll()
    def copy(self):
        self.app.Trace.copy()
    def paste(self):
        self.app.Trace.paste()
    def undo(self, event=None):
        ''' perform the undo-ing '''

        if len(self.uStack):
            item = self.uStack.pop()

            if item['type'] == 'add':
                chs = item['chs']
                for ch in chs:
                    self.app.Trace.remove( ch )
                self.rStack.append({ 'type':'delete', 'chs':chs })
            elif item['type'] == 'delete':
                chs = item['chs']
                for ch in chs:
                    ch.draw()
                self.rStack.append({ 'type':'add', 'chs':chs })
            elif item['type'] == 'move':
                chs = item['chs']
                coords = item['coords']
                for i in range(len(chs)):
                    chs[i].dragTo( coords[i] )
                self.rStack.append({ 'type':'move', 'chs':chs, 'coords':coords })
            elif item['type'] == 'recolor':
                oldColor = self.app.Trace.recolor( item['trace'], item['color'] )
                self.rStack.append({ 'type':'recolor', 'trace':item['trace'], 'color':oldColor })
            elif item['type'] == 'rename':
                self.app.Trace.renameTrace( newName=item['old'], oldName=item['new'] ) # this is backwards on purpose
                self.rStack.append({ 'type':'rename', 'old':item['old'], 'new':item['new'] })
            else:
                error(item)
                raise NotImplementedError

            self.app.Trace.unselectAll()
            self.app.Trace.write()
            self.updateButtons()
        else:
            warn( 'Nothing to undo!' )
    def redo(self, event=None):
        ''' perform the redo-ing '''

        if len(self.rStack):
            item = self.rStack.pop()

            if item['type'] == 'add':
                chs = item['chs']
                for ch in chs:
                    self.app.Trace.remove( ch )
                self.uStack.append({ 'type':'delete', 'chs':chs })
            elif item['type'] == 'delete':
                chs = item['chs']
                for ch in chs:
                    ch.draw()
                self.uStack.append({ 'type':'add', 'chs':chs })
            elif item['type'] == 'move':
                chs = item['chs']
                coords = item['coords']
                for i in range(len(chs)):
                    chs[i].dragTo( coords[i] )
                self.uStack.append({ 'type':'move', 'chs':chs, 'coords':coords })
            elif item['type'] == 'recolor':
                oldColor = self.app.Trace.recolor( item['trace'], item['color'] )
                self.uStack.append({ 'type':'recolor', 'trace':item['trace'], 'color':oldColor })
            elif item['type'] == 'rename':
                self.app.Trace.renameTrace( newName=item['new'], oldName=item['old'] )
                self.uStack.append({ 'type':'rename', 'old':item['old'], 'new':item['new'] })
            else:
                error(item)
                raise NotImplementedError

            self.app.Trace.unselectAll()
            self.app.Trace.write()
            self.updateButtons()
        else:
            warn( 'Nothing to redo!' )
    def updateButtons(self):
        '''
        Don't allow clicking buttons that wrap empty stacks.  However, users will
        still be able to access that functionality thru key bindings.
        '''
        self.undoBtn['state'] = 'normal' if len(self.uStack) else 'disabled'
        self.redoBtn['state'] = 'normal' if len(self.rStack) else 'disabled'
        self.grid()
    def grid(self):
        '''
        Grid button widgets
        '''
        self.header.grid(row=0,column=0, columnspan=5)
        self.selectAllBtn.grid(row=1, column=0)
        self.copyBtn.grid(row=1, column=1, ipady=3)
        self.pasteBtn.grid(row=1, column=2, ipady=3)

        self.undoBtn.grid(row=1, column=3)
        self.redoBtn.grid(row=1, column=4)
    def grid_remove(self):
        '''
        Remove button widgets from grid
        '''
        self.undoBtn.grid_remove()
        self.redoBtn.grid_remove()
Exemplo n.º 52
0
        Parameters
        ----------
        option : str
            foreground, background

        Returns
        -------
        string
            foreground, background
        """
        # Returns the style map for 'option' with any styles starting with
        # ('!disabled', '!selected', ...) filtered out.

        # style.map() returns an empty list for missing options, so this
        # should be future-safe.
        return [elm for elm in self.s.map('Treeview', query_opt=option) if
            elm[:2] != ('!disabled', '!selected')]


if __name__ == "__main__":
    root = Tk()
    csvFile = '../csv_data/test.csv'
    csvDelimiter = ';'
    page1 = Frame(root)
    page1.pack(fill='both', expand=False)
    t = Tree(page1,csvFile,csvDelimiter)
    b2=Button(page1,text='Click after selection', command=lambda:print(t.lvar.get()))
    b2.grid(column=0, row=3)

    root.mainloop()
Exemplo n.º 53
0
        rgb = [int(i/65535 * 255) for i in value0]
        rgb = tuple(rgb)
        if contrast(rgb) < 0.5:
            lbl2["foreground"]='white'
        tvalue = value = '#%02x%02x%02x' % rgb
    elif value[0] == '#':
        h = value.lstrip('#')
        tvalue = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
        if contrast(tvalue) < 0.5:
            lbl2["foreground"]='white'
        
    lbl2["text"]=tvalue
    lbl2["background"]=value
    
root = Tk()
fr = Frame(root)
fr.grid(column=0,row=0)
fr2 = Frame(root)
fr2.grid(column=1,row=0)
lbl = Label(fr,text= 'Enter colour code\n no quotes\n code can be r,g,b\n hash #rrggbb\n or name')
lbl.grid(column=0,row=0,padx=5,pady=10)

ey = Entry(fr2)
ey.grid(column=0,row=0,padx=5,pady=10)
out=StringVar(ey.get())

lf=LabelFrame(fr,text='Colour')
lf.grid(column=0,row=1)
lbl2=Label(lf,text='waiting')
lbl2.grid(column=0,row=1)
but1=Button(fr2,text='Make Colour', command=getit)
Exemplo n.º 54
0
    def __init__(self, mainWin, options):
        parent = mainWin.parent
        self.modelManager = mainWin.modelManager
        super(DialogFormulaParameters, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("Formula Parameters and Trace Options"))
        
        frame = Frame(self)

        '''
        dialogFrame = Frame(frame, width=500)
        dialogFrame.columnconfigure(0, weight=1)
        dialogFrame.rowconfigure(0, weight=1)
        dialogFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        '''
        
        # mainWin.showStatus(_("loading formula options and parameters"))
        
        # load grid
        gridHdr(frame, 1, 0, "Parameters", columnspan=3)
        gridHdr(frame, 1, 1, "QName")
        gridHdr(frame, 2, 1, "Type")
        gridHdr(frame, 3, 1, "Value")
        
        self.gridCells = []
        y = 2
        dataTypes = ("xs:string", "xs:integer", "xs:decimal", "xs:date", "xs:datetime", "xs:QName")
        for parameter in options["parameterValues"].items():
            paramQname, paramTypeValue = parameter
            if isinstance(paramTypeValue, (tuple,list)):
                paramType, paramValue = paramTypeValue  # similar to modelTestcaseObject, where values() are (type,value)
            else:
                paramType = None
                paramValue = paramTypeValue
            self.gridCells.append( (
                gridCell(frame, 1, y, paramQname),
                gridCombobox(frame, 2, y, paramType, values=dataTypes),
                gridCell(frame, 3, y, paramValue)) )
            y += 1
        # extra entry for new cells
        for i in range(5):
            self.gridCells.append( (
                gridCell(frame, 1, y),
                gridCombobox(frame, 2, y, values=dataTypes),
                gridCell(frame, 3, y)) )
            y += 1
        y += 1
        
        # checkbox entries
        label(frame, 1, y, "Parameter Trace:")
        label(frame, 1, y + 3, "API Calls Trace:")
        label(frame, 2, y, "Variable Set Trace:")
        label(frame, 3, y, "Variables Trace:")
        self.checkboxes = (
           checkbox(frame, 1, y + 1, 
                    "Expression Result", 
                    "traceParameterExpressionResult"),
           checkbox(frame, 1, y + 2,
                    "Input Value", 
                    "traceParameterInputValue"),
           checkbox(frame, 1, y + 4, 
                    "Expression Source", 
                    "traceCallExpressionSource"),
           checkbox(frame, 1, y + 5, 
                    "Expression Code", 
                    "traceCallExpressionCode"),
           checkbox(frame, 1, y + 6, 
                    "Expression Evaluation", 
                    "traceCallExpressionEvaluation"),
           checkbox(frame, 1, y + 7,
                    "Expression Result", 
                    "traceCallExpressionResult"),

           checkbox(frame, 2, y + 1, 
                    "Expression Source", 
                    "traceVariableSetExpressionSource"),
           checkbox(frame, 2, y + 2, 
                    "Expression Code", 
                    "traceVariableSetExpressionCode"),
           checkbox(frame, 2, y + 3, 
                    "Expression Evaluation", 
                    "traceVariableSetExpressionEvaluation"),
           checkbox(frame, 2, y + 4,
                    "Expression Result", 
                    "traceVariableSetExpressionResult"),
           checkbox(frame, 2, y + 5,
                    "Assertion Result Counts", 
                    "traceAssertionResultCounts"),
           checkbox(frame, 2, y + 6,
                    "Assertion Satisfied [info]", 
                    "traceSatisfiedAssertions"),
           checkbox(frame, 2, y + 7,
                    "Assertion Unsatisfied [error]", 
                    "errorUnsatisfiedAssertions"),
           checkbox(frame, 2, y + 8,
                    "Assertion Unsatisfied [info]", 
                    "traceUnsatisfiedAssertions"),
           checkbox(frame, 2, y + 9,
                    "Formula Rules", 
                    "traceFormulaRules"),
           checkbox(frame, 2, y + 10,
                    "Evaluation Timing", 
                    "timeVariableSetEvaluation"),
           checkbox(frame, 3, y + 1, 
                    "Variable Dependencies", 
                    "traceVariablesDependencies"),
           checkbox(frame, 3, y + 2, 
                    "Variables Order", 
                    "traceVariablesOrder"),
           checkbox(frame, 3, y + 3, 
                    "Expression Source", 
                    "traceVariableExpressionSource"),
           checkbox(frame, 3, y + 4, 
                    "Expression Code", 
                    "traceVariableExpressionCode"),
           checkbox(frame, 3, y + 5, 
                    "Expression Evaluation", 
                    "traceVariableExpressionEvaluation"),
           checkbox(frame, 3, y + 6, 
                    "Expression Result", 
                    "traceVariableExpressionResult"),
           checkbox(frame, 3, y + 7, 
                    "Filter Winnowing", 
                    "traceVariableFilterWinnowing"),
           checkbox(frame, 3, y + 8, 
                    "Filters Result", 
                    "traceVariableFiltersResult")
        
           # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync
        
           )
        y += 11
        
        mainWin.showStatus(None)

        label(frame, 1, y, "IDs:")
        self.idsEntry = gridCell(frame, 1, y, options.get("runIDs"))
        self.idsEntry.grid(columnspan=2, padx=30)
        _w = 8 if self.modelManager.cntlr.isMac else 12
        okButton = Button(frame, text=_("OK"), width=_w, command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), width=_w, command=self.close)
        okButton.grid(row=y, column=3, sticky=W, pady=3)
        cancelButton.grid(row=y, column=3, sticky=E, pady=3, padx=3)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(1, weight=3)
        frame.columnconfigure(2, weight=1)
        frame.columnconfigure(3, weight=3)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 55
0
    def init_window(self):
        self.master.title("Viet Nam Sign Language Translator")
        self.font0 = TkFont.Font(self, size=12)
        self.font = TkFont.Font(self, size=14)
        self.style = Style()
        self.style.theme_use("clam")
        self.pack(fill=BOTH, expand=1)
        self.inputfilepath = StringVar()
        self.inputvideofile = StringVar()
        self.outputfilepath = StringVar()
        self.outputvideofile = StringVar()
        self.display_sign = StringVar()
        self.display_sequence = StringVar()

        #input file path
        frame1 = tk.Frame(self, relief=GROOVE, borderwidth=1)
        frame1.pack(fill=X)
        input_button = tk.Button(frame1,
                                 text='Input directory',
                                 bg='#b3b3b3',
                                 font=self.font,
                                 command=self.input_browser)
        input_button.pack(side=LEFT, padx=5, pady=5)
        self.inputfilepathText = Entry(frame1,
                                       textvariable=self.inputfilepath,
                                       font=self.font)
        self.inputfilepathText.pack(fill=X, padx=5, expand=True)

        #input video file
        frame2 = tk.Frame(self, relief=GROOVE, borderwidth=1)
        frame2.pack(fill=X)
        inputvideo_button = tk.Button(frame2,
                                      text='Input video file',
                                      bg="#b3b3b3",
                                      font=self.font,
                                      command=self.inputvideo_browser)
        inputvideo_button.pack(side=LEFT, padx=5, pady=5)
        self.inputvideofileText = Entry(frame2,
                                        textvariable=self.inputvideofile,
                                        font=self.font)
        self.inputvideofileText.pack(fill=X, padx=5, expand=True)

        #output file path
        frame3 = tk.Frame(self, relief=GROOVE, borderwidth=1)
        frame3.pack(fill=X)
        output_button = tk.Button(frame3,
                                  text='Output directory',
                                  bg="#b3b3b3",
                                  font=self.font,
                                  command=self.output_browser)
        output_button.pack(side=LEFT, padx=5, pady=5)
        self.outputfilepathText = Entry(frame3,
                                        textvariable=self.outputfilepath,
                                        font=self.font)
        self.outputfilepathText.pack(fill=X, padx=5, expand=True)

        #output video file
        frame9 = tk.Frame(self, relief=GROOVE, borderwidth=1)
        frame9.pack(fill=X)
        outputvideo_button = tk.Button(frame9,
                                       text='Output video file',
                                       bg="#b3b3b3",
                                       font=self.font,
                                       command=self.outputvideo_browser)
        outputvideo_button.pack(side=LEFT, padx=5, pady=5)
        self.outputvideofileText = Entry(frame9,
                                         textvariable=self.outputvideofile,
                                         font=self.font)
        self.outputvideofileText.pack(fill=X, padx=5, expand=True)

        #Mediapipe & open video & reset button
        frame4 = tk.Frame(self)
        frame4.pack(fill=X)
        inputvideo_button = tk.Button(frame4,
                                      text="Open input video",
                                      bg="#b3b3b3",
                                      font=self.font,
                                      command=self.open_invideo)
        inputvideo_button.grid(row=0, column=0)
        mediapipe_button = tk.Button(frame4,
                                     text="Hand Mediapipe Process",
                                     bg="#b3b3b3",
                                     font=self.font,
                                     command=self.hand_mediapipe)
        mediapipe_button.grid(row=0, column=1)
        outputvideo_button = tk.Button(frame4,
                                       text="Open output video",
                                       bg="#b3b3b3",
                                       font=self.font,
                                       command=self.open_outvideo)
        outputvideo_button.grid(row=0, column=2)
        reset_button = tk.Button(frame4,
                                 text="Reset",
                                 bg="#b3b3b3",
                                 font=self.font,
                                 command=self.reset)
        reset_button.grid(row=0, column=3)

        #Predict sign
        frame5 = tk.Frame(self, relief=GROOVE, borderwidth=1)
        frame5.pack(fill=X)
        predict_button = tk.Button(frame5,
                                   text="Predict sign",
                                   bg="#b3b3b3",
                                   font=self.font,
                                   command=self.sign_predict)
        predict_button.pack(side=LEFT, padx=5, pady=5)
        self.signText = Entry(frame5,
                              textvariable=self.display_sign,
                              font=self.font)
        self.signText.pack(fill=X, padx=5, expand=True)

        #Predict sequence
        frame6 = tk.Frame(self, relief=GROOVE, borderwidth=1)
        frame6.pack(fill=X)
        sequence_button = tk.Button(frame6,
                                    text="Predict sequence",
                                    bg="#b3b3b3",
                                    font=self.font,
                                    command=self.sequence_predict)
        sequence_button.pack(side=LEFT, padx=5, pady=5)
        self.sequenceText = Entry(frame6,
                                  textvariable=self.display_sequence,
                                  font=self.font)
        self.sequenceText.pack(fill=X, padx=5, expand=True)

        frame7 = Frame(self, relief=GROOVE, borderwidth=1)
        frame7.pack(fill=BOTH)
        self.my_label = tk.Label(frame7)
        self.my_label.pack()

        frame8 = tk.Frame(self)
        frame8.pack(fill=X)
        quit_button = tk.Button(frame8,
                                text='Close',
                                font=self.font0,
                                command=self.close_window,
                                bg="#b3b3b3")
        quit_button.pack(side=RIGHT, padx=5, pady=5)
class SearchDialogBase:
    '''Create most of a 3 or 4 row, 3 column search dialog.

    The left and wide middle column contain:
    1 or 2 labeled text entry lines (make_entry, create_entries);
    a row of standard Checkbuttons (make_frame, create_option_buttons),
    each of which corresponds to a search engine Variable;
    a row of dialog-specific Check/Radiobuttons (create_other_buttons).

    The narrow right column contains command buttons
    (make_button, create_command_buttons).
    These are bound to functions that execute the command.

    Except for command buttons, this base class is not limited to items
    common to all three subclasses.  Rather, it is the Find dialog minus
    the "Find Next" command, its execution function, and the
    default_command attribute needed in create_widgets. The other
    dialogs override attributes and methods, the latter to replace and
    add widgets.
    '''

    title = "Search Dialog"  # replace in subclasses
    icon = "Search"
    needwrapbutton = 1  # not in Find in Files

    def __init__(self, root, engine):
        '''Initialize root, engine, and top attributes.

        top (level widget): set in create_widgets() called from open().
        frame: container for all widgets in dialog.
        text (Text searched): set in open(), only used in subclasses().
        ent (ry): created in make_entry() called from create_entry().
        row (of grid): 0 in create_widgets(), +1 in make_entry/frame().
        default_command: set in subclasses, used in create_widgets().

        title (of dialog): class attribute, override in subclasses.
        icon (of dialog): ditto, use unclear if cannot minimize dialog.
        '''
        self.root = root
        self.bell = root.bell
        self.engine = engine
        self.top = None

    def open(self, text, searchphrase=None):
        "Make dialog visible on top of others and ready to use."
        self.text = text
        if not self.top:
            self.create_widgets()
        else:
            self.top.deiconify()
            self.top.tkraise()
        self.top.transient(text.winfo_toplevel())
        if searchphrase:
            self.ent.delete(0, "end")
            self.ent.insert("end", searchphrase)
        self.ent.focus_set()
        self.ent.selection_range(0, "end")
        self.ent.icursor(0)
        self.top.grab_set()

    def close(self, event=None):
        "Put dialog away for later use."
        if self.top:
            self.top.grab_release()
            self.top.transient('')
            self.top.withdraw()

    def create_widgets(self):
        '''Create basic 3 row x 3 col search (find) dialog.

        Other dialogs override subsidiary create_x methods as needed.
        Replace and Find-in-Files add another entry row.
        '''
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        _setup_dialog(top)
        self.top = top
        self.frame = Frame(top, padding="5px")
        self.frame.grid(sticky="nwes")
        top.grid_columnconfigure(0, weight=100)
        top.grid_rowconfigure(0, weight=100)

        self.row = 0
        self.frame.grid_columnconfigure(0, pad=2, weight=0)
        self.frame.grid_columnconfigure(1, pad=2, minsize=100, weight=100)

        self.create_entries()  # row 0 (and maybe 1), cols 0, 1
        self.create_option_buttons()  # next row, cols 0, 1
        self.create_other_buttons()  # next row, cols 0, 1
        self.create_command_buttons()  # col 2, all rows

    def make_entry(self, label_text, var):
        '''Return (entry, label), .

        entry - gridded labeled Entry for text entry.
        label - Label widget, returned for testing.
        '''
        label = Label(self.frame, text=label_text)
        label.grid(row=self.row, column=0, sticky="nw")
        entry = Entry(self.frame, textvariable=var, exportselection=0)
        entry.grid(row=self.row, column=1, sticky="nwe")
        self.row = self.row + 1
        return entry, label

    def create_entries(self):
        "Create one or more entry lines with make_entry."
        self.ent = self.make_entry("Find:", self.engine.patvar)[0]

    def make_frame(self, labeltext=None):
        '''Return (frame, label).

        frame - gridded labeled Frame for option or other buttons.
        label - Label widget, returned for testing.
        '''
        if labeltext:
            label = Label(self.frame, text=labeltext)
            label.grid(row=self.row, column=0, sticky="nw")
        else:
            label = ''
        frame = Frame(self.frame)
        frame.grid(row=self.row, column=1, columnspan=1, sticky="nwe")
        self.row = self.row + 1
        return frame, label

    def create_option_buttons(self):
        '''Return (filled frame, options) for testing.

        Options is a list of searchengine booleanvar, label pairs.
        A gridded frame from make_frame is filled with a Checkbutton
        for each pair, bound to the var, with the corresponding label.
        '''
        frame = self.make_frame("Options")[0]
        engine = self.engine
        options = [(engine.revar, "Regular expression"),
                   (engine.casevar, "Match case"),
                   (engine.wordvar, "Whole word")]
        if self.needwrapbutton:
            options.append((engine.wrapvar, "Wrap around"))
        for var, label in options:
            btn = Checkbutton(frame, variable=var, text=label)
            btn.pack(side="left", fill="both")
        return frame, options

    def create_other_buttons(self):
        '''Return (frame, others) for testing.

        Others is a list of value, label pairs.
        A gridded frame from make_frame is filled with radio buttons.
        '''
        frame = self.make_frame("Direction")[0]
        var = self.engine.backvar
        others = [(1, 'Up'), (0, 'Down')]
        for val, label in others:
            btn = Radiobutton(frame, variable=var, value=val, text=label)
            btn.pack(side="left", fill="both")
        return frame, others

    def make_button(self, label, command, isdef=0):
        "Return command button gridded in command frame."
        b = Button(self.buttonframe,
                   text=label,
                   command=command,
                   default=isdef and "active" or "normal")
        cols, rows = self.buttonframe.grid_size()
        b.grid(pady=1, row=rows, column=0, sticky="ew")
        self.buttonframe.grid(rowspan=rows + 1)
        return b

    def create_command_buttons(self):
        "Place buttons in vertical command frame gridded on right."
        f = self.buttonframe = Frame(self.frame)
        f.grid(row=0, column=2, padx=2, pady=2, ipadx=2, ipady=2)

        b = self.make_button("Close", self.close)
        b.lower()
def make_comp_widgets(frame: ttk.Frame):
    """Create widgets for the compiler settings pane.

    These are generally things that are aesthetic, and to do with the file and
    compilation process.
    """
    frame.columnconfigure(0, weight=1)

    thumb_frame = ttk.LabelFrame(
        frame,
        text=_('Thumbnail'),
        labelanchor=N,
    )
    thumb_frame.grid(row=0, column=0, sticky=EW)
    thumb_frame.columnconfigure(0, weight=1)

    UI['thumb_auto'] = ttk.Radiobutton(
        thumb_frame,
        text=_('Auto'),
        value='AUTO',
        variable=chosen_thumb,
        command=set_screen_type,
    )

    UI['thumb_peti'] = ttk.Radiobutton(
        thumb_frame,
        text=_('PeTI'),
        value='PETI',
        variable=chosen_thumb,
        command=set_screen_type,
    )

    UI['thumb_custom'] = ttk.Radiobutton(
        thumb_frame,
        text=_('Custom:'),
        value='CUST',
        variable=chosen_thumb,
        command=set_screen_type,
    )

    UI['thumb_label'] = ttk.Label(
        thumb_frame,
        anchor=CENTER,
        cursor=utils.CURSORS['link'],
    )
    UI['thumb_label'].bind(
        utils.EVENTS['LEFT'],
        find_screenshot,
    )

    UI['thumb_cleanup'] = ttk.Checkbutton(
        thumb_frame,
        text=_('Cleanup old screenshots'),
        variable=cleanup_screenshot,
        command=make_setter('Screenshot', 'del_old', cleanup_screenshot),
    )

    UI['thumb_auto'].grid(row=0, column=0, sticky='W')
    UI['thumb_peti'].grid(row=0, column=1, sticky='W')
    UI['thumb_custom'].grid(row=1, column=0, columnspan=2, sticky='NEW')
    UI['thumb_cleanup'].grid(row=3, columnspan=2, sticky='W')
    add_tooltip(
        UI['thumb_auto'],
        _("Override the map image to use a screenshot automatically taken "
          "from the beginning of a chamber. Press F5 to take a new "
          "screenshot. If the map has not been previewed recently "
          "(within the last few hours), the default PeTI screenshot "
          "will be used instead."))
    add_tooltip(UI['thumb_peti'],
                _("Use the normal editor view for the map preview image."))
    custom_tooltip = _(
        "Use a custom image for the map preview image. Click the "
        "screenshot to select.\n"
        "Images will be converted to JPEGs if needed.")
    add_tooltip(
        UI['thumb_custom'],
        custom_tooltip,
    )

    add_tooltip(
        UI['thumb_label'],
        custom_tooltip,
    )

    add_tooltip(
        UI['thumb_cleanup'],
        _('Automatically delete unused Automatic screenshots. '
          'Disable if you want to keep things in "portal2/screenshots". '))

    if chosen_thumb.get() == 'CUST':
        # Show this if the user has set it before
        UI['thumb_label'].grid(row=2, column=0, columnspan=2, sticky='EW')
    set_screenshot()  # Load the last saved screenshot

    vrad_frame = ttk.LabelFrame(
        frame,
        text=_('Lighting:'),
        labelanchor=N,
    )
    vrad_frame.grid(row=1, column=0, sticky=EW)

    UI['light_fast'] = ttk.Radiobutton(
        vrad_frame,
        text=_('Fast'),
        value=0,
        variable=vrad_light_type,
        command=make_setter('General', 'vrad_force_full', vrad_light_type),
    )
    UI['light_fast'].grid(row=0, column=0)
    UI['light_full'] = ttk.Radiobutton(
        vrad_frame,
        text=_('Full'),
        value=1,
        variable=vrad_light_type,
        command=make_setter('General', 'vrad_force_full', vrad_light_type),
    )
    UI['light_full'].grid(row=0, column=1)

    add_tooltip(
        UI['light_fast'],
        _("Compile with lower-quality, fast lighting. This speeds "
          "up compile times, but does not appear as good. Some "
          "shadows may appear wrong.\n"
          "When publishing, this is ignored."))
    add_tooltip(
        UI['light_full'],
        _("Compile with high-quality lighting. This looks correct, "
          "but takes longer to compute. Use if you're arranging lights. "
          "When publishing, this is always used."))

    packfile_enable = ttk.Checkbutton(
        frame,
        text=_('Dump packed files to:'),
        variable=packfile_dump_enable,
        command=set_pack_dump_enabled,
    )

    packfile_frame = ttk.LabelFrame(
        frame,
        labelwidget=packfile_enable,
    )
    packfile_frame.grid(row=2, column=0, sticky=EW)

    UI['packfile_filefield'] = packfile_filefield = FileField(
        packfile_frame,
        is_dir=True,
        loc=COMPILE_CFG.get_val('General', 'packfile_dump_dir', ''),
        callback=set_pack_dump_dir,
    )
    packfile_filefield.grid(row=0, column=0, sticky=EW)
    packfile_frame.columnconfigure(0, weight=1)
    ttk.Frame(packfile_frame).grid(row=1)

    set_pack_dump_enabled()

    add_tooltip(
        packfile_enable,
        _("When compiling, dump all files which were packed into the map. Useful"
          " if you're intending to edit maps in Hammer."))

    count_frame = ttk.LabelFrame(
        frame,
        text=_('Last Compile:'),
        labelanchor=N,
    )

    count_frame.grid(row=7, column=0, sticky=EW)
    count_frame.columnconfigure(0, weight=1)
    count_frame.columnconfigure(2, weight=1)

    ttk.Label(
        count_frame,
        text=_('Entity'),
        anchor=N,
    ).grid(row=0, column=0, columnspan=3, sticky=EW)

    UI['count_entity'] = ttk.Progressbar(
        count_frame,
        maximum=100,
        variable=count_entity,
        length=120,
    )
    UI['count_entity'].grid(
        row=1,
        column=0,
        columnspan=3,
        sticky=EW,
        padx=5,
    )

    ttk.Label(
        count_frame,
        text=_('Overlay'),
        anchor=CENTER,
    ).grid(row=2, column=0, sticky=EW)
    UI['count_overlay'] = ttk.Progressbar(
        count_frame,
        maximum=100,
        variable=count_overlay,
        length=50,
    )
    UI['count_overlay'].grid(row=3, column=0, sticky=EW, padx=5)

    UI['refresh_counts'] = SubPane.make_tool_button(
        count_frame,
        png.png('icons/tool_sub', resize_to=16),
        refresh_counts,
    )
    UI['refresh_counts'].grid(row=3, column=1)
    add_tooltip(
        UI['refresh_counts'],
        _("Refresh the compile progress bars. Press after a compile has been "
          "performed to show the new values."),
    )

    ttk.Label(
        count_frame,
        text='Brush',
        anchor=CENTER,
    ).grid(row=2, column=2, sticky=EW)
    UI['count_brush'] = ttk.Progressbar(
        count_frame,
        maximum=100,
        variable=count_brush,
        length=50,
    )
    UI['count_brush'].grid(row=3, column=2, sticky=EW, padx=5)

    for wid_name in ('count_overlay', 'count_entity', 'count_brush'):
        # Add in tooltip logic to the widgets.
        add_tooltip(UI[wid_name])

    refresh_counts(reload=False)
def make_map_widgets(frame: ttk.Frame):
    """Create widgets for the map settings pane.

    These are things which mainly affect the geometry or gameplay of the map.
    """
    frame.columnconfigure(0, weight=1)

    voice_frame = ttk.LabelFrame(
        frame,
        text=_('Voicelines:'),
        labelanchor=NW,
    )
    voice_frame.grid(row=1, column=0, sticky=EW)

    UI['voice_priority'] = voice_priority = ttk.Checkbutton(
        voice_frame,
        text=_("Use voiceline priorities"),
        variable=VOICE_PRIORITY_VAR,
        command=make_setter('General', 'use_voice_priority',
                            VOICE_PRIORITY_VAR),
    )
    voice_priority.grid(row=0, column=0)
    add_tooltip(
        voice_priority,
        _("Only choose the highest-priority voicelines. This means more "
          "generic lines will can only be chosen if few test elements are in "
          "the map. If disabled any applicable lines will be used."),
    )

    elev_frame = ttk.LabelFrame(
        frame,
        text=_('Spawn at:'),
        labelanchor=N,
    )

    elev_frame.grid(row=2, column=0, sticky=EW)
    elev_frame.columnconfigure(0, weight=1)
    elev_frame.columnconfigure(1, weight=1)

    UI['elev_preview'] = ttk.Radiobutton(
        elev_frame,
        text=_('Entry Door'),
        value=0,
        variable=start_in_elev,
        command=make_setter('General', 'spawn_elev', start_in_elev),
    )

    UI['elev_elevator'] = ttk.Radiobutton(
        elev_frame,
        text=_('Elevator'),
        value=1,
        variable=start_in_elev,
        command=make_setter('General', 'spawn_elev', start_in_elev),
    )

    UI['elev_preview'].grid(row=0, column=0, sticky=W)
    UI['elev_elevator'].grid(row=0, column=1, sticky=W)

    add_tooltip(
        UI['elev_elevator'],
        _("When previewing in SP, spawn inside the entry elevator. "
          "This also disables the map restarts when you reach the "
          "exit door. Use this to examine the entry and exit corridors."))
    add_tooltip(
        UI['elev_preview'],
        _("When previewing in SP, spawn just before the entry door. "
          "When you reach the exit door, the map will restart."))

    corr_frame = ttk.LabelFrame(
        frame,
        width=18,
        text=_('Corridor:'),
        labelanchor=N,
    )
    corr_frame.grid(row=3, column=0, sticky=EW)
    corr_frame.columnconfigure(0, weight=1)
    corr_frame.columnconfigure(1, weight=1)

    load_corridors()

    UI['corr_sp_entry'] = make_corr_combo(
        corr_frame,
        'sp_entry',
        width=9,
    )

    UI['corr_sp_exit'] = make_corr_combo(
        corr_frame,
        'sp_exit',
        width=9,
    )

    UI['corr_coop'] = make_corr_combo(
        corr_frame,
        'coop',
        width=9,
    )

    UI['corr_sp_entry'].grid(row=1, column=0, sticky=EW)
    UI['corr_sp_exit'].grid(row=1, column=1, sticky=EW)
    UI['corr_coop'].grid(row=2, column=1, sticky=EW)
    ttk.Label(
        corr_frame,
        text=_('SP Entry:'),
        anchor=CENTER,
    ).grid(row=0, column=0, sticky=EW)
    ttk.Label(
        corr_frame,
        text=_('SP Exit:'),
        anchor=CENTER,
    ).grid(row=0, column=1, sticky=EW)
    ttk.Label(
        corr_frame,
        text=_('Coop:'),
        anchor=CENTER,
    ).grid(row=2, column=0, sticky=EW)

    model_frame = ttk.LabelFrame(
        frame,
        text=_('Player Model (SP):'),
        labelanchor=N,
    )
    model_frame.grid(row=4, column=0, sticky=EW)
    UI['player_mdl'] = ttk.Combobox(
        model_frame,
        exportselection=0,
        textvariable=player_model_var,
        values=[PLAYER_MODELS[mdl] for mdl in PLAYER_MODEL_ORDER],
        width=20,
    )
    # Users can only use the dropdown
    UI['player_mdl'].state(['readonly'])
    UI['player_mdl'].grid(row=0, column=0, sticky=EW)

    UI['player_mdl'].bind('<<ComboboxSelected>>', set_model)
    model_frame.columnconfigure(0, weight=1)
Exemplo n.º 59
0
    def __init__(self,
                 mainWin,
                 openType,
                 filesource,
                 filenames,
                 title,
                 colHeader,
                 showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            metadata = filesource.file(filesource.url + os.sep +
                                       TAXONOMY_PACKAGE_FILE_NAME)[0]

            try:
                self.nameToUrls = parseTxmyPkg(mainWin, metadata)
            except Exception as e:
                self.close()
                err = _(
                    "Failed to parse metadata; the underlying error was: {0}"
                ).format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return

        mainWin.showStatus(None)

        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        if showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y,
                                    column=0,
                                    sticky=(S, W),
                                    pady=3,
                                    padx=3)

        self.loadTreeView(openType, colHeader, title)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Exemplo n.º 60
0
    def __init__(self,
                 parent,
                 title,
                 host=None,
                 realm=None,
                 useOsProxy=None,
                 urlAddr=None,
                 urlPort=None,
                 user=None,
                 password=None,
                 database=None,
                 showUrl=False,
                 showUser=False,
                 showHost=True,
                 showRealm=True,
                 showDatabase=False):
        super(DialogUserPassword, self).__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.transient(self.parent)
        self.title(title)
        self.urlAddrVar = StringVar()
        self.urlAddrVar.set(urlAddr if urlAddr else "")
        self.urlPortVar = StringVar()
        self.urlPortVar.set(urlPort if urlPort else "")
        self.userVar = StringVar()
        self.userVar.set(user if user else "")
        self.passwordVar = StringVar()
        self.passwordVar.set(password if password else "")
        self.databaseVar = StringVar()
        self.databaseVar.set(database if database else "")

        frame = Frame(self)
        y = 0
        if showHost:
            hostLabel = Label(frame, text=_("Host:"), underline=0)
            hostDisplay = Label(frame, text=host, width=30)
            if host and len(host) > 30:
                ToolTip(hostDisplay, text=host, wraplength=240)
            hostLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            hostDisplay.grid(row=y,
                             column=1,
                             columnspan=4,
                             sticky=EW,
                             pady=3,
                             padx=3)
            y += 1
        if showRealm:
            realmLabel = Label(frame, text=_("Realm:"), underline=0)
            realmDisplay = Label(frame, text=realm, width=25)
            if realm and len(realm) > 30:
                ToolTip(realmDisplay, text=realm, wraplength=240)
            realmLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            realmDisplay.grid(row=y,
                              column=1,
                              columnspan=4,
                              sticky=EW,
                              pady=3,
                              padx=3)
            y += 1
        self.enabledWidgets = []
        if useOsProxy is not None:
            if sys.platform.startswith("win"):
                hostProxy = _('Microsoft Windows Internet Settings')
            elif sys.platform in ("darwin", "macos"):
                hostProxy = _('Mac OS X System Configuration')
            else:  # linux/unix
                hostProxy = _('environment variables')
            useOsProxyCb = checkbox(
                frame,
                0,
                y,
                text=_("Use proxy server of {0}").format(hostProxy))
            useOsProxyCb.grid(columnspan=5)
            useOsProxyCb.valueVar.set(useOsProxy)
            ToolTip(useOsProxyCb,
                    text=_(
                        "Check to use {0} \n"
                        "Uncheck to specify: \n"
                        "   No proxy if URL address is left blank, \n"
                        "   Proxy via URL address if it is not blank, \n"
                        "       with user and password (if provided)").format(
                            hostProxy),
                    wraplength=360)
            self.useOsProxyCb = useOsProxyCb
            useOsProxyCb.valueVar.trace("w", self.setEnabledState)

            y += 1
        if showUrl:
            urlAddrLabel = Label(frame, text=_("Address:"), underline=0)
            urlAddrEntry = Entry(frame, textvariable=self.urlAddrVar, width=16)
            urlPortLabel = Label(frame, text=_("Port:"), underline=0)
            urlPortEntry = Entry(frame, textvariable=self.urlPortVar, width=5)
            urlAddrEntry.focus_set()
            urlAddrLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            urlAddrEntry.grid(row=y,
                              column=1,
                              columnspan=2,
                              sticky=EW,
                              pady=3,
                              padx=3)
            urlPortLabel.grid(row=y, column=3, sticky=W, pady=3, padx=3)
            urlPortEntry.grid(row=y, column=4, sticky=EW, pady=3, padx=3)
            ToolTip(urlAddrEntry,
                    text=_("Enter URL address and port number \n"
                           "  e.g., address: 168.1.2.3 port: 8080 \n"
                           "  or address: proxy.myCompany.com port: 8080 \n"
                           "  or leave blank to specify no proxy server"),
                    wraplength=360)
            self.enabledWidgets.append(urlAddrEntry)
            self.enabledWidgets.append(urlPortEntry)
            y += 1
        userLabel = Label(frame, text=_("User:"******"Password:"******"*")
        passwordLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
        passwordEntry.grid(row=y,
                           column=1,
                           columnspan=4,
                           sticky=EW,
                           pady=3,
                           padx=3)
        self.enabledWidgets.append(passwordEntry)
        y += 1
        if showDatabase:
            urlDatabaseLabel = Label(frame, text=_("Database:"), underline=0)
            urlDatabaseEntry = Entry(frame,
                                     textvariable=self.databaseVar,
                                     width=25)
            urlDatabaseLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            urlDatabaseEntry.grid(row=y,
                                  column=1,
                                  columnspan=4,
                                  sticky=EW,
                                  pady=3,
                                  padx=3)
            ToolTip(urlAddrEntry,
                    text=_("Enter database name (optional) or leave blank"),
                    wraplength=360)
            self.enabledWidgets.append(urlDatabaseEntry)
            y += 1
        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=E, pady=3)
        cancelButton.grid(row=y,
                          column=3,
                          columnspan=2,
                          sticky=EW,
                          pady=3,
                          padx=3)
        y += 1

        if useOsProxy is not None:
            self.setEnabledState()

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(1, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)