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


Python StringVar.get方法代码示例

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


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

示例1: DlgLogin

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class DlgLogin(Dialog):
    def body(self, master, cfg={}):
        "place user dialog widgets"
        self.config = cfg
        self.config["OK button"] = False
        self.site = StringVar()
        self.site.set(cfg.get("site", ""))
        self.login = StringVar()
        self.login.set(cfg.get("user", ""))
        self.password = StringVar()
        self.password.set(str(cfg.get("password", "")))
        site = Entry(master, width=15, textvariable=self.site)
        site.grid(column=1, row=0, sticky="e")
        Label(master, text=_("Site:")).grid(column=0, row=0, sticky="w")
        loge = Entry(master, width=15, textvariable=self.login)
        loge.grid(column=1, row=1, sticky="e")
        Label(master, text=_("Username:")).grid(column=0, row=1, sticky="w")
        pase = Entry(master, width=15, textvariable=self.password, show="*")
        pase.grid(column=1, row=2, sticky="e")
        Label(master, text=_("Password:")).grid(column=0, row=2, sticky="w")
        self.to_remember = IntVar()
        self.to_remember.set(cfg.get("remember_passwd", 1))
        chk1 = Checkbutton(master, text="Remember",
                           variable=self.to_remember)
        chk1.grid(column=0, row=3, sticky="w", columnspan=2)
        self.resizable(width=0, height=0)
        return loge

    def apply(self):
        "On ok button pressed"
        self.config["remember_passwd"] = self.to_remember.get()
        self.config["site"] = self.site.get()
        self.config["user"] = self.login.get()
        self.config["password"].set_password(self.password.get())
        self.config["OK button"] = True
开发者ID:Lysovenko,项目名称:OTRS_US,代码行数:37,代码来源:dialogs.py

示例2: DlgDelay

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class DlgDelay(Dialog):
    def body(self, master, cfg={}):
        "place user dialog widgets"
        self.config = cfg
        self.config["OK button"] = False
        self.delay = StringVar()
        self.delay.set(cfg.get("delay", ""))
        self.edelay = Entry(master, width=15, textvariable=self.delay)
        self.edelay.grid(column=1, row=0, sticky="e")
        Label(master, text=_("Delay:")).grid(column=0, row=0, sticky="w")
        self.resizable(width=0, height=0)
        return self.edelay

    def validate(self):
        try:
            flt = float(self.delay.get())
        except ValueError:
            return self.edelay
        if flt < 0 or flt > 5:
            return self.edelay
        return None

    def apply(self):
        "On ok button pressed"
        self.config["delay"] = self.delay.get()
        self.config["OK button"] = True
开发者ID:Lysovenko,项目名称:jml,代码行数:28,代码来源:dialogs.py

示例3: ParseGUI

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class ParseGUI(object):
    """Class used for the GUI
    The object parameter is the root widget for the Tkinter GUI
    """
    def __init__(self, master):
        """Constructor method

        :param master: A "master" wigdet
        """
        self.mainframe = Frame(master)  # Create a Frame child widget
        self.mainframe.pack()  # Make the widget visible

        self.path = ''  # Define default path for the .xmcd file
        self.texfile_path = ''  # Define path for the .tex file

        self.name = Label(self.mainframe, text="Welcome to Mathcad to LaTeX converter")  # Create a static text label
        self.name.pack(side="top")  # Make the widget visible and define location

        self.filename = StringVar()  # Create a dynamic string variable
        self.filename.set("Current selected file: none")  # Set the string value
        self.filename_label = Label(self.mainframe, textvariable=self.filename)  # Create a label with the dynamic var
        self.filename_label.pack()
        self.text_updater = Entry(self.mainframe, textvariable=self.filename)  # Create a Entry widget for auto updates

        self.status = StringVar()  # Used for displaying the status of the file operation
        self.status.set("Status: Not parsed")
        self.status_label = Label(self.mainframe, textvariable=self.status)
        self.status_label.pack()
        self.text_updater2 = Entry(self.mainframe, textvariable=self.status)

        self.parse_file = Button(self.mainframe, text="Parse and save!", command=self.parse_file)  # Button for parsing
        self.parse_file.pack(side="right")

        self.parse_file = Button(self.mainframe, text="Open LaTeX file", command=self.open_file)
        self.parse_file.pack(side="right")

        self.select_file = Button(self.mainframe, text="Select file", command=self.select_file)  # Runs a class method
        self.select_file.pack(side="right")

    def select_file(self):  # Method used for selecting a file
        self.path = askopenfilename()  # Display native os file dialog for choosing a file
        self.filename.set("Current selected file: " + os.path.basename(self.path))  # Change the dynamic variable
        self.status.set("Status: Not parsed")  # Set status

    def open_file(self):  # Method used for opening the parsed LaTeX file
        self.texfile_path = os.path.dirname(self.path) + '/ParsedLatexFile/' + os.path.splitext(os.path.basename(self.path))[0] + '.tex'
        if self.status.get() == "Status: File tried parsed! Look under the folder \ParsedLatexFile !":
            os.system("start " + "\"\" \"" + self.texfile_path + "\"")

    def parse_file(self):  # Method for parsing the chosen file
        # Make sure a file is selected and it is a Mathcad file before trying to parse it
        if self.filename.get() != 'Current selected file: none' and os.path.splitext(self.path)[1] == '.xmcd':
            self.status.set("Status: Tring to parse... (most files takes a few seconds)")
            MathcadXMLParser(self.path)  # Call the MathcadXMLParser class with the path
            self.status.set("Status: File tried parsed! Look under the folder \ParsedLatexFile !")
        # Display a error message to the user
        else:
            self.status.set("Status: You need to select a .xmcd (Mathcad) file!")
开发者ID:ArtificialTruth,项目名称:PTC-Mathcad-to-LaTeX-parser,代码行数:60,代码来源:main.py

示例4: FrameKSPObject

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class FrameKSPObject(Frame):
    
    
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        frame = Frame(self)
        frame.pack()
        self.string_var0 = StringVar()
        self.string_var1 = StringVar()
        self.int_var = IntVar()
        self.entry0 = Entry(frame, textvariable=self.string_var0)
        self.entry0.pack(side='left')
        Entry(frame, textvariable=self.string_var1).pack(side='left')
        frame = Frame(self)
        frame.pack()
        Button(frame, width=8, text='Accept', command=self.accept).pack(side='left')
        Button(frame, width=8, text='Cancel', command=self.cancel).pack(side='left')
        Button(frame, width=8, text='Delete', command=self.delete).pack(side='left')
        
        
    def populate(self, kspobject):
        self._kspobject = kspobject
        self.string_var0.set(kspobject.name)
        self.string_var1.set(kspobject.value)
        self.int_var.set(kspobject.id_)
        
        
    def accept(self):
        name = self.string_var0.get()
        value = self.string_var1.get()
        id_ = self.int_var.get()
        self.master.master.update_kspobject(name, value, id_)
        self.master.destroy()
    
    
    def cancel(self):
        self.master.destroy()
    
    
    def delete(self):
        id_ = self.int_var.get()
        self.master.master.delete_kspobject(id_)
        self.master.destroy()
        
        
        
        
        
        
        
        
        
        
        
        
        
开发者ID:dan2082,项目名称:KSPData,代码行数:46,代码来源:frame_kspobject.py

示例5: DiceTab

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class DiceTab(Frame):
    def __init__(self,master=None):
        Frame.__init__(self,master)
        #Sides of Dice
        labelSides=Label(self,text="Sides")
        labelSides.grid(row=0,column=0)
        self.sides=StringVar()
        self.sides.set(20)
        spinboxSides=Spinbox(self,from_=1,to=20,increment=1,width=4)
        spinboxSides.config(textvariable=self.sides, font="sans 24", justify="center")
        spinboxSides.grid(row=0,column=1)
        #Number of Dices
        labelNumber=Label(self,text="Number")
        labelNumber.grid(row=1,column=0)
        self.number=StringVar()
        self.number.set(1)
        spinboxNumber=Spinbox(self,from_=1,to=30,increment=1,width=4)
        spinboxNumber.config(textvariable=self.number, font="sans 24", justify="center")
        spinboxNumber.grid(row=1,column=1)
        #Modifier
        labelModifier=Label(self,text="Modifier")
        labelModifier.grid(row=2,column=0)
        self.modifier=StringVar()
        self.modifier.set(0)
        spinboxModifier=Spinbox(self,from_=-5,to=5,increment=1,width=4)
        spinboxModifier.config(textvariable=self.modifier, font="sans 24", justify="center")
        spinboxModifier.grid(row=2,column=1)
        #Hide Checkbox
        labelHide=Label(self, text="Hide")
        labelHide.grid(row=2, column=2)
        self.hide=IntVar()
        self.hide.set(0)
        checkbuttonHide=Checkbutton(self,variable=self.hide)
        checkbuttonHide.grid(row=2,column=3)
        #Result display
        self.result=StringVar()
        self.result.set("")
        labelResult1=Label(self,text="Result")
        labelResult1.grid(row=1, column=4)
        labelResult2=Label(self,text=self.result.get(),relief=SUNKEN,width=4)
        labelResult2.grid(row=1,column=5)
        #Button to roll
        buttonRoll=Button(self,text="Roll!", command=self.roll)
        buttonRoll.grid(row=2,column=5)
        

    def roll(self):
        self.throws=[]
        numberOfDices=int(self.number.get())
        sidesOfDice=int(self.sides.get())
        modifierOfDice=int(self.modifier.get())
        
        for i in range(numberOfDices):
            self.throws.append(rd.randint(1,sidesOfDice))
        self.result.set(str(sum(self.throws)+modifierOfDice))
        labelResult2=Label(self,text=self.result.get(),relief=SUNKEN, width=4)
        labelResult2.grid(row=1,column=5)
开发者ID:jkesselring,项目名称:DnDApp,代码行数:59,代码来源:dice.py

示例6: __init__

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class Valve:
    def __init__(self, name, setting, action_a, action_b, interval):
        self.name = StringVar()
        self.name.set('Valve')
        self.set_name(name)

        self.setting = setting
        self.interval = interval

        self.action_a = StringVar()
        self.action_a.set('ACTION A')
        self.set_action_a(action_a)

        self.action_b = StringVar()
        self.action_b.set('ACTION B')
        self.set_action_b(action_b)

    def __str__(self):
        string = 'NAME:\t  ' + self.name.get() + '\nACTION A:\t' + self.action_a.get() + '\t\tSETTNG:\t' + self.setting
        string += '\nACTION B:\t' + self.action_b.get() + '\t\tINTERVAL:\t(' + str(self.interval[0]) + ', ' + str(self.interval[1]) + ')\n'
        return string

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name.set(name)

    def get_setting(self):
        return self.setting

    def set_setting(self, setting):
        self.setting = setting

    def get_interval(self):
        return self.interval

    def set_interval(self, interval):
        self.interval = interval

    def get_action_a(self):
        return self.action_a

    def set_action_a(self, action):
        self.action_a.set(action)

    def get_action_b(self):
        return self.action_b

    def set_action_b(self, action):
        self.action_b.set(action)
开发者ID:xistingsherman,项目名称:SPTOR,代码行数:53,代码来源:Valve.py

示例7: Select_Py_Version

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class Select_Py_Version(_Dialog):
    """
    Select_Py_Version is a tkinter pop-up dialog used to select a python
    interpreter for use with Tk_Nosy.
    """

    def body(self, master):
        dialogframe = Frame(master, width=300, height=300)
        dialogframe.pack()


        self.Label_1 = Label(dialogframe, text="Select Python Version")
        self.Label_1.pack()

        if self.dialogOptions:
            rbL = self.dialogOptions.get('rbL', ['No Options','No Options'])
        else:
            rbL = ['No Options', 'No Options']

        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set(rbL[0])
        self.RadioGroup1_StringVar_traceName = \
            self.RadioGroup1_StringVar.trace_variable("w", self.RadioGroup1_StringVar_Callback)

        for rb in rbL:
            self.Radiobutton_1 = Radiobutton(dialogframe, text=rb, value=rb)
            self.Radiobutton_1.pack(anchor=W)
            self.Radiobutton_1.configure( variable=self.RadioGroup1_StringVar )
        self.resizable(0, 0) # Linux may not respect this


    def RadioGroup1_StringVar_Callback(self, varName, index, mode):
        """When radio group selection changes, print message to CLI."""
        print( "RadioGroup1_StringVar_Callback varName, index, mode",
                varName, index, mode )
        print( "    new StringVar value =", self.RadioGroup1_StringVar.get() )


    def validate(self):
        """Validates and packages dialog selections prior to return to calling
           routine.
           set values in "self.result" dictionary for return
        """
        self.result = {} # return a dictionary of results

        self.result["selection"] = self.RadioGroup1_StringVar.get()
        return 1

    def apply(self):
        print( 'apply called')
开发者ID:sonofeft,项目名称:Tk_Nosy,代码行数:52,代码来源:select_py_version_dialog.py

示例8: __init__

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar 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

示例9: GuiGeneratorSelect

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class GuiGeneratorSelect(Frame):
    def __init__(self, parent, generators):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        
        self._generators = generators
        self._generatorName = StringVar()
        self._generatorName.set(generators[0].getName())
        self._generatorName.trace("w", self._switchSettings)
        
        self._generatorLbl = Label(self, text="Generator");
        self._generatorLbl.pack(side=LEFT)
        
        param = (self, self._generatorName) + tuple(i.getName() for i in generators)
        self._generatorOpt = OptionMenu(*param)
        self._generatorOpt.pack(side=LEFT)
        
        
        self._switchSettings()
        
    def _switchSettings(self, *args):
       print("DBG: switch generator settings")
       for i in self._generators:
           if i.getName() == self._generatorName.get(): 
               i.pack()
               self._generatorGui = i
               print("pack " + str(i.getName()))
           else:
               i.pack_forget() 
               print("unpack " + str(i.getName()))
    
    def getCurrGeneratorGui(self):
        return self._generatorGui         
开发者ID:awaken1988,项目名称:pyTools,代码行数:36,代码来源:tas_bytegenerator.py

示例10: PredictionWidget

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
 class PredictionWidget(Frame):
     """Shows a prediction to the user."""
     def __init__(self, master):
         """Make boxes, register callbacks etc."""
         Frame.__init__(self, master)
         self.active_category = StringVar()
         self.bind("<Configure>", self.onResize)
         self.date = None
         self.predictor = Predictor()
         self.category_buttons = self.createCategoryButtons()
         self.text = Label(self, justify=CENTER, font="Arial 14")
     def createCategoryButtons(self):
         """Create the buttons used to choose category. Return them."""
         result = []
         icons = self.readIcons()
         categories = self.predictor.categories()
         for i in categories:
             if i in icons:
                 icon = icons[i]
             else:
                 icon = icons["= default ="]
             category_button = Radiobutton(self, image=icon,
                  variable=self.active_category, value=i, indicatoron=False,
                  width=icon_size, height=icon_size, command=self.update)
             category_button.image_data = icon
             result.append(category_button)
         self.active_category.set(categories[0])
         return result
     def readIcons(self):
         """Read the gui icons from disk. Return them."""
         result = {}
         categories = open(nextToThisFile("icons.txt")).read().split("\n\n")
         for i in categories:
             category_name, file_data = i.split("\n", maxsplit=1)
             image = PhotoImage(data=file_data)
             result[category_name] = image
         return result
     def onResize(self, event):
         """Rearrange the children when the geometry of self changes."""
         if event.widget == self:
             center = (event.width / 2, event.height / 2)
             radius = min(center) - icon_size / 2
             self.text.place(anchor=CENTER, x=center[0], y=center[1])
             for i, j in enumerate(self.category_buttons):
                 turn = 2 * math.pi
                 angle = turn * (1 / 4 - i / len(self.category_buttons))
                 j.place(anchor=CENTER,
                         x=center[0] + math.cos(angle) * radius,
                         y=center[1] - math.sin(angle) * radius)
     def update(self, date=None):
         """Change contents based on circumstances. Set date if given."""
         if date:
             self.date = date
         if self.date:
             predictions = self.predictor.predict(self.date)
             prediction = predictions[self.active_category.get()]
             prediction = textwrap.fill(prediction, width=20)
         else:
             prediction = ""
         self.text.configure(text=prediction)
开发者ID:JoelSjogren,项目名称:horoskop,代码行数:62,代码来源:main.py

示例11: Example

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class Example(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)

        self.dict = {'Asia': ['Japan', 'China', 'India'],
                     'Europe': ['Portugal', 'Switzerland', 'Ukraine']}

        self.var_a = StringVar(self)
        self.var_b = StringVar(self)

        self.var_a.trace('w', self.update_options)

        self.option_menu_a = OptionMenu(self, self.var_a, *self.dict.keys())
        self.option_menu_a.pack(side="top")
        self.option_menu_a["width"] = 10
        self.option_menu_b = OptionMenu(self, self.var_b, '')
        self.option_menu_b["width"] = 10
        self.option_menu_b.pack(side="top")

        self.var_a.set('Asia')

    def update_options(self, *args):
        countries = self.dict[self.var_a.get()]
        self.var_b.set(countries[0])

        menu = self.option_menu_b['menu']
        menu.delete(0, 'end')

        for c in countries:
            menu.add_command(label=c, command=lambda x=c: self.var_b.set(x))
开发者ID:dossan,项目名称:tkinter,代码行数:32,代码来源:sync_two_option_menus.py

示例12: test_CheckbuttonWithVar

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
def test_CheckbuttonWithVar():
    parent = Tk()
    var = StringVar(master=parent)
    var.set(1)
    box = CheckbuttonWithVar(parent, var)
    box.deselect()
    assert var.get() == '0'
    parent.destroy()
开发者ID:nishimaomaoxiong,项目名称:pyDEA,代码行数:10,代码来源:test_gui_classes_of_table_frame.py

示例13: OptionMenu45

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class OptionMenu45(OptionMenu):
    def __init__(self,parent,title,option_list,**config):
        self.result = StringVar()
        self.result.set(title)
        OptionMenu.__init__(self,parent,self.result,*option_list,**config)
  
    def get(self):
        return self.result.get()
开发者ID:Yangsilu,项目名称:database,代码行数:10,代码来源:optionmenu45.py

示例14: FeasDisp

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class FeasDisp(ttk.Frame):
    """Widget for displaying all of the feasible states in the conflict."""

    def __init__(self, master=None, conflict=None, *args):
        """Initialize the widget."""
        ttk.Frame.__init__(self, master, padding=5)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)

        self.conflict = conflict

        self.dispFormat = StringVar(value='pattern')
        self.dispList = StringVar()
        self.feasList = []

        self.fmts = {'Pattern': 'YN-', 'List (YN)': 'YN',
                     'List (ordered and [decimal])': 'ord_dec'}
        cBoxOpts = ('Pattern', 'List (YN)', 'List (ordered and [decimal])')
        self.feasText = ttk.Label(self, text='Feasible States')
        self.feasText.grid(row=0, column=0, columnspan=3)
        self.cBox = ttk.Combobox(self, textvariable=self.dispFormat,
                                 values=cBoxOpts, state='readonly')
        self.cBoxLb = ttk.Label(self, text='Format:')
        self.feasLBx = Listbox(self, listvariable=self.dispList)
        self.scrl = ttk.Scrollbar(self, orient=VERTICAL,
                                  command=self.feasLBx.yview)

        # ###########
        self.cBoxLb.grid(column=0, row=1, sticky=NSEW, pady=3)
        self.cBox.grid(column=1, row=1, columnspan=2, sticky=NSEW, pady=3)
        self.feasLBx.grid(column=0, row=2, columnspan=2, sticky=NSEW)
        self.scrl.grid(column=2, row=2, sticky=NSEW)

        self.cBox.bind('<<ComboboxSelected>>', self.fmtSel)
        self.feasLBx.configure(yscrollcommand=self.scrl.set)

        self.dispFormat.set('Pattern')
        self.fmtSel()

    def fmtSel(self, *args):
        """Action on selection of a new format."""
        self.refreshList()

    def setFeas(self, feasList):
        """Change the list of feasible states to be displayed."""
        self.feasList = feasList
        self.refreshList()

    def refreshList(self):
        """Update the list of feasible states displayed and the format."""
        fmt = self.fmts[self.dispFormat.get()]
        if fmt == "YN-":
            feas = self.conflict.feasibles.dash
        if fmt == "YN":
            feas = self.conflict.feasibles.yn
        if fmt == "ord_dec":
            feas = self.conflict.feasibles.ordDec
        self.dispList.set(tuple(feas))
开发者ID:onp,项目名称:gmcr-py,代码行数:60,代码来源:widgets_f02_03_feasDisp.py

示例15: RankingEditor

# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import get [as 别名]
class RankingEditor(ttk.Frame):
    """Display and edit the state ranking for a single Decision Maker."""

    def __init__(self, master, conflict, dm):
        """Initialize a RankingEditor widget for a decision maker."""
        ttk.Frame.__init__(self, master, borderwidth=2)

        self.master = master
        self.conflict = conflict
        self.dm = dm

        self.columnconfigure(1, weight=1)

        self.dmText = StringVar(value=dm.name + ': ')
        self.dmLabel = ttk.Label(self, textvariable=self.dmText, width=20)
        self.dmLabel.grid(row=0, column=0, sticky=NSEW)

        self.prefRankVar = StringVar(value=str(dm.perceivedRanking))
        self.prefRankEntry = ttk.Entry(self, textvariable=self.prefRankVar)
        self.prefRankEntry.grid(row=0, column=1, sticky=NSEW)

        self.errorDetails = None

        self.prefRankEntry.bind("<FocusOut>", self.onFocusOut)

    def onFocusOut(self, event):
        """Validate the preference ranking when focus leaves the widget."""
        try:
            perceivedRank = literal_eval(self.prefRankVar.get())
        except SyntaxError:
            self.errorDetails = ("DM {}'s preference ranking is "
                                 "invalid.").format(self.dm.name)
            self.master.event_generate("<<errorChange>>")
            return
        except NameError:
            self.errorDetails = ("DM {}'s preference ranking is "
                                 "invalid.").format(self.dm.name)
            self.master.event_generate("<<errorChange>>")
            return
        prefRank = perceivedRank + self.dm.misperceived
        self.errorDetails = gmcrUtil.validatePreferenceRanking(
            prefRank, self.conflict.feasibles)
        if self.errorDetails:
            self.errorDetails += ("  Check DM {}'s preference "
                                  "ranking.").format(self.dm.name)
            self.master.event_generate("<<errorChange>>")
            return
        self.dm.preferenceRanking = prefRank
        self.dm.calculatePreferences()
        self.master.event_generate("<<errorChange>>")

    def enableWidget(self):
        """Enable editting of the ranking."""
        self.prefRankEntry['state'] = 'normal'

    def disableWidget(self):
        """Disable editting of the ranking."""
        self.prefRankEntry['state'] = 'disabled'
开发者ID:onp,项目名称:gmcr-py,代码行数:60,代码来源:widgets_f05_01_PrefRank.py


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