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


Python tkinter.StringVar类代码示例

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


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


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