本文整理汇总了Python中tkinter.StringVar.set方法的典型用法代码示例。如果您正苦于以下问题:Python StringVar.set方法的具体用法?Python StringVar.set怎么用?Python StringVar.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.StringVar
的用法示例。
在下文中一共展示了StringVar.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Example
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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))
示例2: GuiGeneratorSelect
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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
示例3: DlgDelay
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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
示例4: __init__
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
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])
示例5: Example
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
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)
示例6: initUI
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
def initUI(self, server):
self.parent.title("TrackWise Service Manager")
self.pack(fill=BOTH, expand = True, padx = 300)
# self.centerWindow()
menubar = Menu(self.parent)
self.parent.config(menu = menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label = "Exit", command = self.onExit)
menubar.add_cascade(label = "File", menu = fileMenu)
svcsMenu = Menu(menubar)
svcsMenu.add_command(label = "List Service Status", command = self.onStatus)
svcsMenu.add_command(label = "Stop Services", command = self.onStop)
svcsMenu.add_command(label = "Start Services", command = self.onStart)
menubar.add_cascade(label = "Services", menu = svcsMenu)
# svcs = ['TrackWise Tomcat', 'Web Services Tomcat', 'QMD Tomcat', 'Keystone Intake', 'ID Intake', 'TWC']
svcs = server.getservices()
hostname = server.gethostname().strip()
servertype = server.gettype().strip()
frame0 = Labelframe(self, text = "Server Details", borderwidth = 1)
frame0.grid(column = 0, row = 0, sticky = W)
so = StringVar()
svroverview = Message(frame0, textvariable = so, anchor = W, width = 300)
svroverview.grid(column = 0, row = 0)
sstr = "Server: {}\n".format(hostname)
sstr += "Server Type: {}".format(servertype)
so.set(sstr)
frame1 = Labelframe(self, text = "Service Status", borderwidth = 1)
frame1.grid(column = 0, row = 1, sticky = W)
l = StringVar()
label1 = Message(frame1, textvariable = l , anchor = W)
svcscount = 0
lstr = ""
for i in svcs:
svcscount += 1
lstr += '{} - '.format(i) + ('UP\n' if svcscount % 2 else 'DOWN\n')
l.set(lstr)
label1.pack(side=TOP, padx = 5, pady = 5)
frame4 = Frame(self, relief=RAISED, borderwidth = 1)
frame4.grid(column = 0, row = 2, sticky = W)
closeButton = Button(frame4, text="Close", command = self.quit)
closeButton.grid(column = 0, row = 0)
okButton = Button(frame4, text = "OK")
okButton.grid(column = 1, row = 0)
示例7: PredictionWidget
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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)
示例8: Mjolnir3
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
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)
示例9: __init__
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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
示例10: InfoFrame
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
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)
示例11: Example
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
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)
示例12: undo
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [as 别名]
def undo (self):
if len(self.history_list) > 1:
a = self.history_list.pop(len(self.history_list) - 1)
a = self.history_list[len(self.history_list) -1]
StringVar.set(self, a)
else:
a = self.history_list[0]
StringVar.set(self, a)
示例13: test_CheckbuttonWithVar
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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()
示例14: OptionMenu45
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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()
示例15: FeasDisp
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import set [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))