• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python tkinter.StringVar类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: Mjolnir3

class Mjolnir3(KRCCModule):
  def __init__(self, root):
    super().__init__()
    self.root = root
    self.exception = None

    self.list_string = StringVar()
    self.listbox = Listbox(root, listvariable=self.list_string,
                           font='TkFixedFont', width=300)

    self.load()

  def establish_connection_and_run(self):
    error = None
    dots = 0
    connection = None
    while not self.terminate:
      try:
        if connection is None:
          connection = krpc.connect(name=self.name)
        self.run_with_connection(connection)
        error = None
        dots = 0
      except Exception as e:
        if error != e.args[0]:
          error = e.args[0]
          print('\n')
          print(traceback.format_exc())
          sys.stdout.write('Retrying...\n')
        if dots > 80:
          dots = 0
          sys.stdout.write('\n')
        sys.stdout.write('.')
        dots += 1
        sys.stdout.flush()
        time.sleep(1)
    if connection is not None:
      connection.close()

  def run_with_connection(self, connection):
    logging.debug('KRPC connection established')
    strategy = PreLaunch(connection)
    while not self.terminate:
      strategy = strategy.update()
      self.list_string.set(tuple(strategy.display()))

  def run(self):
    try:
      self.establish_connection_and_run()
      self.listbox.destroy()
    except RuntimeError:
      # Should only happen when KeyboardInterrupt is thrown in the MainThread.
      pass

  @property
  def name(self):
    return 'Mjolnir 3'

  def load(self):
    self.listbox.pack(side=LEFT, fill=BOTH)
开发者ID:jsartisohn,项目名称:krpc_scripts,代码行数:60,代码来源:mjolnir3.py


示例2: Example

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ["Scarlett Johansson", "Rachel Weiss", "Natalie Portman", "Jessica Alba", "Angelina jolie", "Emma Stone", "Sandra Bullock", "Julia Roberts",
        "Jennifer Lawrence", "Mila Kunis", "Jennifer Aniston", "Charlize Theron", "Cameron Diaz", "Nicole Kidman", "Meryl Streep", "Reese Witherspoon"]

        lb = Listbox(self, selectmode="multiple")
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)
        self.var.set(value)
开发者ID:Exodus111,项目名称:Projects,代码行数:30,代码来源:listbox.py


示例3: Example

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Listbox")
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=210)

    def onSelect(self, val):

        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)

        self.var.set(value)
开发者ID:KimBoWoon,项目名称:Python_Practice,代码行数:32,代码来源:TKBook.py


示例4: __init__

    def __init__(self, resizable=(True, True), geometry=(620, 220)):
        assert (isinstance(resizable, (tuple, list)))
        assert (isinstance(geometry, (tuple, list)))

        self.root = Tk()

        self.config = configparser.ConfigParser()
        self.config_file_name = "config.ini"
        self.config.read(self.config_file_name)

        self.default_case = StringVar(value=self.config["DEFAULT"].get("case", "CASE"))
        self.default_team = StringVar(value=self.config["DEFAULT"].get("team", "TEAM"))
        self.default_series = StringVar()
        self.default_last_index = StringVar()

        self.root.title("The Stampede")
        self.root.resizable(width=resizable[0], height=resizable[1])
        self.root.geometry('{}x{}'.format(geometry[0], geometry[1]))
        self.root.minsize(geometry[0], geometry[1])
        self.root.maxsize(geometry[0]+200, geometry[1])
        self.file_name = StringVar()
        self.file_name.trace("w", self.file_name_changed)
        self.stamp_button = None
        self.add_widgets()
        self.add_menus()
        self.center(self.root)
开发者ID:qcaron,项目名称:stampede,代码行数:26,代码来源:main.py


示例5: DlgDelay

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,代码行数:26,代码来源:dialogs.py


示例6: __init__

    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()
开发者ID:onp,项目名称:gmcr-py,代码行数:35,代码来源:widgets_f02_03_feasDisp.py


示例7: DateWidget

 class DateWidget(Frame):
     """Gets a date from the user."""
     def __init__(self, master):
         """Make boxes, register callbacks etc."""
         Frame.__init__(self, master)
         self.label = Label(self, text="När är du född?")
         self.label.pack()
         self.entry_text = StringVar()
         self.entry_text.trace("w", lambda *args: self.onEntryChanged())
         self.entry = Entry(self, width=date_entry_width,
              textvariable=self.entry_text)
         self.entry.insert(0, "ÅÅÅÅ-MM-DD")
         self.entry.pack(pady=small_pad)
         self.button = Button(self, text="Uppdatera",
              command=lambda: self.onDateChanged())
         self.button.pack()
         self.entry.focus_set()
         self.entry.select_range(0, END)
         self.entry.bind("<Return>", lambda x: self.onDateChanged())
     def setListener(self, pred_view):
         """Select whom to notify when a new date is entered."""
         self.pred_view = pred_view
     def onDateChanged(self):
         """Notifies the PredictionWidget that the date has been changed."""
         try:
             date = datetime.datetime.strptime(self.entry.get(),
                  "%Y-%m-%d").date()
             self.pred_view.update(date)
         except ValueError:
             self.entry.configure(foreground="red")
     def onEntryChanged(self):
         """Reset the text color."""
         self.entry.configure(foreground="")
开发者ID:JoelSjogren,项目名称:horoskop,代码行数:33,代码来源:main.py


示例8: __init__

 def __init__(self, parent, table, *args, **kw):
     super().__init__(parent, *args, **kw)
     self.table = table
     self.goto_spin = None
     self.text_var_nb_pages = StringVar()
     self.current_page_str = StringVar()
     self.create_widgets()
开发者ID:nishimaomaoxiong,项目名称:pyDEA,代码行数:7,代码来源:navigation_frame_gui.py


示例9: __init__

class MyFirstGUI:
    LABEL_TEXT = [
        "This is our first GUI!",
        "Actually, this is our second GUI.",
        "We made it more interesting...",
        "...by making this label interactive.",
        "Go on, click on it again.",
    ]
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label_index = 0
        self.label_text = StringVar()
        self.label_text.set(self.LABEL_TEXT[self.label_index])
        self.label = Label(master, textvariable=self.label_text)
        self.label.bind("<Button-1>", self.cycle_label_text)
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

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

    def greet(self):
        print("Greetings!")

    def cycle_label_text(self, event):
        self.label_index += 1
        self.label_index %= len(self.LABEL_TEXT) # wrap around
        self.label_text.set(self.LABEL_TEXT[self.label_index])
开发者ID:gshkr123,项目名称:Python_Task,代码行数:32,代码来源:GUI-Lables.py


示例10: employee

 def employee(self):
     """Function for creation of the GUI to select an employee"""
     self.background.destroy()
     employees=[]
     airports=[]
     employfile="employees.csv"
     airfile="airport.csv"
     curfile="countrycurrency.csv"
     ratefile="currencyrates.csv"
     employee_info=self.look.LookupEmployee(employfile)
     self.look.LookupAirport(airfile)
     self.look.LookupCounrtyCurrency(curfile)
     self.look.LookupCurrencyRate(ratefile)
     for key in employee_info:
         employees.append(key)
     employees.sort()
     #New GUI
     background=Tk()
     background.wm_title("Select an Employee")
     background.geometry("%dx%d+%d+%d" % (400, 150, 150, 200))
     background.configure(background='light sky blue')
     Label(background, text="Choose an employee:", bg="white").grid(padx=10,pady=30,column=0, row=5)
     self.box1name=StringVar()
     self.answer=StringVar()
     box1 = ttk.Combobox(background, values=employees, textvariable=self.box1name, state='readonly')#Allows user to select an employee
     box1.set("Choose an employee")
     box1.grid(padx=30,column=0,row=6)
     answer=Label(background, textvariable=self.answer, bg="white").grid(column=0,row=8)
     button = Button(background, text="Select", command=self.select, bg="white")#Calls select
     button.grid(padx=10,column=1,row=6)
     background.mainloop()
开发者ID:esmullen21,项目名称:OO-ModuleProject,代码行数:31,代码来源:projectMain.py


示例11: __init__

    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")
开发者ID:ArtificialTruth,项目名称:PTC-Mathcad-to-LaTeX-parser,代码行数:34,代码来源:main.py


示例12: body

 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
开发者ID:Lysovenko,项目名称:OTRS_US,代码行数:26,代码来源:dialogs.py


示例13: __init__

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,代码行数:30,代码来源:krcc_module.py


示例14: InfoFrame

class InfoFrame(Frame):
    def __init__(self,master=None, thread=None):
        Frame.__init__(self, master)
        self.controlThread=thread
        
        self.stringVar=StringVar()
        
        self.grid()
        self.createWidgets()
        
    def createWidgets(self):
        self.inputText=Label(self)
        if self.inputText != None:
            self.inputText['textvariable']=self.stringVar
            self.inputText["width"] = 50
            self.inputText.grid(row=0, column=0, columnspan=6)
        else:
            pass
        
        
        self.cancelBtn = Button(self, command=self.clickCancelBtn)   # need to implement
        if self.cancelBtn !=None:
            self.cancelBtn["text"] = "Cancel"
            self.cancelBtn.grid(row=0, column=6)
        else:
            pass
        
    def clickCancelBtn(self):
        print("close the InfoDialog")
        self.controlThread.setStop()
            
    def updateInfo(self, str):
        self.stringVar.set(str)
开发者ID:fscnick,项目名称:RapidgatorDownloader,代码行数:33,代码来源:DialogThread.py


示例15: PredictionWidget

 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,代码行数:60,代码来源:main.py


示例16: __init__

    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()
开发者ID:OptimalBPM,项目名称:qal,代码行数:30,代码来源:frame_mapping.py


示例17: __init__

    def __init__(self, parent, frames, forks, wheelsets, groups, components):
        """
        inicjalizacja obiektu okna - nieistotne dla idei zdania
        """
        super(ConfigurationWindow, self).__init__(parent)
        self._bike = None
        self.parent = parent
        self.frames = frames
        self.forks = forks
        self.wheelsets = wheelsets
        self.groups = groups
        self.components = components
        self.parent.title("Bicycle configurator")
        self._bike_price = StringVar(self.parent)
        self._bike_weight = StringVar(self.parent)
        self._bike_travel = StringVar(self.parent)
        self.price_label = Label(self.parent, textvariable=self._bike_price)
        self.weight_label = Label(self.parent, textvariable=self._bike_weight)
        self.travel_label = Label(self.parent, textvariable=self._bike_travel)

        self.createInterface()
        self.createBike()

        self.price_label.pack()
        self.weight_label.pack()
        self.travel_label.pack()
        
        self.pack(fill=BOTH, expand=1)
开发者ID:kpiszczek,项目名称:wzorceuj,代码行数:28,代码来源:cw5b.py


示例18: GuiGeneratorSelect

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,代码行数:34,代码来源:tas_bytegenerator.py


示例19: OptionMenu45

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,代码行数:8,代码来源:optionmenu45.py


示例20: init_before_run

 def init_before_run(self, nb_models, coefficients):
     ''' See base class.
     '''
     current_dmu = StringVar()
     current_dmu.trace('w', self.frame.on_dmu_change)
     self.current_dmu = current_dmu
     self.increment = 100 / (len(coefficients) * nb_models)
     self.frame.progress_bar['value'] = 0
开发者ID:nishimaomaoxiong,项目名称:pyDEA,代码行数:8,代码来源:run_routine.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tkinter.Tcl类代码示例发布时间:2022-05-27
下一篇:
Python tkinter.Scale类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap