コード例 #1
0
ファイル: checkbutton.py プロジェクト: zXpp/TutorialForPython
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        #窗口大小位置
        self.master.geometry("600x400+100+400")  #长x宽+x+y
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.helloLabel = Label(self, text='Hello, world!\n')
        self.helloLabel.pack()

        self.c1 = Checkbutton(self,
                              text="1",
                              command=lambda: self.helloLabel.config(
                                  text=self.helloLabel["text"] + "1被选中了奇数次\n"))
        self.c1.pack()
        self.c2 = Checkbutton(self,
                              text="2",
                              command=lambda: self.helloLabel.config(
                                  text=self.helloLabel["text"] + "2被选中了奇数次\n"))
        self.c2.pack()
        self.quitButton = Button(self,
                                 text='Quit',
                                 fg="red",
                                 command=self.quit)
        self.quitButton.pack()
コード例 #2
0
class PasswordDialog(Dialog):

    def __init__(self, title, prompt, parent):
        self.prompt = prompt
        Dialog.__init__(self, parent, title)

    def body(self, master):
        from tkinter import Label
        from tkinter import Entry
        from tkinter import Checkbutton
        from tkinter import IntVar
        from tkinter import W

        self.checkVar = IntVar()

        Label(master, text=self.prompt).grid(row=0, sticky=W)

        self.e1 = Entry(master)

        self.e1.grid(row=0, column=1)

        self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar)
        self.cb.pack()
        self.cb.grid(row=1, columnspan=2, sticky=W)
        self.e1.configure(show='*')

    def apply(self):
        self.result = (self.e1.get(), self.checkVar.get() == 1)
コード例 #3
0
    def _initialise_tool_bar(self):
        """For private use. Initialise the tool bar"""
        self.toolbar = Frame(self, bd=1, relief="raised")
        self.toolbar.pack(fill="x")

        self.select_leaves_button = HoverButton(
            self.toolbar,
            text="Select leaves",
            relief="raised",
            command=self._select_leaves,
            state="disabled",
            tooltip_text=
            "Enter set leaves to be displayed in trees. By default, all labelled leaves in network are selected"
        )

        self.draw_button = HoverButton(
            self.toolbar,
            text="Draw trees/graph",
            relief="raised",
            command=self.generate_trees_graph,
            state="disabled",
            tooltip_text="Draw embedded/input trees or rSPR graph")

        self.graphics_enabled = IntVar()
        self.graphics = False
        graphics_check_box = Checkbutton(self.toolbar,
                                         text="Enable graphics",
                                         variable=self.graphics_enabled,
                                         command=self.set_graphics)
        graphics_check_box.pack(side="right", padx=(0, 10))
        ToolTip(
            graphics_check_box,
            "Enable graph visualisation for the next entered network/trees")
コード例 #4
0
 def _create_widgets(self) -> None:
     # settings
     settings_frame_parent = Frame(self, bg=CONFIG['colors']['menu'])
     settings_frame_child = Frame(settings_frame_parent,
                                  bg=CONFIG['colors']['menu'])
     tips_lab = Label(settings_frame_child,
                      text='Tips:',
                      bg=CONFIG['colors']['menu'],
                      font=CONFIG['font']['XS'])
     mode_check = Checkbutton(settings_frame_child,
                              variable=self._mode_var,
                              font=CONFIG['font']['XS'],
                              bg=CONFIG['colors']['menu'])
     rounds_count_lab = Label(settings_frame_child,
                              text='Rounds:',
                              bg=CONFIG['colors']['menu'],
                              font=CONFIG['font']['XS'])
     rounds_count_spinbox = Spinbox(settings_frame_child,
                                    from_=1,
                                    to=100,
                                    width=3,
                                    textvariable=self._rounds_count_var,
                                    font=CONFIG['font']['M'])
     boxes_count_lab = Label(settings_frame_child,
                             text='Boxes:',
                             bg=CONFIG['colors']['menu'],
                             font=CONFIG['font']['XS'])
     boxes_count_spinbox = Spinbox(settings_frame_child,
                                   from_=3,
                                   to=10,
                                   width=3,
                                   textvariable=self._boxes_count_var,
                                   font=CONFIG['font']['M'])
     start_but = Button(settings_frame_child,
                        text='START',
                        command=self._controller.start,
                        font=CONFIG['font']['S'])
     # guess boxes
     score_frame = Frame(self)
     self._score_lab = Label(score_frame,
                             bg=CONFIG['colors']['score'],
                             text='Round: 00 | Wins: 00 | Fails: 00',
                             font=CONFIG['font']['M'])
     # boxes
     frame_boxes_parent = Frame(self)
     self._frame_boxes_child = Frame(frame_boxes_parent)
     # PACKED
     settings_frame_parent.pack(fill='x')
     settings_frame_child.pack(expand=True, padx=5, pady=5)
     tips_lab.pack(side='left')
     mode_check.pack(side='left')
     rounds_count_lab.pack(side='left')
     rounds_count_spinbox.pack(side='left', fill='y')
     boxes_count_lab.pack(side='left')
     boxes_count_spinbox.pack(side='left', fill='y')
     start_but.pack(side='left', fill='y', padx=5)
     score_frame.pack(fill='x')
     self._score_lab.pack(fill='x')
     frame_boxes_parent.pack(fill='both', expand=True)
     self._frame_boxes_child.pack(expand=True, padx=20, pady=20)
コード例 #5
0
    def __init__(self, master):
        Frame.__init__(self, master)

        self._value = os.getcwd()
        self._var = StringVar(self)
        self._var.set(self._value)
        self._var.trace('w', self._validate)

        label = Label(self, text="Root:")
        label.pack(side=LEFT)
        self._entry = Entry(self, textvariable=self._var)
        self._entry.pack(side=LEFT, fill=X, expand=True)

        self._recursive_var = BooleanVar()
        recursive_cb = Checkbutton(self, text='Recursive', variable=self._recursive_var)
        recursive_cb.pack(side=LEFT)
        self._recursive_var.trace('w', self._validate)
        
        open_button = Button(self, text="Open", command=self._select_root)
        open_button.pack(side=LEFT)
        
        refresh_button = Button(self, text="Refresh", command=self._refresh)
        refresh_button.pack(side=LEFT)

        repad(self, 'padx', 0, 5)
コード例 #6
0
class CheckBox:
    def __init__(self, root, text: str, x: int, y: int):
        self.varChecked = BooleanVar()
        self.text = text
        self.checkbox = Checkbutton(root,
                                    text=self.text,
                                    variable=self.varChecked,
                                    onvalue=True,
                                    offvalue=False)
        self.x = x
        self.y = y

        self.checkbox.pack()
        self.checkbox.place(x=self.x, y=self.y)

    @property
    def command(self):
        return self.command

    @command.setter
    def command(self, command):
        self.checkbox['command'] = command

    def isChecked(self):
        return True if self.varChecked.get() else False

    def check(self):
        self.checkbox.select()

    def uncheck(self):
        self.checkbox.deselect()
コード例 #7
0
    def ask_for_object_classes(self):

        window = Toplevel(self.root)
        window.wm_title("Choose object classes to detect?")
        window.resizable(width=False, height=False)
#        instruct.geometry('{}x{}'.format(500, 100))
        window.geometry('{}x{}'.format(200, 320))
#        time.config(bg='lightgreen')
        window.attributes('-topmost', True)
        
        label1 = Label(window, text="Choose object classes to detect?")
        label1.pack(side="top", padx="10", pady="5")

        self.object_classes_to_detect = {key:IntVar(value=value) for key, value in self.object_classes_to_detect.items()}
        
        for key, value in self.object_classes_to_detect.items():
            c = Checkbutton(window, text = key, variable = value, onvalue = 1, offvalue = 0)
            c.select()
            c.pack(side="top", anchor=W, padx="10", pady="5")
        
        btn1 = Button(window, text="Save", command=lambda *args: self.set_classes(window))
        btn1.pack(side="top", fill="both", expand="yes", padx="10", pady="5")
        
        
        self.root.wait_window(window)
コード例 #8
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        shift = StringVar()
        known = BooleanVar()   # true -> shift key known

        self.columnconfigure(0, weight=1, pad=5)
        self.columnconfigure(1, weight=1, pad=5)

        self.rowconfigure(0, pad=5)
        self.rowconfigure(1, pad=5)
        self.rowconfigure(2, weight=1, pad=5)
        self.rowconfigure(3, pad=5)
        self.rowconfigure(4, weight=1, pad=5)

        # Title
        bbutton = Button(self, text="<", command=lambda: controller.show_frame("MainPage"))
        bbutton.grid(row=0, column=0, padx=10, sticky=W)
        title = Label(self, text="Caesar Cipher")
        title.grid(row=0, columnspan=2, padx=10)

        # Shift Key
        sframe = Frame(self)
        sentry = Entry(sframe, textvariable=shift, width=55)
        sentry.pack(side=LEFT)
        sentry.insert(0, "Shift key")
        cb = Checkbutton(sframe, text="Unknown key", variable=known)
        cb.select()
        cb.pack(side=RIGHT, padx=10)
        sframe.grid(row=1, columnspan=2, padx=10, sticky=W+E)

        # Text input
        tinput = Text(self, wrap=WORD)
        tinput.grid(row=2, columnspan=2, padx=10, pady=10, sticky=N+E+S+W)
        scrolli = Scrollbar(self, command=tinput.yview)
        tinput.configure(yscrollcommand=scrolli.set)
        scrolli.grid(row=2, column=1, pady=10, sticky=N+S+E)
        tinput.insert(1.0, "Input")
        tinput.bind("<Control-Key-a>", select_all)  # select-all Windows/Linux
        tinput.bind("<Command-Key-a>", select_all)  # select-all Mac

        # Encode/Decode buttons
        ebutton = Button(self, text="Encode", width=15)
        ebutton.grid(row=3, column=0, padx=10, sticky=E)
        ebutton.configure(command=lambda: self.encode_prep(tinput.get(1.0, 'end-1c'), shift.get()))
        dbutton = Button(self, text="Decode", width=15)
        dbutton.grid(row=3, column=1, padx=10, sticky=W)
        dbutton.configure(command=lambda: self.decode_prep(tinput.get(1.0, 'end-1c'), shift.get(), not known.get()))

        # Output box
        self.output = Text(self, wrap=WORD)
        self.output.grid(row=4, columnspan=2, padx=10, pady=10, sticky=N+E+S+W)
        self.output.bind("<1>", lambda event: self.output.focus_set())
        scrollo = Scrollbar(self, command=self.output.yview)
        scrollo.grid(row=4, column=1, pady=10, sticky=N+S+E)
        self.output.configure(yscrollcommand=scrollo.set)
        self.output.insert(1.0, "Output")
        self.output.configure(state="disabled")
        self.output.bind("<Control-Key-a>", select_all)    # select-all Windows/Linux
        self.output.bind("<Command-Key-a>", select_all)    # select-all Mac
コード例 #9
0
ファイル: password_dialog.py プロジェクト: WaffleTime/GUIDE
class PasswordDialog(Dialog):

    def __init__(self, title, prompt, parent):
        self.prompt = prompt
        Dialog.__init__(self, parent, title)

    def body(self, master):
        from tkinter import Label
        from tkinter import Entry
        from tkinter import Checkbutton
        from tkinter import IntVar
        from tkinter import W

        self.checkVar = IntVar()

        Label(master, text=self.prompt).grid(row=0, sticky=W)

        self.e1 = Entry(master)

        self.e1.grid(row=0, column=1)

        self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar)
        self.cb.pack()
        self.cb.grid(row=1, columnspan=2, sticky=W)
        self.e1.configure(show='*')

    def apply(self):
        self.result = (self.e1.get(), self.checkVar.get() == 1)
コード例 #10
0
ファイル: components.py プロジェクト: mechbear14/space-app
class Filter:
    def __init__(self, master, map_object):
        self.canvas = None
        self.map_object = map_object
        self.draw_freq_checkbox = Checkbutton(
            master,
            anchor=W,
            text="Frequent routes",
            variable=self.map_object.show_route,
            command=self.update_map)
        self.draw_buoys_checkbox = Checkbutton(
            master,
            anchor=W,
            text="Buoys",
            variable=self.map_object.show_buoys,
            command=self.update_buoy)
        self.draw_freq_checkbox.pack(fill=X)
        self.draw_buoys_checkbox.pack(fill=X)

    def set_control_canvas(self, canvas):
        self.canvas = canvas

    def update_map(self):
        if self.map_object.show_route.get():
            self.map_object.set_image("route", self.canvas.canvas)
        else:
            self.map_object.set_image("map", self.canvas.canvas)

    def update_buoy(self):
        self.map_object.set_buoys(self.canvas.canvas,
                                  self.map_object.show_buoys.get(),
                                  self.canvas.translate)
コード例 #11
0
ファイル: cover.py プロジェクト: sanshao27/spiders-1
    def __init__(self):
        self.path = None
        ''''''

        top = Toplevel()
        top.title('生成封面')
        w = 300
        h = 200
        ws = top.winfo_screenwidth()
        hs = top.winfo_screenheight()
        # 计算 x, y 位置
        x = (ws / 2) - (w / 2)
        top.geometry('%dx%d+%d+%d' % (w, h, x, 100))
        ''''''

        clupValue = IntVar()
        clipButton = Checkbutton(top,
                                 text="完成后打开文件夹",
                                 onvalue=1,
                                 offvalue=0,
                                 height=1,
                                 variable=clupValue)
        clipButton.pack(side='top', expand='no', fill=None)
        clupValue.set(1)

        closeValue = IntVar()
        clipButton = Checkbutton(top,
                                 text="完成后关闭界面",
                                 onvalue=1,
                                 offvalue=0,
                                 height=1,
                                 variable=closeValue)
        clipButton.pack(side='top', expand='no', fill=None)
        closeValue.set(1)

        Button(top, bd=1, bg=None, text='选择文件夹',
               command=self.selectPath).pack(side='top')

        path = StringVar(top, value='download')
        inputPath = Entry(top, bd=0, textvariable=path, state='readonly')
        inputPath.pack(side='top')
        path.set('请选择文件夹')

        progressText = StringVar()
        progress = Label(top, text="请选择文件夹", textvariable=progressText)
        progress.pack(side='top')
        progressText.set('0/0')
        ''''''

        self.top = top
        self.progressText = progressText
        self.inputPath = inputPath
        self.path = path
        self.clupValue = clupValue
        self.closeValue = closeValue

        self.files = []

        top.mainloop()
コード例 #12
0
ファイル: GrepDialog.py プロジェクト: belzner/idle-errors-uap
    def create_other_buttons(self):
        f = self.make_frame()[0]

        btn = Checkbutton(f, anchor="w",
                variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.select()
コード例 #13
0
ファイル: extraOptionsGUI.py プロジェクト: Gink-k/VkMusic
    def __init__(self,
                 parent=None,
                 myBtn=Button,
                 extraParams={},
                 maxSize=(300, 200),
                 **options):
        Toplevel.__init__(self, parent, **options)
        fname = os.path.join(resFileName, 'extra_bg2.jpg')

        self.extraParams = extraParams
        self.bg_image = PhotoImage(file=fname)

        canvas = Canvas(self,
                        width=maxSize[0],
                        height=maxSize[1],
                        highlightthickness=0)
        canvas.pack(side='top', fill='both', expand='yes')
        canvas.create_image(0, 0, image=self.bg_image, anchor='nw')

        self.mkDirVar = IntVar()
        mkDirChBtn = Checkbutton(canvas,
                                 text='',
                                 variable=self.mkDirVar,
                                 command=self.setMkDirParams)
        mkDirChBtn.pack()
        canvas.create_window(40, 50, window=mkDirChBtn)
        canvas.create_text(125,
                           50,
                           font=("Times", 11),
                           text='Создать папку "Music"')

        self.reverseVar = IntVar()
        reverseChBtn = Checkbutton(canvas,
                                   text='',
                                   variable=self.reverseVar,
                                   command=self.setReverseParams)
        reverseChBtn.pack()
        canvas.create_window(40, 90, window=reverseChBtn)
        canvas.create_text(175,
                           90,
                           font=("Times", 11),
                           text='Реверсировать выделение композиций')

        dirBtn = myBtn(canvas,
                       text='Папка для закачки',
                       command=self.setDirectory)
        dirBtn.pack()
        canvas.create_window(100, 170, height=30, window=dirBtn)

        qBtn = myBtn(canvas, text='ок', command=self.destroy)
        qBtn.pack()
        canvas.create_window(250, 170, height=30, width=40, window=qBtn)

        self.setInitSetting()

        self.grab_set()
        self.focus_set()
        self.wait_window()
コード例 #14
0
    def display(self, frame):
        ''' Displays a checkbox that can be marked for recording '''

        # create a top level
        level = Toplevel(frame)

        # create a radio button for the recording
        checkbox = Checkbutton(level, text="Record", variable=self.recordvar)
        checkbox.pack()
コード例 #15
0
 def _pack_draw_fit_button(self, master):
     checkbutton_var = IntVar()
     toggle_function = partial(self._toggle_draw_fit,
                               checkbutton_var=checkbutton_var)
     b = Checkbutton(master,
                     text='Draw Fit',
                     command=toggle_function,
                     variable=checkbutton_var)
     b.pack()
コード例 #16
0
    def _add_option(self, name, description, value=False):
        var = BooleanVar()
        self._vars[name] = var
        
        var.set(value)
        var.trace('w', self._options_update)

        cb = Checkbutton(self, text=description, variable=var)
        cb.pack(side=LEFT)
コード例 #17
0
 def __init__(self, text=None, default="", *args, **kwargs):
     command = kwargs.pop("command") if kwargs.get("command") else None
     ttk.Frame.__init__(self, *args, **kwargs)
     self.var = IntVar()
     self.var.set(default)
     entry = Checkbutton(self, variable=self.var, command=command)
     entry.pack(side="right", fill="x", expand=False, padx=2)
     label = Label(self, text=text)
     label.pack(side="left", fill=None, padx=2, expand=False)
コード例 #18
0
ファイル: settingsGUI.py プロジェクト: AliGyula/Maze
class settings(tk.Frame):
    def __init__(self, master=None):
        self.width = 0
        self.height = 0
        self.cell = 0
        self.speed = 0
        self.isLaunching = 0

        self.widthEntry = None
        self.heightEntry = None
        self.cellEntry = None
        self.speedEntry = None
        self.editorBtn = None

        tk.Frame.__init__(self, master)
        self.var = tk.IntVar()
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.master.title("Settings")
        self.master.geometry("300x210")
        self.master.resizable(False, False)

        widthLabel = Label(self.master, text="width:")
        heightLabel = Label(self.master, text="height:")
        cellLabel = Label(self.master, text="cell size:")
        speedLabel = Label(self.master, text="speed(1-100):")

        self.widthEntry = Entry(self.master)
        self.heightEntry = Entry(self.master)
        self.cellEntry = Entry(self.master)
        self.speedEntry = Entry(self.master)
        self.editorBtn = Checkbutton(self.master,
                                     text="launch level editor",
                                     variable=self.var)

        btn = Button(self.master, text="OK!", command=self.getSettings)

        widthLabel.pack()
        self.widthEntry.pack()
        heightLabel.pack()
        self.heightEntry.pack()
        cellLabel.pack()
        self.cellEntry.pack()
        speedLabel.pack()
        self.speedEntry.pack()
        self.editorBtn.pack()
        btn.pack()

    def getSettings(self):
        self.width = self.widthEntry.get()
        self.height = self.heightEntry.get()
        self.cell = self.cellEntry.get()
        self.speed = self.speedEntry.get()
        self.isLaunching = self.var.get()
        self.master.destroy()
コード例 #19
0
    def populate(self):
        if self.frame_unpaid is not None:
            self.frame_unpaid.destroy()

        if self.frame_paid is not None:
            self.frame_paid.destroy()

        if self.frame_add is not None:
            self.frame_add.destroy()

        if self.frame_dialog is not None:
            self.frame_dialog.destroy()

        if self.addBillBox is not None:
            self.addBillBox.destroy()

        self.frame_unpaid = Frame(self, relief=RIDGE, borderwidth=2)
        self.frame_unpaid.pack(pady=0, padx=0, fill=X)
        self.frame_paid = Frame(self, relief=RIDGE, borderwidth=2)
        self.frame_paid.pack(pady=0, padx=0, fill=X)
        self.frame_dialog = Frame(self)
        self.frame_dialog.pack(pady=0, padx=0, fill=X)

        Label(self.frame_unpaid, text=unpaid_bills_label_text).pack(side=TOP, padx=5, pady=10)

        for bill_string in sorted(unpaid_dict):
            local_frame = Frame(self.frame_unpaid)
            local_frame.pack(pady=0, padx=0, fill=X)
            unpaid_dict[bill_string] = IntVar()
            Label(local_frame, text=bill_string).pack(side=LEFT, padx=5)
            c = Checkbutton(local_frame, text=checkbox_text, variable=unpaid_dict[bill_string], command=self.chk)
            c.pack(side=RIGHT)

        Label(self.frame_paid, text=paid_bills_label_text).pack(side=TOP, padx=5, pady=10)

        for data in sorted(paid_dict):
            bill_data = data.split('|')
            bill_string = bill_data[0]
            if len(bill_data) > 1:
                bill_date = bill_data[1].split('.')
                if len(bill_date) > 1:
                    bill_string += '(' + bill_date[1] + '.' + bill_date[0] + ')'
                else:
                    bill_string += '(xx.' + bill_date[0] + ')'

            local_frame = Frame(self.frame_paid)
            local_frame.pack(pady=0, padx=0, fill=X)
            paid_dict[data] = IntVar()
            Label(local_frame, text=bill_string).pack(side=LEFT, padx=5)
            c = Checkbutton(local_frame, text=checkbox_text, variable=paid_dict[data], command=self.unchk)
            c.pack(side=RIGHT)
            c.select()

        Button(self.frame_dialog, text='CONFIGURE', command=self.setup, width=9).pack(side=RIGHT, padx=5, pady=5)

        Button(self.frame_dialog, text='DISMISS', command=self.dismiss, width=9).pack(side=LEFT, padx=5, pady=5)
コード例 #20
0
ファイル: app.py プロジェクト: degi/nelderplot
 def body(self, master):
     self.optOuts = []
     self.cbs = []
     for optText in self.output_text_options:
         v = IntVar()
         cb = Checkbutton(master, text=optText, variable = v)
         cb.select()
         cb.pack(anchor=tk.W)
         self.cbs.append(cb)
         self.optOuts.append(v) 
     return self.cbs[0]
コード例 #21
0
class PairsWindow(object):
    
    def __init__(self, parent):
        
        self.parent = parent
        self.window = Toplevel(parent.root)
        self.window.wm_title("Pairs")                
        #self.window.resizable(width=False, height=False)
        #self.window.geometry('{}x{}'.format(250, 450))
        self.window.attributes('-topmost', True)
        
        self.drawWidgets()   
        
    def drawWidgets(self):

        label1 = Label(self.window, text="Choose pairs you want to delete:")
        label1.pack(side="top", padx="10", pady="5")
        
        self.tmp = OrderedDict()
        self.tmp = {str(key) + ': ' + str(self.parent.pixel_points[key]) + ' ' + str(self.parent.fix_points[key]):IntVar(value=0) for key, value in enumerate(self.parent.fix_points)}
        
        for key, value in self.tmp.items():
            self.c = Checkbutton(self.window, text = str(key), variable = value, onvalue = 1, offvalue = 0)
            self.c.pack(side="top", anchor=W, padx="10", pady="5")
            
        btn1 = Button(self.window, text="Delete selected", command=lambda *args: self.del_sel(self.window))
        btn1.pack(side="top", fill="both", padx="10", pady="5")
        
        btn2 = Button(self.window, text="Save pairs to disk", command=lambda *args: self.parent.save_pairs())
        btn2.pack(side="top", fill="both", padx="10", pady="5")
        
    def update_gui(self):
               
        for widget in self.window.winfo_children():
            widget.destroy()
        self.drawWidgets()        
        
    def del_sel(self, window):                
        
        tmp = 0
        for i, key in enumerate(self.tmp.copy()):            
            if self.tmp[key].get() == 1:
                    i = i - tmp
                    self.tmp.pop(key)
                    #More lists than needed but too lazy to change it :)
                    self.parent.pixel_points.pop(i)
                    self.parent.fix_points.pop(i)
                    self.parent.refPt.pop( (i * 2) )
                    self.parent.refPt.pop( (i * 2) )
                    self.parent.inter_line_counter -= 2
                    tmp += 1
        
        self.update_gui()
        self.parent.draw()
コード例 #22
0
ファイル: dialog.py プロジェクト: Jonson26/ConfigChess
    def __init__(self, x, y, board, playerdata):
        self.pd = playerdata
        self.board = board
        self.root = Toplevel()
        self.root.title("Miscellanious Gameplay Options Editing Window")

        f1 = Frame(self.root)
        f1.pack(side=TOP)
        f2 = Frame(self.root)
        f2.pack(side=TOP)
        f3 = Frame(self.root)
        f3.pack(side=TOP)

        b1 = Button(f1, text="SAVE", command=self.save)
        b2 = Button(f1, text="CANCEL", command=self.root.destroy)
        b1.pack(side=LEFT)
        b2.pack(side=LEFT)

        l1 = Label(f2, text="Maximum amount of moves per player per turn: ")
        self.l2 = Label(self.root, text=" ")

        self.e = Entry(f2)
        self.e.delete(0, END)
        self.e.insert(0, self.board.movesPerPlayer + 1)

        l1.pack(side=LEFT)
        self.e.pack(side=LEFT)
        self.l2.pack(side=BOTTOM)

        l3 = Label(f3, text="Win condition:")

        self.c1 = ttk.Combobox(
            f3,
            values=[
                "Until one player loses all of his pieces",
                "Until one of the opponents has no more Kings"
            ],
            width=50)  #menu for win condition selection
        if (self.board.winCondition == "All"):
            self.c1.current(0)
        elif (self.board.winCondition == "King"):
            self.c1.current(1)

        l3.pack(side=LEFT)
        self.c1.pack(side=LEFT)

        self.v2 = BooleanVar()
        c = Checkbutton(f3, text="Enable Turn Pass", variable=self.v2)
        self.v2.set(self.board.passEnable)
        c.pack(side=BOTTOM)

        self.align(x, y)
        self.root.mainloop()
コード例 #23
0
 def __add_option(self, text, selected=False):
     if selected:
         var = StringVar(value=text)
     else:
         var = StringVar(value="")
     button = Checkbutton(self.options_frame,
                          text=text,
                          var=var,
                          onvalue=text,
                          offvalue="")
     button.pack()
     self.vars.append(var)
コード例 #24
0
ファイル: dialog.py プロジェクト: Jonson26/ConfigChess
    def __init__(self, x, y, board):
        self.boardA = board
        self.boardB = copy(board)
        self.root = Toplevel()
        self.root.title("Piece Placement Editing Window")

        f1 = Frame(self.root)  #frame containing the save and cancel buttons
        f1.pack(side=TOP)

        f2 = Frame(self.root)  #frame containing piece selection
        f2.pack(side=LEFT)

        b1 = Button(f1, text="SAVE", command=self.save)
        b2 = Button(f1, text="CANCEL", command=self.root.destroy)
        b1.pack(side=LEFT)
        b2.pack(side=RIGHT)

        l1 = Label(f2, text="Type")
        l2 = Label(f2, text="Colour")

        self.c1 = ttk.Combobox(
            f2, values=__piece_types__)  #menu for piece type selection
        self.c1.current(0)

        l1.pack()
        self.c1.pack()
        l2.pack()

        self.v1 = StringVar()  #radiobuttons for piece colour selection
        self.v1.set("red")
        for c in __player_colours__:
            b = Radiobutton(f2, text=c, variable=self.v1, value=c)
            b.pack()

        self.v2 = BooleanVar()
        c = Checkbutton(f2,
                        text="Centrally Symmetrical Opponent",
                        variable=self.v2)
        self.v2.set(False)
        c.pack()

        self.canvas = Canvas(self.root, width=320, height=320)
        self.boardB.canvas = self.canvas
        self.canvas.bind("<Button-1>", self.callback1)
        self.canvas.bind("<Button-3>", self.callback2)
        self.canvas.pack(side=BOTTOM)

        self.redraw(0)

        self.align(x, y)

        self.root.mainloop()
コード例 #25
0
ファイル: __init__.py プロジェクト: tuantvk/pystrap
def Checkbox(root, style="", **options):

    props = {
        'activeforeground': load_color(style)['color'],
        'activebackground': load_color(style)['acColor']
    }

    props.update(**options)

    C = Checkbutton(root)

    C.config(props)

    C.pack()
コード例 #26
0
class GUI:
    def __init__(self, master):
        self.master = master
        master.title("Tithe Reporter")
        master.geometry('1000x500')

        self.filepath = ""
        self.cmd = 0
        self.names = []
        self.size = 0
        self.df = DataFrame()

        self.file_button = Button(master, text="Choose a file", command=self.filesearch)
        self.file_button.pack()

        self.makeboxes_button = Button(master, text="Retrieve Names", command=self.makeboxes)
        self.makeboxes_button.pack()

        self.generate_button = Button(master, text="Generate PDFs", command=self.generate)
        self.generate_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()

    def filesearch(self):
        tmpdir = filedialog.askopenfilename(initialdir=os.getcwd(), title='Choose file')
        if tmpdir:
            try:
                self.file_button.configure(text='File Found', bg='green')
                self.filepath = tmpdir
                self.getnames()
            except:
                messagebox.showerror("Open source file", "Failed to read file" + tmpdir)

    def getnames(self):
        self.df = read_csv(self.filepath, encoding='utf-8')
        self.names = self.df['Name'].tolist()
        self.size = len(self.filepath)

    def makeboxes(self):
        try:
            for name in self.names:
                var = IntVar()
                self.check_buttons = Checkbutton(self.master, variable=var, text=name)
                self.check_buttons.pack()
        except:
            messagebox.showerror("Populate Names", "Failed to create list of names")

    def generate(self):
        self.df['totals'] = self.df.sum(axis=1)
コード例 #27
0
    def create_option_buttons(self):
        "Fill frame with Checkbuttons bound to SearchEngine booleanvars."
        f = self.make_frame("Options")

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.revar,
                text="Regular expression")
        btn.pack(side="left", fill="both")
        if self.engine.isre():
            btn.select()

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.casevar,
                text="Match case")
        btn.pack(side="left", fill="both")
        if self.engine.iscase():
            btn.select()

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.wordvar,
                text="Whole word")
        btn.pack(side="left", fill="both")
        if self.engine.isword():
            btn.select()

        if self.needwrapbutton:
            btn = Checkbutton(f, anchor="w",
                    variable=self.engine.wrapvar,
                    text="Wrap around")
            btn.pack(side="left", fill="both")
            if self.engine.iswrap():
                btn.select()
コード例 #28
0
def _makesetting(setting_window, conf):
    setting_label = Label(setting_window,
                          text=_('Setting'),
                          font=('courier', 20, 'bold'))
    setting_label.pack(side=TOP)

    style_container = Frame(setting_window)
    style_container.pack(side=TOP)
    style_label = Label(style_container,
                        text=_('Display wallpaper in style: '),
                        font=('courier', 15, 'bold'))
    style_label.pack(side=LEFT)
    style_combobox = Combobox(style_container)
    available_style = {
        '3': 'zoom',
        '2': 'scaled',
        '1': 'stretched',
        '0': 'centered',
        '4': 'wallpaper'
    }
    style_combobox['value'] = (_('centered'), _('stretched'), _('scaled'),
                               _('zoom'), _('wallpaper'))
    style_combobox.state(['readonly'])
    style_combobox.current(int(conf['style']))
    style_combobox.pack(side=LEFT)

    random_container = Frame(setting_window)
    random_container.pack(side=TOP)
    random_label = Label(random_container,
                         text=_('Choose wallpaper randomly? '),
                         font=('courier', 15, 'bold'))
    random_label.pack(side=LEFT)
    random_checkbutton = Checkbutton(random_container)
    random_checkbutton.pack(side=LEFT)
    if conf['random'] == "1":
        random_checkbutton.select()

    interval_container = Frame(setting_window)
    interval_container.pack(side=TOP)
    interval_label = Label(interval_container,
                           text=_('Change wallpaper every '),
                           font=('courier', 15, 'bold'))
    interval_label.pack(side=LEFT)
    interval_text = Text(interval_container, height=1, width=4)
    interval_text.insert(END, conf['interval'])
    interval_text.pack(side=LEFT)
    minute_label = Label(interval_container,
                         text=_(' minutes.'),
                         font=('courier', 15, 'bold'))
    minute_label.pack(side=LEFT)
コード例 #29
0
class CheckRaddioButtons:
    def __init__(self, master):

        self.master = master
        master.title("Presenting choices with check buttons and radio buttons")

        # Create a checkbutton and show in window
        self.checkbutton = Checkbutton(master,
                                       text='SPAN? ',
                                       font=('Arial', 12, 'bold'))
        self.checkbutton.pack()

        self.spam = StringVar()
        self.spam.set('SPAM!')
        self.spam.get()

        self.checkbutton.config(text="Span",
                                variable=self.spam,
                                onvalue="Span Please",
                                offvalue="Boo Span")
        print(self.spam.get())
        print(self.spam.get())

        self.breakfast = StringVar()
        self.radiobutton = Radiobutton(root,
                                       text="SPAM",
                                       variable=self.breakfast)
        self.radiobutton.pack()

        self.rbeggs = Radiobutton(root,
                                  text="Eggs",
                                  variable=self.breakfast,
                                  value='Eggs')
        self.rbeggs.pack()

        self.rbsausage = Radiobutton(root,
                                     text="Sausage",
                                     variable=self.breakfast,
                                     value='Sausage')
        self.rbsausage.pack()

        self.rbspan = Radiobutton(root,
                                  text="SPAM",
                                  variable=self.breakfast,
                                  value='SPAM')
        self.rbspan.pack()

        self.breakfast.get()
        self.checkbutton.config(variable=self.breakfast)
コード例 #30
0
class ProgressCheckButton(Frame, Observable):
    def __init__(self, parent, model, index, status_model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self.model = model
        self.index = index
        self.status_model = status_model
        self.var = IntVar()
        self.var.set(model.get_checked())
        self.progress_var = IntVar()
        self.progress_status = ProgressStatus.undefined
        self.check_button = Checkbutton(self, text=model.get_label, variable=self.var, command=self._check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self.progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self.model.add_listener(self._model_changed)

    def _model_changed(self, new_status):
        model_state = self.model.get_checked()
        gui_state = self.var.get()
        if model_state is not gui_state:
            self.model.set_checked(gui_state)

    def refresh_check(self):
        if self.status_model.is_checked_force_reload():
            self.check_button.select()
        else:
            self.check_button.deselect()

    def is_checked(self):
        return self.var.get()

    def _progress_status_changed(self, new_status):
        self._refresh_progress()

    def _refresh_progress(self):
        status = self.status_model.get_status()
        if not status == self.progress_status:
            if status == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _check_changed(self):
        new_checked = self.var.get()
        if new_checked is not self.model.get_checked():
            self.model.set_checked(new_checked)
        if new_checked is not self.status_model.is_checked():
            self._notify(self.index, new_checked)
コード例 #31
0
ファイル: SearchDialogBase.py プロジェクト: google/cpython-pt
 def create_option_buttons(self):
     "Fill frame with Checkbuttons bound to SearchEngine booleanvars."
     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, anchor="w", variable=var, text=label)
         btn.pack(side="left", fill="both")
         if var.get():
             btn.select()
     return frame, options  # for test
コード例 #32
0
ファイル: chbox.py プロジェクト: joshnankivel/wikikit
    def __init__(self, parent):

        Frame.__init__(self, parent)
        self.parent = parent
        self.test01 = BooleanVar()
        checkbutton = Checkbutton(parent,
                                  text='check it',
                                  variable=self.test01,
                                  command=self.testcheck)

        checkbutton.pack()

        testbutton = Button(parent, text='check test', command=self.testcheck)
        testbutton.pack()
        self.parent.title('Checkbutton test')
コード例 #33
0
 def show(self):
     frame = Frame(Interface.functional_area)
     frame.pack(fill=X)
     label = Label(frame, text=self._button_text)
     label.pack(side=LEFT)
     for text, value in self._options:
         var = BooleanVar()
         var.set(value)
         check_button = Checkbutton(frame,
                                    text=text,
                                    variable=var,
                                    onvalue=True,
                                    offvalue=False)
         check_button.pack(side=LEFT)
         self._value_list.append(var)
コード例 #34
0
class ProgressListBoxItem(Frame, Observable):
    def __init__(self, parent, model):
        Frame.__init__(self, parent)
        Observable.__init__(self)
        self._model = model

        # Create variables and initialise to zero
        self._checked_var = IntVar()
        self._progress_var = IntVar()
        self._checked_var.set(0)
        self._progress_var.set(0)
        self._current_gui_checked_state = CheckStatus.undefined
        self._current_gui_progress_state = ProgressStatus.undefined

        self.check_button = Checkbutton(self, text=model.get_label(), variable=self._checked_var, command=self._user_check_changed)
        self.progress_bar = Progressbar(self, orient='horizontal', mode='indeterminate', variable=self._progress_var)
        self.check_button.pack(side=LEFT, fill="both", expand=True)

        self._update()
        self._model.add_listener(self._model_changed)

    def _model_changed(self):
        self.update()

    def _update(self):
        # Update check status
        model_check_state = self._model.get_check_status()
        if model_check_state is not self._current_gui_checked_state:
            self._current_gui_checked_state = model_check_state
            # if self.status_model.is_checked_force_reload():
            if model_check_state:
                self.check_button.select()
            else:
                self.check_button.deselect()

        # Update progress status
        model_progress_state = self._model.get_progress_status
        if not model_progress_state == self._current_gui_progress_state:
            self._current_gui_progress_state = model_progress_state
            if model_progress_state == ProgressStatus.in_progress:
                self.progress_bar.pack(side=RIGHT, fill="both", expand=True)
            else:
                self.progress_bar.pack_forget()

    def _user_check_changed(self):
        new_checked = self._checked_var.get()
        if new_checked is not self._model.get_check_status():
            self._model.manual_set_checked(new_checked)
コード例 #35
0
ファイル: widgets.py プロジェクト: cedrick-f/Profil
    def __init__(self, parent: Frame, profilConfig: ProfilConfig):
        Frame.__init__(self, parent)
        self.profilConfig = profilConfig

        self.bool_vars: Dict[str, List[BooleanVar, Dict[BooleanVar]]] = {}
        self.chk_btn: Dict[str, List[Checkbutton, Dict[Checkbutton]]] = {}

        # Les groupes ...
        for groupe in PROFILS.groups:
            bool_var = BooleanVar()
            checkbutton = Checkbutton(
                self,
                text=groupe.nom,
                variable=bool_var,
                command=lambda n=groupe.nom: self.manage_buttons(n))
            self.bool_vars[groupe.nom] = [bool_var, {}]
            self.chk_btn[groupe.nom] = [checkbutton, {}]

            #             if groupe.nom in self.profilConfig.get_names():
            #                 checkbutton.configure(state='normal')
            #                 bool_var.set(True)
            #             else:
            #                 checkbutton.configure(state='disabled')

            checkbutton.pack(anchor="w")

            # Les éléments ...
            if len(groupe.lst_elem) > 1:
                for elem in groupe.lst_elem:
                    bool_var = BooleanVar()
                    checkbutton = Checkbutton(
                        self,
                        text=elem.name,
                        variable=bool_var,
                        command=lambda: self.manage_buttons(elem.name))
                    self.bool_vars[groupe.nom][1][elem.name] = bool_var
                    self.chk_btn[groupe.nom][1][elem.name] = checkbutton

                    #grp = self.profilConfig.get_group(groupe.nom)
                    #                     if grp is not None and elem.name in grp.get_names():
                    #                         checkbutton.configure(state='normal')
                    #                         bool_var.set(True)
                    #                     else:
                    #                         checkbutton.configure(state='disabled')

                    checkbutton.pack(anchor="w", padx=(20, 0))
        self.update()
コード例 #36
0
    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, anchor="w", variable=var, text=label)
            btn.pack(side="left", fill="both")
            if var.get():
                btn.select()
        return frame, options
コード例 #37
0
def _makesetting(setting_window, conf):
    setting_label = Label(setting_window,
                          text=_('Setting'),
                          font=('courier', 20, 'bold'))
    setting_label.pack(side=TOP)

    style_container = Frame(setting_window)
    style_container.pack(side=TOP)
    style_label = Label(style_container,
                        text=_('Display wallpaper in style: '),
                        font=('courier', 15, 'bold'))
    style_label.pack(side=LEFT)
    style_combobox = Combobox(style_container)
    available_style = {'3': 'zoom', '2': 'scaled', '1': 'stretched', '0': 'centered', '4': 'wallpaper'}
    style_combobox['value'] = (_('centered'), _('stretched'), _('scaled'), _('zoom'), _('wallpaper'))
    style_combobox.state(['readonly'])
    style_combobox.current(int(conf['style']))
    style_combobox.pack(side=LEFT)

    random_container = Frame(setting_window)
    random_container.pack(side=TOP)
    random_label = Label(random_container,
                         text=_('Choose wallpaper randomly? '),
                         font=('courier', 15, 'bold'))
    random_label.pack(side=LEFT)
    random_checkbutton = Checkbutton(random_container)
    random_checkbutton.pack(side=LEFT)
    if conf['random'] == "1":
        random_checkbutton.select()

    interval_container = Frame(setting_window)
    interval_container.pack(side=TOP)
    interval_label = Label(interval_container,
                           text=_('Change wallpaper every '),
                           font=('courier', 15, 'bold'))
    interval_label.pack(side=LEFT)
    interval_text = Text(interval_container, height=1, width=4)
    interval_text.insert(END, conf['interval'])
    interval_text.pack(side=LEFT)
    minute_label = Label(interval_container,
                         text=_(' minutes.'),
                         font=('courier', 15, 'bold'))
    minute_label.pack(side=LEFT)
コード例 #38
0
ファイル: main.py プロジェクト: pielambr/ydlui
 def _init_ui(self):
     # Label to specify video link
     lbl_video_url = Label(self, text="Video URL:")
     lbl_video_url.place(x=20, y=20)
     # Entry to enter video url
     entr_video_url = Entry(self, width=50, textvariable=self._video_url)
     entr_video_url.place(x=100, y=20)
     # Checkbutton to extract audio
     cb_extract_audio = Checkbutton(self, var=self._extract_audio, text="Only keep audio")
     cb_extract_audio.pack()
     cb_extract_audio.place(x=20, y=60)
     # Button to browse for location
     b_folder_choose = Button(self, text="Choose output directory", command=self.ask_directory)
     b_folder_choose.place(x=150, y=90)
     # Button to start downloading
     b_start_download = Button(self, text="Start download", command=self.download)
     b_start_download.place(x=20, y=90)
     # Log window to log progress
     self._logger.place(x=20, y=130)
コード例 #39
0
ファイル: gui.py プロジェクト: FranciscoMeloJr/Python-Tests
    def __init__(self, master):
        self.init_args()
        self.master = master
        master.title("Helper")

        self.label = Label(master, text="Parser Helper")
        self.label.pack()

        self.exception_value = IntVar()
        # Exception
        C1 = Checkbutton(master, text="Exception", variable=self.exception_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C1.pack()


        self.cause_value = IntVar()
        # Cause by
        C2 = Checkbutton(master, text="Cause by", variable=self.cause_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C2.pack()
        # Verbose
        self.verbose_value = IntVar()
        C3 = Checkbutton(master, text="Verbose", variable=self.verbose_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C3.pack()

        # Log to file
        self.log_value = IntVar()
        C4 = Checkbutton(master, text="Log to file", variable=self.log_value, \
                         onvalue=1, offvalue=0, height=5, \
                         width=20)
        C4.pack()

        self.greet_button = Button(master, text="Select file", command=self.open_file)
        self.greet_button.pack()

        self.close_button = Button(master, text="Execute", command=self.execute)
        self.close_button.pack()

        self.close_button = Button(master, text="Quit", command=master.quit)
        self.close_button.pack()
コード例 #40
0
ファイル: gui.py プロジェクト: OFFIS-Automation/Framework
    def init_gui(self):
        """init helper"""
        # setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        # Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(
            msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white"
        )
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        # History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(
            history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white"
        )
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind("<Double-Button-1>", self.select_recent_file)
        self.set_history_window()

        # status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        # labels
        self.lblRatingLabel = Label(rating_frame, text="Rating:")
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text="Recently Used:").pack(side=LEFT)
        Label(top_frame, text="Module or package").pack(side=LEFT)

        # file textbox
        self.txtModule = Entry(top_frame, background="white")
        self.txtModule.bind("<Return>", self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        # results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(
            res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier"
        )
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        # buttons
        Button(top_frame, text="Open", command=self.file_open).pack(side=LEFT)
        Button(top_frame, text="Open Package", command=(lambda: self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text="Run", command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text="Quit", command=self.quit).pack(side=BOTTOM)

        # radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(
            check_frame,
            text="Information",
            fg=COLORS["(I)"],
            variable=self.information_box,
            command=self.refresh_msg_window,
        )
        c = Checkbutton(
            check_frame,
            text="Convention",
            fg=COLORS["(C)"],
            variable=self.convention_box,
            command=self.refresh_msg_window,
        )
        r = Checkbutton(
            check_frame, text="Refactor", fg=COLORS["(R)"], variable=self.refactor_box, command=self.refresh_msg_window
        )
        w = Checkbutton(
            check_frame, text="Warning", fg=COLORS["(W)"], variable=self.warning_box, command=self.refresh_msg_window
        )
        e = Checkbutton(
            check_frame, text="Error", fg=COLORS["(E)"], variable=self.error_box, command=self.refresh_msg_window
        )
        f = Checkbutton(
            check_frame, text="Fatal", fg=COLORS["(F)"], variable=self.fatal_box, command=self.refresh_msg_window
        )
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        # check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(
            radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window
        )
        rawMet = Radiobutton(
            radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window
        )
        dup = Radiobutton(
            radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window
        )
        ext = Radiobutton(
            radio_frame,
            text="External dependencies",
            variable=self.box,
            value="External dependencies",
            command=self.refresh_results_window,
        )
        stat = Radiobutton(
            radio_frame,
            text="Statistics by type",
            variable=self.box,
            value="Statistics by type",
            command=self.refresh_results_window,
        )
        msgCat = Radiobutton(
            radio_frame,
            text="Messages by category",
            variable=self.box,
            value="Messages by category",
            command=self.refresh_results_window,
        )
        msg = Radiobutton(
            radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window
        )
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=E)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, columnspan=2, sticky=W)

        # dictionary for check boxes and associated error term
        self.msg_type_dict = {
            "I": lambda: self.information_box.get() == 1,
            "C": lambda: self.convention_box.get() == 1,
            "R": lambda: self.refactor_box.get() == 1,
            "E": lambda: self.error_box.get() == 1,
            "W": lambda: self.warning_box.get() == 1,
            "F": lambda: self.fatal_box.get() == 1,
        }
        self.txtModule.focus_set()
コード例 #41
0
ファイル: cmd_minised_gui.py プロジェクト: Grumbel/minised
class MiniSedGUI(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.cfg = MiniSedConfig()

        self.source_directory = None
        self.target_directory = None

        self.create_widgets()
        self.pack(anchor=CENTER, fill=BOTH, expand=1)

        self.files_with_content = []

        self.cfg.directory.trace('w', self.disable_apply)
        self.cfg.glob.trace('w', self.disable_apply)
        self.cfg.search.trace('w', self.disable_apply)
        self.cfg.replace.trace('w', self.disable_apply)
        self.cfg.ignore_case.trace('w', self.disable_apply)

    def disable_apply(self, *args):
        self.run_btn["state"] = 'disabled'

    def create_widgets(self):

        self.directory_frame = Frame(self)
        self.directory_frame.pack(side=TOP, fill=X, expand=0, padx=4, pady=4)
        self.directory_frame.grid_columnconfigure(1, weight=1)

        self.directory_label = Label(self.directory_frame, text="Directory:")
        self.directory_label.grid(column=0, row=0)

        self.directory_entry = Entry(self.directory_frame, textvariable=self.cfg.directory)
        self.directory_entry.grid(column=1, row=0, sticky=W + E)
        self.directory_entry.bind('<Return>', lambda arg: self.do_preview())

        self.directory_button = Button(self.directory_frame, text="Browse")
        self.directory_button["command"] = lambda: do_ask_directory(self.cfg.directory)
        self.directory_button.grid(column=2, row=0)

        self.glob_label = Label(self.directory_frame, text="Glob:")
        self.glob_label.grid(column=0, row=1, stick=E)

        self.glob_entry = Entry(self.directory_frame, textvariable=self.cfg.glob)
        self.glob_entry.bind('<Return>', lambda arg: self.do_preview())
        self.glob_entry.grid(column=1, row=1, sticky=N + S + W)

        self.search_replace_frame = Frame(self)
        self.search_replace_frame.grid_columnconfigure(1, weight=1)
        self.search_replace_frame.pack(anchor=N, side=TOP, fill=X, expand=0, padx=4, pady=4)

        self.search_label = Label(self.search_replace_frame, text="Search:")
        self.search_label.grid(column=0, row=0, sticky=E)
        self.search_entry = Entry(self.search_replace_frame, textvariable=self.cfg.search)
        self.search_entry.grid(column=1, row=0, sticky=N + S + W + E)
        self.search_entry.bind('<Return>', lambda arg: self.do_preview())

        self.replace_label = Label(self.search_replace_frame, text="Replace:")
        self.replace_label.grid(column=0, row=1, sticky=E)
        self.replace_entry = Entry(self.search_replace_frame, textvariable=self.cfg.replace)
        self.replace_entry.grid(column=1, row=1, sticky=N + S + W + E)
        self.replace_entry.bind('<Return>', lambda arg: self.do_preview())

        self.option_frame = Frame(self)
        self.option_frame.pack(side=TOP, fill=X, expand=0, pady=4)

        self.work_frame = LabelFrame(self.option_frame, text="Options")
        self.work_frame.pack(side=LEFT, padx=4, pady=4)

        self.ignore_case_checkbutton = Checkbutton(
            self.work_frame, text="ignore case", variable=self.cfg.ignore_case)
        self.ignore_case_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.create_backups_checkbutton = Checkbutton(
            self.work_frame, text="create backups", variable=self.cfg.create_backups)
        self.create_backups_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.preview_frame = LabelFrame(self.option_frame, text="Preview")
        self.preview_frame.pack(side=LEFT, padx=4, pady=4)
        self.show_full_content_checkbutton = Checkbutton(
            self.preview_frame, text="show full content", variable=self.cfg.show_full_content)
        self.show_full_content_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.show_original_checkbutton = Checkbutton(
            self.preview_frame, text="show original", variable=self.cfg.show_original)
        self.show_original_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.text_frame = Frame(self)
        self.text_frame.pack(side=TOP, fill=BOTH, expand=1, pady=4)

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

        self.scrollbar = Scrollbar(self.text_frame)
        self.scrollbar.grid(column=1, row=0, sticky=N + S)

        self.text = Text(self.text_frame, yscrollcommand=self.scrollbar.set, width=120, height=20)

        self.text.tag_config("file", background="lightgray", foreground="black")
        self.text.tag_config("search", background="lightblue", foreground="black")
        self.text.tag_config("replace", background="orange", foreground="black")
        self.text.tag_config("hollow", foreground="gray")
        self.text.tag_config("highlight", background="lightyellow")

        self.text.config(state=DISABLED)
        self.text.grid(column=0, row=0, sticky=N + S + W + E)
        self.scrollbar.config(command=self.text.yview)

        self.confirm_button_frame = Frame(self)
        self.confirm_button_frame.pack(side=BOTTOM, anchor=E)

        self.cancel_btn = Button(self.confirm_button_frame)
        self.cancel_btn["text"] = "Quit"
        self.cancel_btn["command"] = self.quit
        self.cancel_btn.grid(column=1, row=0, sticky=S, pady=8, padx=8)

        self.preview_btn = Button(self.confirm_button_frame)
        self.preview_btn["text"] = "Preview"
        self.preview_btn["command"] = self.do_preview
        self.preview_btn.grid(column=2, row=0, sticky=S, pady=8, padx=8)

        self.run_btn = Button(self.confirm_button_frame)
        self.run_btn["text"] = "Apply"
        self.run_btn["command"] = self.do_execute
        self.run_btn.grid(column=3, row=0, sticky=S, pady=8, padx=8)
        self.run_btn["state"] = 'disabled'

    def do_preview(self):
        directory = self.cfg.directory.get()

        self.text.config(state=NORMAL)
        self.text.delete("1.0", END)
        self.text.config(state=DISABLED)

        self.files_with_content = []
        for path, dirs, files in os.walk(directory):
            for fname in files:
                filename = os.path.join(path, fname)

                if not self.cfg.glob.get() or fnmatch.fnmatch(fname.lower(), self.cfg.glob.get().lower()):
                    with open(filename, 'rt', encoding='latin-1') as fin:
                        lines = fin.read().splitlines()
                    lines = minised_on_lines(lines, self.cfg.search.get(), self.cfg.replace.get(),
                                             self.cfg.ignore_case.get())
                    self.files_with_content.append((filename, lines))

                    self.text.config(state=NORMAL)
                    self.text.insert(END, "%s:\n" % filename, "file")
                    for line in lines:
                        if isinstance(line, tuple):
                            if self.cfg.show_original.get():
                                self.text.insert(END, "%s" % line[0], "hollow")
                                self.text.insert(END, "%s" % line[1], "search")
                                self.text.insert(END, "%s\n" % line[3], "hollow")

                            self.text.insert(END, "%s" % line[0], "highlight")
                            self.text.insert(END, "%s" % line[2], "replace")
                            self.text.insert(END, "%s" % line[3], "highlight")
                            self.text.insert(END, "\n")
                        elif self.cfg.show_full_content.get():
                            self.text.insert(END, "%s\n" % line)
                    self.text.insert(END, "\n")
                    self.text.config(state=DISABLED)

                    self.master.update()
        self.run_btn["state"] = 'normal'

    def do_execute(self):
        for filename, lines in self.files_with_content:
            if self.cfg.create_backups.get():
                os.rename(filename, filename + "~")

            with open(filename, 'wt', encoding='latin-1', newline='\r\n') as fout:
                for line in lines:
                    if isinstance(line, tuple):
                        fout.write(line[0])
                        fout.write(line[2])
                        fout.write(line[3])
                    else:
                        fout.write(line)
                    fout.write("\n")

        self.run_btn["state"] = 'disabled'
        tkinter.messagebox.showinfo("Replacement successful",
                                    "Replacements have been performed successfully on the files")
コード例 #42
0
ファイル: widgets.py プロジェクト: bbferka/pracmln
class FilePickEdit(Frame):
    
    def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, 
                 rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'):
        """
            file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"])
        """
        self.master = master
        self.directory = directory
        self.user_onChange = user_onChange
        Frame.__init__(self, master)
        row = 0
        self.unmodified = True
        self.allowNone = allowNone
        self.file_extension = ""
        if type(file_mask) != list:
            file_mask = [file_mask]
        if "." in file_mask[0]:
            self.file_extension = file_mask[0][file_mask[0].rfind('.'):]
        # read filenames
        self.file_mask = file_mask
        self.updateList()
        # filename frame
        self.list_frame = Frame(self)
        self.list_frame.grid(row=row, column=0, sticky="WE")
        self.list_frame.columnconfigure(0, weight=1)
        # create list
        self.picked_name = StringVar()
        self.makelist()
        # refresh button
        self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1)
        self.refresh_button.grid(row=0, column=1, sticky='E')        
        # save button
        self.save_button = Button(self.list_frame, text="save", command=self.save, height=1)
        self.save_button.grid(row=0, column=2, sticky="E")
        # editor
        row += 1
        if coloring:
            self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter)
        else:
            self.editor = ScrolledText2(self, self.onEdit)
        if font is not None:
            self.editor.configure(font=font)
        if edit_height is not None:
            self.editor.configure(height=edit_height)
        self.editor.grid(row=row, column=0, sticky="NEWS")
        self.rowconfigure(row, weight=1)
        self.columnconfigure(0, weight=1)
        # option to change filename on edit
        row += 1
        self.options_frame = Frame(self)
        self.options_frame.grid(row=row, column=0, sticky=W)
        self.rename_on_edit = IntVar()
        self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit)
        self.cb.pack(side=LEFT)
        self.cb.configure(command=self.onChangeRename)
        self.rename_on_edit.set(rename_on_edit)
        # filename frame
        row += 1
        self.filename_frame = Frame(self)
        self.filename_frame.grid(row=row, column=0, sticky="WE")
        self.filename_frame.columnconfigure(0, weight=1)
        # save as filename
        self.save_name = StringVar()
        self.save_edit = Entry(self.filename_frame, textvariable = self.save_name)
        self.save_edit.grid(row=0, column=0, sticky="WE")
        self.save_name.trace("w", self.onSaveChange)
        # pick default if applicableButton
        self.select(default_file)
        self.row = row
        
    def setDirectory(self, directory, keep=False):
        self.directory = directory
        self.updateList()
        self.makelist()
#         menu = self.list["menu"] scrolledlist
#         menu = self.list.listbox#["scrolledlist"]
#         menu.delete(0, 'end')
        # add the new ones
#         for filename in self.files:
#             menu.add_command(label=filename, command=_setit(self.picked_name, filename, None))
        # if keep is true, only the files list will be updated but the content of the
        # text area will not be altered/removed
        if not keep: self.select("")
    
    def refresh(self):
        sel = self.get()
        self.updateList()
        self.select(sel, notify=False)
    
    def reloadFile(self):
        self.editor.delete("1.0", END)
        filename = self.picked_name.get()
        if os.path.exists(os.path.join(self.directory, filename)):
            new_text = open(os.path.join(self.directory, filename)).read()
            if new_text.strip() == "":
                new_text = "// %s is empty\n" % filename
            new_text = new_text.replace("\r", "")
        else:
            new_text = ""
        self.editor.insert(INSERT, new_text)
        
    def setText(self, txt):
        """
        Replaces the text in the edit field as by typing
        into it.
        """
        self.select("")
        if txt.strip() == "":
            txt = "// empty database\n"
        self.editor.insert(INSERT, txt)
        self.onEdit()
        

    def onSelChange(self):
        self.reloadFile()
        filename = self.picked_name.get()
        self.save_name.set(filename)
        self.save_edit.configure(state=DISABLED)
        self.unmodified = True
        if self.user_onChange is not None:
            self.user_onChange(filename)

    def onSaveChange(self, name, index, mode):
        pass

    def autoRename(self):
        # modify "save as" name
        filename = self.picked_name.get()
        if filename == "": filename = "new" + self.file_extension # if no file selected, create new filename
        ext = ""
        extpos = filename.rfind(".")
        if extpos != -1: ext = filename[extpos:]
        base = filename[:extpos]
        hpos = base.rfind("-")
        num = 0
        if hpos != -1:
            try:
                num = int(base[hpos+1:])
                base = base[:hpos]
            except:
                pass
        while True:
            num += 1
            filename = "%s-%d%s" % (base, num, ext)
            if not os.path.exists(filename):
                break
        self.save_name.set(filename)
        # user callback
        if self.user_onChange is not None:
            self.user_onChange(filename)

    def onEdit(self):
        if self.unmodified:
            self.unmodified = False
            # do auto rename if it's enabled or there is no file selected (editing new file)
            if self.rename_on_edit.get() == 1 or self.picked_name.get() == "":
                self.autoRename()
            # enable editing of save as name
            self.save_edit.configure(state=NORMAL)

    def onChangeRename(self):
        # called when clicking on "rename on edit" checkbox
        if self.rename_on_edit.get() == 1:
            if (not self.unmodified) and self.save_name.get() == self.picked_name.get():
                self.autoRename()
        else:
            self.save_name.set(self.picked_name.get())

    def updateList(self):
        self.files = []
        if self.allowNone:
            self.files.append("")
        if os.path.exists(self.directory):
            for filename in os.listdir(self.directory):
                for fm in self.file_mask:
                    if fnmatch(filename, fm):
                        self.files.append(filename)
        self.files.sort()
        if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask))
        

    def select(self, filename, notify=True):
        """ selects the item given by filename """
        if filename in self.files:
            if not havePMW:
                self.picked_name.set(filename)
            else:
                self.list.selectitem(self.files.index(filename))
                if notify: self.onSelChange(filename)
        else:
            self.editor.delete("1.0", END)
                

    def makelist(self):
        if havePMW:
            self.list = ComboBox(self.list_frame,
                    selectioncommand = self.onSelChange,
                    scrolledlist_items = self.files,
            )
            self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS")
            self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
            self.picked_name = self.list
        else:
            self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files))
            self.list.grid(row=0, column=0, sticky="NEW")
            self.picked_name.trace("w", self.onSelChange)

    def save(self):
        self.get()

    def set(self, selected_item):
        self.select(selected_item)

    def get(self):
        """ gets the name of the currently selected file, saving it first if necessary """
        filename = self.save_name.get()
        if self.unmodified == False:
            self.unmodified = True
            # save the file
            f = open(os.path.join(self.directory, filename), "w")
            f.write(self.editor.get("1.0", END).encode('utf-8'))
            f.close()
            # add it to the list of files
#             if not filename in self.files:
#                 self.files.append(filename)
#                 self.files.sort()
#                 self.list.destroy()
#                 self.makelist()
            # set it as the new pick
            #if havePMW:
            #    self.picked_name.selectitem(self.files.index(filename), 1)
            #else:
            #    self.picked_name.set(filename)
#             self.select(filename)
            self.refresh()
            self.select(filename, notify=False)
            self.save_edit.configure(state=DISABLED)
        return filename

    def get_text(self):
        return self.editor.get("1.0", END)

    def get_filename(self):
        return self.save_name.get()

    def set_enabled(self, state):
        self.editor.configure(state=state)
        if havePMW:
            self.list.component('entryfield_entry').configure(state=state)
#             self.list.component('arrowbutton').configure(state=state)
            self.list.component('arrowbutton').bind('<1>', (lambda a: 'break') if state==DISABLED else self.list._postList)
        else:
            self.list.configure(state=state)
        self.save_button.configure(state=state)
        self.cb.configure(state=state)
        self.save_edit.configure(state=state)
コード例 #43
0
def closeAndStartUmineko():
	rootWindow.withdraw()
	mainUmineko()
	installFinishedMessage = "Install Finished. Temporary install files have been displayed - please delete the " \
							 "temporary files after checking the mod has installed correctly."
	print(installFinishedMessage)
	messagebox.showinfo("Install Completed", installFinishedMessage)
	rootWindow.destroy()



# Add an 'OK' button. When pressed, the dialog is closed
defaultPadding = {"padx": 20, "pady": 10}
b = tkinter.Button(rootWindow, text="Install Higurashi Mods", command=closeAndStartHigurashi)
b.pack(**defaultPadding)
b = tkinter.Button(rootWindow, text="Install Umineko Mods", command=closeAndStartUmineko)
b.pack(**defaultPadding)

tkinter.Label(rootWindow, text="Advanced Settings").pack()

# Add a checkbox to enable/disable IPV6. IPV6 is disabled by default due to some
# installations failing when IPV6 is used due to misconfigured routers/other problems.
use_ipv6_var = IntVar()
def onIPV6CheckboxToggled():
	GLOBAL_SETTINGS.USE_IPV6 = use_ipv6_var.get()
c = Checkbutton(rootWindow, text="Enable IPv6", var=use_ipv6_var, command=onIPV6CheckboxToggled)
c.pack()

rootWindow.mainloop()
コード例 #44
0
class ProblemBrowser(object):
    def __init__(self):
        self.action = None
        self.root = root = Tk()
        root.title('Never gonna fold you up')
        root.protocol("WM_DELETE_WINDOW", self.close)

        root.pack_propagate(True)

        scrollbar = Scrollbar(root, orient=tkinter.VERTICAL)
        self.problem_list = Listbox(root, exportselection=False, yscrollcommand=scrollbar.set)
        self.problem_list.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        scrollbar.config(command=self.problem_list.yview)
        scrollbar.pack(side=tkinter.LEFT, fill=tkinter.Y)
        self.problem_list.bind('<<ListboxSelect>>', lambda evt: self.populate_problem_canvas())

        self.problem_canvas = Canvas(root, bd=1, relief=tkinter.SUNKEN, width=500, height=500)
        self.problem_canvas.pack(expand=True, fill=tkinter.BOTH, side=tkinter.LEFT)
        self.problem_canvas.bind("<Configure>", lambda evt: self.populate_problem_canvas())

        button_frame = Frame(root)
        button_frame.pack(fill=tkinter.Y, side=tkinter.LEFT)

        # Reposition the figure so it's center of mass is at 0.5, 0.5
        v = IntVar()
        self.center_cb = Checkbutton(button_frame, text="center", variable=v, command=lambda: self.populate_problem_canvas())
        self.center_cb.var = v
        self.center_cb.pack(side=tkinter.TOP)

        # Use meshes.reconstruct_facets instead of polygon/hole logic.
        v = IntVar()
        self.reconstruct_cb = Checkbutton(button_frame, text="reconstruct", variable=v, command=lambda: self.populate_problem_canvas())
        self.reconstruct_cb.var = v
        self.reconstruct_cb.pack(side=tkinter.TOP)

        self.populate_problems()
        self.current_problem_name = None
        self.current_problem = None


    def populate_problems(self):
        self.problem_list.delete(0, tkinter.END)
        for file in sorted((get_root() / 'problems').iterdir()):
            self.problem_list.insert(tkinter.END, file.stem)


    def populate_problem_canvas(self):
        sel = self.problem_list.curselection()
        if not sel: return
        assert len(sel) == 1
        name = self.problem_list.get(sel[0])
        if name != self.current_problem_name:
            self.current_problem_name = name
            self.current_problem = load_problem(name)
        if self.current_problem:
            p = self.current_problem
            if self.center_cb.var.get():
                p = center_problem(p)
            if self.reconstruct_cb.var.get():
                facets = meshes.reconstruct_facets(p)
                facets = meshes.keep_real_facets(facets, p)
                skeleton = [e for f in facets for e in edges_of_a_facet(f)]
                p = Problem(facets, skeleton)
            draw_problem(self.problem_canvas, p)


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

    def close(self):
        if self.root:
            self.root.destroy()
            self.root = None
コード例 #45
0
ファイル: SideWindow.py プロジェクト: Astron/panda3d
class sideWindow(AppShell):
    #################################################################
    # sideWindow(AppShell)
    # This class will open a side window wich contains a scene graph and
    # a world setting page.
    #################################################################
    appversion      = '1.0'
    appname         = 'Navigation Window'
    frameWidth      = 325
    frameHeight     = 580
    frameIniPosX    = 0
    frameIniPosY    = 110
    padx            = 0
    pady            = 0

    lightEnable = 0
    ParticleEnable = 0
    basedriveEnable = 0
    collision = 0
    backface = 0
    texture = 1
    wireframe = 0

    enableBaseUseDrive = 0

    def __init__(self, worldColor,lightEnable,ParticleEnable, basedriveEnable,collision,
                 backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent = None, nodePath = render, **kw):
        self.worldColor = worldColor
        self.lightEnable = lightEnable
        self.ParticleEnable = ParticleEnable
        self.basedriveEnable = basedriveEnable
        self.collision = collision
        self.backface = backface
        self.texture = texture
        self.wireframe = wireframe
        self.grid = grid
        self.enableAutoCamera = enableAutoCamera
        self.widgetVis = widgetVis

        # Define the megawidget options.
        optiondefs = (
            ('title',       self.appname,       None),
            )
        self.defineoptions(kw, optiondefs)

        if parent == None:
            self.parent = Toplevel()
        else:
            self.parent = parent

        AppShell.__init__(self, self.parent)
        self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY))

        self.parent.resizable(False,False) ## Disable the ability to resize for this Window.

    def appInit(self):
        print('----SideWindow is Initialized!!')

    def createInterface(self):
        # The interior of the toplevel panel
        interior = self.interior()
        mainFrame = Frame(interior)
        ## Creat NoteBook
        self.notebookFrame = Pmw.NoteBook(mainFrame)
        self.notebookFrame.pack(fill=tkinter.BOTH,expand=1)
        sgePage = self.notebookFrame.add('Tree Graph')
        envPage = self.notebookFrame.add('World Setting')
        self.notebookFrame['raisecommand'] = self.updateInfo

        ## Tree Grapgh Page
        self.SGE = seSceneGraphExplorer.seSceneGraphExplorer(
            sgePage, nodePath = render,
            scrolledCanvas_hull_width = 270,
            scrolledCanvas_hull_height = 570)
        self.SGE.pack(fill = tkinter.BOTH, expand = 0)

        ## World Setting Page
        envPage = Frame(envPage)
        pageFrame = Frame(envPage)
        self.LightingVar = IntVar()
        self.LightingVar.set(self.lightEnable)
        self.LightingButton = Checkbutton(
            pageFrame,
            text = 'Enable Lighting',
            variable = self.LightingVar,
            command = self.toggleLights)
        self.LightingButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.CollisionVar = IntVar()
        self.CollisionVar.set(self.collision)
        self.CollisionButton = Checkbutton(
            pageFrame,
            text = 'Show Collision Object',
            variable = self.CollisionVar,
            command = self.showCollision)
        self.CollisionButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.ParticleVar = IntVar()
        self.ParticleVar.set(self.ParticleEnable)
        self.ParticleButton = Checkbutton(
            pageFrame,
            text = 'Show Particle Dummy',
            variable = self.ParticleVar,
            command = self.enableParticle)
        self.ParticleButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.baseUseDriveVar = IntVar()
        self.baseUseDriveVar.set(self.basedriveEnable)
        self.baseUseDriveButton = Checkbutton(
            pageFrame,
            text = 'Enable base.usedrive',
            variable = self.baseUseDriveVar,
            command = self.enablebaseUseDrive)
        self.baseUseDriveButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.backfaceVar = IntVar()
        self.backfaceVar.set(self.backface)
        self.backfaceButton = Checkbutton(
            pageFrame,
            text = 'Enable BackFace',
            variable = self.backfaceVar,
            command = self.toggleBackface)
        self.backfaceButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.textureVar = IntVar()
        self.textureVar.set(self.texture)
        self.textureButton = Checkbutton(
            pageFrame,
            text = 'Enable Texture',
            variable = self.textureVar,
            command = self.toggleTexture)
        self.textureButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.wireframeVar = IntVar()
        self.wireframeVar.set(self.wireframe)
        self.wireframeButton = Checkbutton(
            pageFrame,
            text = 'Enable Wireframe',
            variable = self.wireframeVar,
            command = self.toggleWireframe)
        self.wireframeButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.gridVar = IntVar()
        self.gridVar.set(self.grid)
        self.gridButton = Checkbutton(
            pageFrame,
            text = 'Enable Grid',
            variable = self.gridVar,
            command = self.toggleGrid)
        self.gridButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.widgetVisVar = IntVar()
        self.widgetVisVar.set(self.widgetVis)
        self.widgetVisButton = Checkbutton(
            pageFrame,
            text = 'Enable WidgetVisible',
            variable = self.widgetVisVar,
            command = self.togglewidgetVis)
        self.widgetVisButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.enableAutoCameraVar = IntVar()
        self.enableAutoCameraVar.set(self.enableAutoCamera)
        self.enableAutoCameraButton = Checkbutton(
            pageFrame,
            text = 'Enable Auto Camera Movement for Loading Objects',
            variable = self.enableAutoCameraVar,
            command = self.toggleAutoCamera)
        self.enableAutoCameraButton.pack(side=tkinter.LEFT, expand=False)
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        pageFrame = Frame(envPage)
        self.backgroundColor = ColorEntry(
            pageFrame, text = 'BG Color', value=self.worldColor)
        self.backgroundColor['command'] = self.setBackgroundColorVec
        self.backgroundColor['resetValue'] = [0,0,0,0]
        self.backgroundColor.pack(side=tkinter.LEFT, expand=False)
        self.bind(self.backgroundColor, 'Set background color')
        pageFrame.pack(side=tkinter.TOP, fill=tkinter.X, expand=True)

        envPage.pack(expand=False)

        ## Set all stuff done
        self.notebookFrame.setnaturalsize()
        mainFrame.pack(fill = 'both', expand = 1)


    def createMenuBar(self):
        # We don't need menu bar here.
        self.menuBar.destroy()

    def onDestroy(self, event):
        #################################################################
        # onDestroy(self, event)
        # This function will be called when user closed the side window.
        # Here we will send out a message with whole data set we will need
        # for the next time user open the side window.
        #################################################################
        messenger.send('SW_close',[self.worldColor,
                                   self.lightEnable,
                                   self.ParticleEnable,
                                   self.basedriveEnable,
                                   self.collision,
                                   self.backface,
                                   self.texture,
                                   self.wireframe,
                                   self.grid,
                                   self.widgetVis,
                                   self.enableAutoCamera])
        '''
        If you have open any thing, please rewrite here!
        '''
        pass

    ###############################
    def updateInfo(self, page = 'Tree Graph'):
        #################################################################
        # updateInfo(self, page = 'Tree Graph')
        # This function will be called when each time user change the main
        # page of the window.
        # What it dose is to call right function to restore the data for current selected page.
        #################################################################
        if page=='Tree Graph':
            self.updateTreeGraph()
        elif page == 'World Setting':
            self.updateWorldSetting()

    def updateTreeGraph(self):
        #################################################################
        # updateTreeGraph(self)
        # When scene graoh page has been opend, call sceneGraphExplorer to
        # updata the tree.
        #################################################################
        self.SGE.update()
        pass

    def updateWorldSetting(self):
        #################################################################
        # updateWorldSetting(self)
        # When world setting page has been selected, this function will
        # reset those check box in the page to reflect the current world setting.
        #################################################################
        self.LightingVar.set(self.lightEnable)

        self.CollisionVar.set(self.collision)
        self.ParticleVar.set(self.ParticleEnable)
        self.baseUseDriveVar.set(self.basedriveEnable)
        self.backgroundColor.set(value = self.worldColor)
        pass

    def toggleLights(self):
        #################################################################
        # toggleLights(self)
        # send out a message to let sceneEditor know we need to toggle the light.
        # Then, sceneEditor will pass the message to dataHolder to disable/enable
        # the lights. (lightManager is inside the dataHolder)
        #################################################################
        self.lightEnable = (self.lightEnable+1)%2
        messenger.send('SW_lightToggle')
        pass

    def showCollision(self):
        #################################################################
        # showCollision(self)
        # This function will send out a message to sceneEditor to toggle
        # the visibility of collision objects.
        #################################################################
        self.collision = (self.collision+1)%2
        messenger.send('SW_collisionToggle', [self.collision])
        pass

    def enableParticle(self):
        #################################################################
        # enableParticle(self)
        # This function will send out a message to sceneEditor to toggle
        # the visibility of particle objects.
        #################################################################
        self.ParticleEnable = (self.ParticleEnable+1)%2
        messenger.send('SW_particleToggle', [self.ParticleEnable])
        pass

    def enablebaseUseDrive(self):
        #################################################################
        # enablebaseUseDrive(self)
        # This function will toggle the usage of base.useDrive.
        # Well, it may not usefull at all.
        #
        # We won't send out any message in this time to notice
        # the sceneEditor this event happend.
        # In the other hand, we will restore it back when
        # the side window has been closed.
        #
        #################################################################
        if self.enableBaseUseDrive==0:
            print('Enabled')
            base.useDrive()
            self.enableBaseUseDrive = 1
        else:
            print('disabled')
            #base.useTrackball()
            base.disableMouse()
            self.enableBaseUseDrive = 0
        self.basedriveEnable = (self.basedriveEnable+1)%2
        pass

    def toggleBackface(self):
        #################################################################
        # toggleBackface(self)
        # This function will toggle the back face setting. so it will
        # render the polygon with two sides.
        #################################################################
        base.toggleBackface()
        self.backface = (self.backface+1)%2
        return

    def toggleBackfaceFromMainW(self):
        #################################################################
        # toggleBackfaceFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the back face setting in the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.backface = (self.backface+1)%2
        self.backfaceButton.toggle()
        return

    def toggleTexture(self):
        #################################################################
        # toggleTexture(self)
        # This function will toggle the txture using option for the whole scene.
        #################################################################
        base.toggleTexture()
        self.texture = (self.texture+1)%2
        return

    def toggleTextureFromMainW(self):
        #################################################################
        # toggleTextureFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the texture usage from the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.texture = (self.texture+1)%2
        self.textureButton.toggle()
        return

    def toggleWireframe(self):
        #################################################################
        # toggleWireframe(self)
        # This function will toggle the wire frame mode.
        #################################################################
        base.toggleWireframe()
        self.wireframe = (self.wireframe+1)%2
        return

    def toggleWireframeFromMainW(self):
        #################################################################
        # toggleWireframeFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the wire frame mode in the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.wireframe = (self.wireframe+1)%2
        self.wireframeButton.toggle()
        return

    def toggleGrid(self):
        #################################################################
        # toggleGrid(self)
        # This function will toggle the usage of the grid.
        #################################################################
        self.grid = (self.grid+1)%2
        if self.grid==1:
            SEditor.grid.enable()
        else:
            SEditor.grid.disable()

    def togglewidgetVis(self):
        #################################################################
        # togglewidgetVis(self)
        # This function will toggle the visibility of the widget of the grid.
        #################################################################
        self.widgetVis = (self.widgetVis+1)%2
        SEditor.toggleWidgetVis()
        if SEditor.widget.fActive:
                messenger.send('shift-f')
        return

    def toggleWidgetVisFromMainW(self):
        #################################################################
        # toggleWidgetVisFromMainW(self)
        # This function is called by sceneEditor when user used hot key
        # to toggle the visibility of widgets ('v') from the main panda window.
        # In here we will only reset the flag and reset the state of
        # check box
        #################################################################
        self.widgetVis = (self.widgetVis+1)%2
        self.widgetVisButton.toggle()
        return

    def setBackgroundColorVec(self,color):
        #################################################################
        # setBackgroundColorVec(self,color)
        # Call back function
        # This will be called from the colorEntry on the world setting page.
        # The "color" here is a list containing three integer data, R, G and B.
        #################################################################
        base.setBackgroundColor(color[0]/255.0,
                                color[1]/255.0,
                                color[2]/255.0)
        self.worldColor = [color[0],color[1],color[2],0]

    def toggleAutoCamera(self):
        #################################################################
        # toggleAutoCamera(self)
        # This function will toggle the usage of the auto-camera movement
        # when user loaded model or actor into the scene.
        #################################################################
        self.enableAutoCamera = (self.enableAutoCamera+1)%2
        SEditor.toggleAutoCamera()
        return

    def selectPage(self,page='Tree Graph'):
        #################################################################
        #################################################################
        self.notebookFrame.selectpage(page)