当前位置: 首页>>代码示例>>Python>>正文


Python BooleanVar.get方法代码示例

本文整理汇总了Python中tkinter.BooleanVar.get方法的典型用法代码示例。如果您正苦于以下问题:Python BooleanVar.get方法的具体用法?Python BooleanVar.get怎么用?Python BooleanVar.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.BooleanVar的用法示例。


在下文中一共展示了BooleanVar.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_invalid_value_domain

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
 def test_invalid_value_domain(self):
     v = BooleanVar(self.root, name="name")
     self.root.globalsetvar("name", "value")
     with self.assertRaises(ValueError):
         v.get()
     self.root.globalsetvar("name", "1.0")
     with self.assertRaises(ValueError):
         v.get()
开发者ID:LesyaMazurevich,项目名称:python-1,代码行数:10,代码来源:test_variables.py

示例2: test_get

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
 def test_get(self):
     v = BooleanVar(self.root, True, "name")
     self.assertIs(v.get(), True)
     self.root.globalsetvar("name", "0")
     self.assertIs(v.get(), False)
     self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1)
     self.assertIs(v.get(), True)
     self.root.globalsetvar("name", 0)
     self.assertIs(v.get(), False)
     self.root.globalsetvar("name", "on")
     self.assertIs(v.get(), True)
开发者ID:Cartmanfku,项目名称:cpython,代码行数:13,代码来源:test_variables.py

示例3: test_invalid_value_domain

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
 def test_invalid_value_domain(self):
     false = 0 if self.root.wantobjects() else "0"
     v = BooleanVar(self.root, name="name")
     with self.assertRaises(TclError):
         v.set("value")
     self.assertEqual(self.root.globalgetvar("name"), false)
     self.root.globalsetvar("name", "value")
     with self.assertRaises(ValueError):
         v.get()
     self.root.globalsetvar("name", "1.0")
     with self.assertRaises(ValueError):
         v.get()
开发者ID:Cartmanfku,项目名称:cpython,代码行数:14,代码来源:test_variables.py

示例4: Preferences

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class Preferences(Frame):
    def __init__(self, client):
        # Basic setup
        super(Preferences, self).__init__()
        self.client = client

        # Setup the variables used
        self.echo_input = BooleanVar()
        self.echo_input.set(self.client.config['UI'].getboolean('echo_input'))
        self.echo_input.trace("w", self.echo_handler)
        self.logging = BooleanVar()
        self.logging.set(self.client.config['logging'].getboolean('log_session'))
        self.logging.trace('w', self.logging_handler)
        self.log_dir = self.client.config['logging']['log_directory']

        # Build the actual window and widgets
        prefs = Toplevel(self)
        prefs.wm_title("Preferences")
        echo_input_label = Label(prefs, text="Echo Input:")
        logging_label = Label(prefs, text='Log to file:')
        echo_checkbox = Checkbutton(prefs, variable=self.echo_input)
        logging_checkbox = Checkbutton(prefs, variable=self.logging)
        logging_button_text = 'Choose file...' if self.log_dir == "" else self.log_dir
        logging_button = Button(prefs, text=logging_button_text, command=self.logging_pick_location)

        # Pack 'em in.
        echo_input_label.grid(row=0, column=0)
        echo_checkbox.grid(row=0, column=1)
        logging_label.grid(row=1, column=0)
        logging_checkbox.grid(row=1, column=1)
        logging_button.grid(row=1, column=2)

    def logging_pick_location(self):
        location = askdirectory(initialdir="%UserProfile%\Documents\\")
        self.client.config['logging']['log_directory'] = location
        self.write_config()

    def echo_handler(self, arg1, arg2, mode):
        pprint(self.echo_input.get())
        self.client.config['UI']['echo_input'] = 'yes' if self.echo_input.get() else 'no'
        self.write_config()

    def logging_handler(self, arg1, arg2, mode):
        self.client.config['logging']['log_session'] = 'yes' if self.logging.get else 'no'
        self.write_config()

    def write_config(self, file='config.ini'):
        self.client.config.write(open(file, 'w'))
开发者ID:Errorprone85,项目名称:TEC-Client,代码行数:50,代码来源:preferences.py

示例5: __init__

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class KRCCModule:
  __metaclass__ = ABCMeta

  def __init__(self):
    self._terminate = BooleanVar(False)
    self._id = StringVar(False)

  @property
  def terminate(self):
    return self._terminate.get()

  @terminate.setter
  def terminate(self, value):
    self._terminate.set(value)

  @property
  def id(self):
    return self._id.get()

  @id.setter
  def id(self, value):
    self._id.set(value)

  @abstractproperty
  def name(self):
    pass

  @abstractmethod
  def run(self):
    pass
开发者ID:jsartisohn,项目名称:krpc_scripts,代码行数:32,代码来源:krcc_module.py

示例6: Application

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class Application(Frame):
    "application frame"

    def __init__(self, master):
        """
         @ brief
             initialize the frame with master
         @ params
             self    -- new instance
             master  -- root container
             """
        super(Application, self).__init__(master)

        self.grid()
        self.__createWidgets()

    def __createWidgets(self):
        """
            @ brief
                create the widgets
                """
        Label(self, text="input dictionary tree: ").grid(row=0, column=0, sticky=W)

        self.dict_with_label = BooleanVar()
        Checkbutton(self, text="label edge", variable=self.dict_with_label).grid(row=0, column=0, sticky=E)

        self.source_text = Text(self, width=40, wrap=WORD)
        self.source_text.grid(row=1, column=0, sticky=W)

        Button(self, text="visual tree", command=self.__submitSource).grid(row=2, column=0, sticky=W)

        Button(self, text="clear", command=self.__clearText).grid(row=2, column=0, sticky=E)

    def __submitSource(self):
        "listener for visual button"
        source = self.source_text.get("1.0", END)
        if "" != source:
            current_view = Draw(self)
            current_view.initDot()
            current_view.setSource(source, self.dict_with_label.get())
            current_view.show()

    def __clearText(self):
        "clear button callback"
        self.source_text.delete(0.0, END)
开发者ID:smileboywtu,项目名称:VisualJson,代码行数:47,代码来源:application.py

示例7: OBCheckbutton

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class OBCheckbutton(Tk):
    """ Messagebox with only one button and a checkbox below the button
        for instance to add a 'Do not show this again' option """

    def __init__(self, title="", message="", button="Ok", image=None,
                 checkmessage="", style="clam", **options):
        """
            Create a messagebox with one button and a checkbox below the button:
                parent: parent of the toplevel window
                title: message box title
                message: message box text
                button: message displayed on the button
                image: image displayed at the left of the message
                checkmessage: message displayed next to the checkbox
                **options: other options to pass to the Toplevel.__init__ method
        """
        Tk.__init__(self, **options)
        self.resizable(False, False)
        self.title(title)
        s = Style(self)
        s.theme_use(style)
        if image:
            Label(self, text=message, wraplength=335,
                  font="Sans 11", compound="left",
                  image=image).grid(row=0, padx=10, pady=(10, 0))
        else:
            Label(self, text=message, wraplength=335,
                  font="Sans 11").grid(row=0, padx=10, pady=(10, 0))
        b = Button(self, text=button, command=self.destroy)
        b.grid(row=2, padx=10, pady=10)
        self.var = BooleanVar(self)
        c = Checkbutton(self, text=checkmessage, variable=self.var)
        c.grid(row=1, padx=10, pady=0, sticky="e")
        self.grab_set()
        b.focus_set()
        self.wait_window(self)

    def get_check(self):
        return self.var.get()
开发者ID:j4321,项目名称:Sudoku-Tk,代码行数:41,代码来源:custom_messagebox.py

示例8: test_get

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
 def test_get(self):
     v = BooleanVar(self.root, True, "name")
     self.assertAlmostEqual(True, v.get())
     self.root.globalsetvar("name", "0")
     self.assertAlmostEqual(False, v.get())
开发者ID:LesyaMazurevich,项目名称:python-1,代码行数:7,代码来源:test_variables.py

示例9: test_default

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
 def test_default(self):
     v = BooleanVar(self.root)
     self.assertEqual(False, v.get())
开发者ID:LesyaMazurevich,项目名称:python-1,代码行数:5,代码来源:test_variables.py

示例10: __init__

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class SearchEngine:
    """Handles searching a text widget for Find, Replace, and Grep."""

    def __init__(self, root):
        '''Initialize Variables that save search state.

        The dialogs bind these to the UI elements present in the dialogs.
        '''
        self.root = root  # need for report_error()
        self.patvar = StringVar(root, '')   # search pattern
        self.revar = BooleanVar(root, False)   # regular expression?
        self.casevar = BooleanVar(root, False)   # match case?
        self.wordvar = BooleanVar(root, False)   # match whole word?
        self.wrapvar = BooleanVar(root, True)   # wrap around buffer?
        self.backvar = BooleanVar(root, False)   # search backwards?

    # Access methods

    def getpat(self):
        return self.patvar.get()

    def setpat(self, pat):
        self.patvar.set(pat)

    def isre(self):
        return self.revar.get()

    def iscase(self):
        return self.casevar.get()

    def isword(self):
        return self.wordvar.get()

    def iswrap(self):
        return self.wrapvar.get()

    def isback(self):
        return self.backvar.get()

    # Higher level access methods

    def setcookedpat(self, pat):
        "Set pattern after escaping if re."
        # called only in SearchDialog.py: 66
        if self.isre():
            pat = re.escape(pat)
        self.setpat(pat)

    def getcookedpat(self):
        pat = self.getpat()
        if not self.isre():  # if True, see setcookedpat
            pat = re.escape(pat)
        if self.isword():
            pat = r"\b%s\b" % pat
        return pat

    def getprog(self):
        "Return compiled cooked search pattern."
        pat = self.getpat()
        if not pat:
            self.report_error(pat, "Empty regular expression")
            return None
        pat = self.getcookedpat()
        flags = 0
        if not self.iscase():
            flags = flags | re.IGNORECASE
        try:
            prog = re.compile(pat, flags)
        except re.error as what:
            args = what.args
            msg = args[0]
            col = args[1] if len(args) >= 2 else -1
            self.report_error(pat, msg, col)
            return None
        return prog

    def report_error(self, pat, msg, col=-1):
        # Derived class could override this with something fancier
        msg = "Error: " + str(msg)
        if pat:
            msg = msg + "\nPattern: " + str(pat)
        if col >= 0:
            msg = msg + "\nOffset: " + str(col)
        tkMessageBox.showerror("Regular expression error",
                               msg, master=self.root)

    def search_text(self, text, prog=None, ok=0):
        '''Return (lineno, matchobj) or None for forward/backward search.

        This function calls the right function with the right arguments.
        It directly return the result of that call.

        Text is a text widget. Prog is a precompiled pattern.
        The ok parameter is a bit complicated as it has two effects.

        If there is a selection, the search begin at either end,
        depending on the direction setting and ok, with ok meaning that
        the search starts with the selection. Otherwise, search begins
        at the insert mark.

#.........这里部分代码省略.........
开发者ID:10sr,项目名称:cpython,代码行数:103,代码来源:SearchEngine.py

示例11: __init__

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]

#.........这里部分代码省略.........
        OptionMenu(self.toplevel, self.conf_filename, *builtins_list).grid(
            row=row, column=1)
        self.conf_filename.set(builtins_list[0])
        row += 1
        Label(self.toplevel, text='Load Custom Run Def').grid(row=row,
                                                              column=0)
        Button(self.toplevel, text="find file", command=self._ParamFuncFile
               ).grid(row=row, column=1)
        row += 1

        # Mantis Settings
        Label(self.toplevel, text='-'*20+'Mantis Settings'+'-'*20).grid(row=row,
                                                        columnspan=3, column=0)
        row += 1
        Label(self.toplevel, text='(Empty fields use default values)').grid(row=row,
                                                        columnspan=3, column=0)
        row += 1
        Label(self.toplevel, text='Digitization Time').grid(row=row, column=0)
        Entry(self.toplevel, textvariable=self.len_sequenceVar).grid(row=row,
                                                                     column=1)
        Label(self.toplevel, text='[ms]').grid(row=row, column=2, sticky='W')
        row += 1

        Button(self.toplevel, text="Start Run", command=self.DoRun
               ).grid(row=row, column=0)
        Button(self.toplevel, text="ABORT", command=self._Abort, bg='red'
               ).grid(row=row, column=1)
        Label(self.toplevel, textvariable=self.stateVar).grid(row=row, column=2)

    def _ParamFuncFile(self):
        '''
        '''
        self.conf_filename.set(askopenfilename())
        if self.conf_filename.get():
            self._GetParamFuncs()

    def _Abort(self):
        '''
        '''
        self.keep_runningVar.set(False)
        if self.runthread.is_alive():
            print('terminating child process')
            self.runthread.terminate()
        else:
            print('no current thread')
        self.stateVar.set('aborted')

    def _IsRunning(self):
        '''
        '''
        print(self.runthread.is_alive())

    def _GetParamFuncs(self):
        '''
        '''
        fname = self.conf_filename.get()
        if not fname or fname == 'default_run':
            if not 'run_params' in sys.modules:
                from . import default_run as run_params
            else:
                reload(run_params)
        elif fname == 'noise_analysis_run':
            from . import noise_analysis_run as run_params
        else:
            imp.load_source('run_params', fname)
            import run_params
开发者ID:project8,项目名称:Pypeline,代码行数:70,代码来源:data_run_gui.py

示例12: GrepDialog

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class GrepDialog(SearchDialogBase):

    title = "Find in Files Dialog"
    icon = "Grep"
    needwrapbutton = 0

    def __init__(self, root, engine, flist):
        SearchDialogBase.__init__(self, root, engine)
        self.flist = flist
        self.globvar = StringVar(root)
        self.recvar = BooleanVar(root)

    def open(self, text, searchphrase, io=None):
        SearchDialogBase.open(self, text, searchphrase)
        if io:
            path = io.filename or ""
        else:
            path = ""
        dir, base = os.path.split(path)
        head, tail = os.path.splitext(base)
        if not tail:
            tail = ".py"
        self.globvar.set(os.path.join(dir, "*" + tail))

    def create_entries(self):
        SearchDialogBase.create_entries(self)
        self.globent = self.make_entry("In files:", self.globvar)[0]

    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()

    def create_command_buttons(self):
        SearchDialogBase.create_command_buttons(self)
        self.make_button("Search Files", self.default_command, 1)

    def default_command(self, event=None):
        prog = self.engine.getprog()
        if not prog:
            return
        path = self.globvar.get()
        if not path:
            self.top.bell()
            return
        from OutputWindow import OutputWindow  # leave here!
        save = sys.stdout
        try:
            sys.stdout = OutputWindow(self.flist)
            self.grep_it(prog, path)
        finally:
            sys.stdout = save

    def grep_it(self, prog, path):
        dir, base = os.path.split(path)
        list = self.findfiles(dir, base, self.recvar.get())
        list.sort()
        self.close()
        pat = self.engine.getpat()
        print("Searching %r in %s ..." % (pat, path))
        hits = 0
        try:
            for fn in list:
                try:
                    with open(fn, errors='replace') as f:
                        for lineno, line in enumerate(f, 1):
                            if line[-1:] == '\n':
                                line = line[:-1]
                            if prog.search(line):
                                sys.stdout.write("%s: %s: %s\n" %
                                                 (fn, lineno, line))
                                hits += 1
                except OSError as msg:
                    print(msg)
            print(("Hits found: %s\n"
                  "(Hint: right-click to open locations.)"
                  % hits) if hits else "No hits.")
        except AttributeError:
            # Tk window has been closed, OutputWindow.text = None,
            # so in OW.write, OW.text.insert fails.
            pass

    def findfiles(self, dir, base, rec):
        try:
            names = os.listdir(dir or os.curdir)
        except OSError as msg:
            print(msg)
            return []
        list = []
        subdirs = []
        for name in names:
            fn = os.path.join(dir, name)
            if os.path.isdir(fn):
                subdirs.append(fn)
            else:
                if fnmatch.fnmatch(name, base):
#.........这里部分代码省略.........
开发者ID:belzner,项目名称:idle-errors-uap,代码行数:103,代码来源:GrepDialog.py

示例13: GrepDialog

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class GrepDialog(SearchDialogBase):
    "Dialog for searching multiple files."

    title = "Find in Files Dialog"
    icon = "Grep"
    needwrapbutton = 0

    def __init__(self, root, engine, flist):
        """Create search dialog for searching for a phrase in the file system.

        Uses SearchDialogBase as the basis for the GUI and a
        searchengine instance to prepare the search.

        Attributes:
            globvar: Value of Text Entry widget for path to search.
            recvar: Boolean value of Checkbutton widget
                    for traversing through subdirectories.
        """
        SearchDialogBase.__init__(self, root, engine)
        self.flist = flist
        self.globvar = StringVar(root)
        self.recvar = BooleanVar(root)

    def open(self, text, searchphrase, io=None):
        "Make dialog visible on top of others and ready to use."
        SearchDialogBase.open(self, text, searchphrase)
        if io:
            path = io.filename or ""
        else:
            path = ""
        dir, base = os.path.split(path)
        head, tail = os.path.splitext(base)
        if not tail:
            tail = ".py"
        self.globvar.set(os.path.join(dir, "*" + tail))

    def create_entries(self):
        "Create base entry widgets and add widget for search path."
        SearchDialogBase.create_entries(self)
        self.globent = self.make_entry("In files:", self.globvar)[0]

    def create_other_buttons(self):
        "Add check button to recurse down subdirectories."
        btn = Checkbutton(
                self.make_frame()[0], variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")

    def create_command_buttons(self):
        "Create base command buttons and add button for search."
        SearchDialogBase.create_command_buttons(self)
        self.make_button("Search Files", self.default_command, 1)

    def default_command(self, event=None):
        """Grep for search pattern in file path. The default command is bound
        to <Return>.

        If entry values are populated, set OutputWindow as stdout
        and perform search.  The search dialog is closed automatically
        when the search begins.
        """
        prog = self.engine.getprog()
        if not prog:
            return
        path = self.globvar.get()
        if not path:
            self.top.bell()
            return
        from idlelib.outwin import OutputWindow  # leave here!
        save = sys.stdout
        try:
            sys.stdout = OutputWindow(self.flist)
            self.grep_it(prog, path)
        finally:
            sys.stdout = save

    def grep_it(self, prog, path):
        """Search for prog within the lines of the files in path.

        For the each file in the path directory, open the file and
        search each line for the matching pattern.  If the pattern is
        found,  write the file and line information to stdout (which
        is an OutputWindow).
        """
        dir, base = os.path.split(path)
        list = self.findfiles(dir, base, self.recvar.get())
        list.sort()
        self.close()
        pat = self.engine.getpat()
        print(f"Searching {pat!r} in {path} ...")
        hits = 0
        try:
            for fn in list:
                try:
                    with open(fn, errors='replace') as f:
                        for lineno, line in enumerate(f, 1):
                            if line[-1:] == '\n':
                                line = line[:-1]
                            if prog.search(line):
                                sys.stdout.write(f"{fn}: {lineno}: {line}\n")
#.........这里部分代码省略.........
开发者ID:1st1,项目名称:cpython,代码行数:103,代码来源:grep.py

示例14: FrameMapping

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class FrameMapping(FrameCustomItem):
    """Holds and visualizes a Map between two columns of different datasets"""
    row_index = None

    is_key = None
    src_reference = None
    src_datatype = None
    src_cast_to = None
    dest_table = None
    curr_data = None
    curr_raw_data = None
    mapping = None

    preview = None
    dest_reference = None

    def __init__(self, _master, _mapping = None,
                 _on_get_source_references = None,
                 _on_get_destination_references = None,
                 _on_select = None):
        super(FrameMapping, self).__init__(_master)


        # Add monitored variables.
        self.is_key = BooleanVar()
        self.src_reference = StringVar()
        self.src_datatype = StringVar()
        self.curr_data = StringVar()

        self.result_cast_to = StringVar()
        self.preview = StringVar()

        self.dest_reference = StringVar()

        self.on_get_source_references = _on_get_source_references
        self.on_get_destination_references = _on_get_destination_references

        self.on_select = _on_select
        self.init_widgets()

        self.mapping = _mapping



        if _mapping is not None:
            self.mapping_to_gui()


    def mapping_to_gui(self):

        self.src_reference.set(str(empty_when_none(self.mapping.src_reference)))
        self.dest_reference.set(str(empty_when_none(self.mapping.dest_reference)))
        self.src_datatype.set(self.mapping.src_datatype)
        self.is_key.set(bool_to_binary_int(self.mapping.is_key))

    def gui_to_mapping(self):

        self.mapping.src_reference = self.src_reference.get()
        self.mapping.dest_reference = self.dest_reference.get()

        self.mapping.is_key = binary_int_to_bool(self.is_key.get())

    def reload_references(self):
        self.cb_source_ref['values'] = self.get_source_references()
        self.cb_dest_ref['values'] = self.get_destination_references()


    def get_source_references(self, _force = None):
        if self.on_get_source_references:
            return self.on_get_source_references(_force)

    def get_destination_references(self, _force = None):
        if self.on_get_destination_references:
            return self.on_get_destination_references( _force)


    def on_change_source_ref(self, *args):
        # reload dataset.
        pass


    def init_widgets(self):

        """Init all widgets"""

        # Source reference
        self.cb_source_ref = ttk.Combobox(self, textvariable=self.src_reference, state='normal')
        self.cb_source_ref['values'] = self.get_source_references()
        self.cb_source_ref.pack(side=LEFT, fill=X, expand=1)


        # Data type label
        self.l_data_type = ttk.Label(self, textvariable=self.src_datatype, width=8)
        self.src_datatype.set("Not set")

        self.l_data_type.pack(side=LEFT)

        # Dest reference
        self.cb_dest_ref = ttk.Combobox(self, textvariable=self.dest_reference, state='normal')
        self.cb_dest_ref['values'] = self.get_destination_references()
#.........这里部分代码省略.........
开发者ID:OptimalBPM,项目名称:qal,代码行数:103,代码来源:frame_mapping.py

示例15: MarkovDemo

# 需要导入模块: from tkinter import BooleanVar [as 别名]
# 或者: from tkinter.BooleanVar import get [as 别名]
class MarkovDemo(Frame):

    "MarkovDemo(master=None, **kw) -> MarkovDemo instance"

    TEXT = dict(height=2, width=46, wrap=WORD)  # Text Options
    GRID = dict(padx=5, pady=5)                 # Grid Options

    # Initialize a MarkovDemo instance with a GUI for interaction.

    def __init__(self, master=None, **kw):
        "Initialize the MarkovDemo instance's widgets and settings."
        super().__init__(master, **kw)
        self.build_widgets()
        self.place_widgets()
        self.setup_widgets()
        self.grid_rowconfigure(2, weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.key = self.primer = None

    def build_widgets(self):
        "Build the various widgets that will be used in the program."
        # Create processing frame widgets.
        self.processing_frame = LabelFrame(self, text='Processing Mode:')
        self.mode_var = StringVar(self, 'encode')
        self.decode_button = Radiobutton(self.processing_frame,
                                         text='Decode Cipher-Text',
                                         command=self.handle_radiobuttons,
                                         value='decode',
                                         variable=self.mode_var)
        self.encode_button = Radiobutton(self.processing_frame,
                                         text='Encode Plain-Text',
                                         command=self.handle_radiobuttons,
                                         value='encode',
                                         variable=self.mode_var)
        self.freeze_var = BooleanVar(self, False)
        self.freeze_button = Checkbutton(self.processing_frame,
                                         text='Freeze Key & Primer',
                                         command=self.handle_checkbutton,
                                         offvalue=False,
                                         onvalue=True,
                                         variable=self.freeze_var)
        # Create encoding frame widgets.
        self.encoding_frame = LabelFrame(self, text='Encoding Options:')
        self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
        self.chain_size_entry = Entry(self.encoding_frame)
        self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
        self.plain_text_entry = Entry(self.encoding_frame)
        # Create input frame widgets.
        self.input_frame = LabelFrame(self, text='Input Area:')
        self.input_text = ScrolledText(self.input_frame, **self.TEXT)
        # Create output frame widgets.
        self.output_frame = LabelFrame(self, text='Output Area:')
        self.output_text = ScrolledText(self.output_frame, **self.TEXT)

    def place_widgets(self):
        "Place the widgets where they belong in the MarkovDemo frame."
        # Locate processing frame widgets.
        self.processing_frame.grid(sticky=EW, **self.GRID)
        self.decode_button.grid(row=0, column=0, **self.GRID)
        self.encode_button.grid(row=0, column=1, **self.GRID)
        self.freeze_button.grid(row=0, column=2, **self.GRID)
        # Locate encoding frame widgets.
        self.encoding_frame.grid(sticky=EW, **self.GRID)
        self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID)
        self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID)
        self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID)
        self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID)
        self.encoding_frame.grid_columnconfigure(1, weight=1)
        # Locate input frame widgets.
        self.input_frame.grid(sticky=NSEW, **self.GRID)
        self.input_text.grid(sticky=NSEW, **self.GRID)
        self.input_frame.grid_rowconfigure(0, weight=1)
        self.input_frame.grid_columnconfigure(0, weight=1)
        # Locate output frame widgets.
        self.output_frame.grid(sticky=NSEW, **self.GRID)
        self.output_text.grid(sticky=NSEW, **self.GRID)
        self.output_frame.grid_rowconfigure(0, weight=1)
        self.output_frame.grid_columnconfigure(0, weight=1)

    def setup_widgets(self):
        "Setup each widget's configuration for the events they handle."
        self.input_text.bind('<Key>', self.handle_key_events)
        self.input_text.bind('<Control-Key-a>', self.handle_control_a)
        self.input_text.bind('<Control-Key-/>', lambda event: 'break')
        self.output_text['state'] = DISABLED
        self.output_text.bind('<Control-Key-a>', self.handle_control_a)
        self.output_text.bind('<Control-Key-/>', lambda event: 'break')

    ########################################################################

    # Take care of any special event needing dedicated processing.

    def handle_radiobuttons(self):
        "Change the interface based on the encoding / decoding setting."
        if self.encrypting:
            self.freeze_button.grid()
            if not self.freeze_var.get():
                self.encoding_frame.grid()
        else:
#.........这里部分代码省略.........
开发者ID:jacob-carrier,项目名称:code,代码行数:103,代码来源:recipe-578076.py


注:本文中的tkinter.BooleanVar.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。