本文整理汇总了Python中tkinter.StringVar.trace方法的典型用法代码示例。如果您正苦于以下问题:Python StringVar.trace方法的具体用法?Python StringVar.trace怎么用?Python StringVar.trace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.StringVar
的用法示例。
在下文中一共展示了StringVar.trace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DateWidget
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
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="")
示例2: GuiGeneratorSelect
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [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: Example
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [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))
示例4: init_before_run
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
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
示例5: EntryTextHolder
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class EntryTextHolder(Entry):
def __init__(self, master=None):
Entry.__init__(self, master)
self._value = StringVar()
self['textvariable'] = self._value
self._value.trace('w', self._valuechanged)
self.model = TextHolderModel(view=self)
def _valuechanged(self, *args):
self.model.text = self._value.get()
#--- model --> view
def update_text(self):
text = self.model.text
if text != self.get():
self.delete(0, 'end')
self.insert(0, text)
示例6: Tk_Nosy
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class Tk_Nosy(object):
"""This class is the tkinter GUI object"""
# make a collection of python interpreters to choose from
pythonInterpreterCollection = None # will be PyInterpsOnSys object
# extra python interpreters can run nosetests concurrently to main window
# concurrent_versionL contains tuples = (PI, Popup)
concurrent_versionL = [] # additional running python interpreters
def __init__(self, master):
self.dirname = os.path.abspath( os.curdir )
self.initComplete = 0
self.master = master
self.x, self.y, self.w, self.h = -1,-1,-1,-1
# bind master to <Configure> in order to handle any resizing, etc.
# postpone self.master.bind("<Configure>", self.Master_Configure)
self.master.bind('<Enter>', self.bindConfigure)
self.menuBar = Menu(master, relief = "raised", bd=2)
self.menuBar.add("command", label = "Change_Dir", command = self.menu_Directory_Change_Dir)
disp_Choices = Menu(self.menuBar, tearoff=0)
self.display_test_details = StringVar()
self.display_test_details.set('N')
disp_Choices.add_checkbutton(label='Display Test Details', variable=self.display_test_details, onvalue='Y', offvalue='N')
self.display_watched_files = StringVar()
self.display_watched_files.set('N')
disp_Choices.add_checkbutton(label='Show Watched Files', variable=self.display_watched_files, onvalue='Y', offvalue='N')
self.menuBar.add("cascade", label="Display", menu=disp_Choices)
py_choices = Menu(self.menuBar, tearoff=0)
py_choices.add("command", label = "Change Python Version",
command = self.changePythonVersion)
py_choices.add("command", label = "Find New Python Interpreter",
command = self.findNewPythonInterpreter)
py_choices.add("command", label = "Launch Another Python Interpreter",
command = self.launchAnotherPythonInterpreter)
self.menuBar.add("cascade", label="Python", menu=py_choices)
#top_Snippet = Menu(self.menuBar, tearoff=0)
self.menuBar.add("command", label = "Run", command = self.menu_Run)
self.display_test_details.trace("w", self.rerun_tests)
self.display_watched_files.trace("w", self.rerun_tests)
master.config(menu=self.menuBar)
# make a Status Bar
self.statusMessage = StringVar()
self.statusMessage.set(self.dirname)
self.statusbar = Label(self.master, textvariable=self.statusMessage,
bd=1, relief=SUNKEN)
self.statusbar.pack(anchor=SW, fill=X, side=BOTTOM)
self.statusbar_bg = self.statusbar.cget('bg') # save bg for restore
self.arial_12_bold_font = tkinter.font.Font(family="Arial", size=12,
weight=tkinter.font.BOLD)
self.arial_12_font = tkinter.font.Font(family="Arial", size=12)
self.statusbar.config( font=self.arial_12_bold_font )
frame = Frame(master)
frame.pack(anchor=NE, fill=BOTH, side=TOP)
self.Pass_Fail_Button = Button(frame,text="Pass/Fail Will Be Shown Here",
image="", width="15", background="green",
anchor=W, justify=LEFT, padx=2)
self.Pass_Fail_Button.pack(anchor=NE, fill=X, side=TOP)
self.Pass_Fail_Button.bind("<ButtonRelease-1>", self.Pass_Fail_Button_Click)
self.master.title("tk_nosy")
self.oscillator = 1 # animates character on title
self.oscillator_B = 0 # used to return statusbar to statusbar_bg
self.lbframe = Frame( frame )
self.lbframe.pack(anchor=SE, side=LEFT, fill=BOTH, expand=1)
scrollbar = Scrollbar(self.lbframe, orient=VERTICAL)
self.Text_1 = Text(self.lbframe, width="80", height="24",
yscrollcommand=scrollbar.set)
scrollbar.config(command=self.Text_1.yview)
scrollbar.pack(side=RIGHT, fill=Y)
self.Text_1.pack(side=LEFT, fill=BOTH, expand=1)
self.master.resizable(1,1) # Linux may not respect this
self.numNosyCalls = 0
self.need_to_pick_dir = 1
#.........这里部分代码省略.........
示例7: Selector
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class Selector(Frame):
"""The Selector class implements a selector, label and variable(to hold the data)
"""
caption = None
"""The caption of the selector"""
caption_orientation = None
"""The orientation of the selector, can be "LEFT", "RIGHT", "TOP", "BOTTOM"."""
value = None
"""The current value of the selector"""
values = None
"""The selectable values"""
onchange = None
"""The onchange-event is triggered when the value is changed."""
do_not_propagate = False
"""If True, the onchange event isn't triggered on changing the value."""
def __init__(self, _master, _values=None, _caption=None, _caption_orientation=None, _relief=None, _onchange=None):
super(Selector, self).__init__(_master, bd=1, relief=_relief)
self.value = StringVar()
if _values:
self.values = _values
else:
self.values = None
if _caption:
self.caption = _caption
else:
self.caption = None
if _caption_orientation:
self.caption_orientation = _caption_orientation
else:
self.caption_orientation = LEFT
if _onchange:
self.onchange = _onchange
# Add handling when type is changed
else:
self.onchange = None
do_not_propagate = False
self.init_widgets()
def set_but_do_not_propagate(self, _value):
"""Sets the value, but by setting the do_not_propagate-flag, the onchange event will not fire.
:param _value: The new value
"""
self.do_not_propagate = True
self.value.set(_value)
def _do_onchange(self, *args):
"""
Calls onchange if assigned.
:param args: a list of arguments.
"""
if self.do_not_propagate == False and self.onchange:
self.onchange(_current_index=0, _current_value=self.cb.get())
else:
self.do_not_propagate = False
def init_widgets(self):
"""
Initialize visual elements.
"""
self.value = StringVar()
self.cb = ttk.Combobox(self, textvariable=self.value, state='readonly')
self.cb['values'] = self.values
self.cb.current(0)
self.l_caption = ttk.Label(self, text=self.caption)
_cb_o = None
if self.caption_orientation == LEFT:
_cb_o = RIGHT
elif self.caption_orientation == RIGHT:
_cb_o = LEFT
elif self.caption_orientation == TOP:
_cb_o = BOTTOM
elif self.caption_orientation == BOTTOM:
_cb_o = TOP
self.cb.pack(side=_cb_o)
self.l_caption.pack(side=self.caption_orientation)
self.value.trace('w', self._do_onchange)
示例8: ConfigurationWindow
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class ConfigurationWindow(Frame):
"""
Klasa GUI konfiguratora roweru
w metodzie 'createBike' jest tworzony obiekt roweru
z wykorzystaniem dekoratorów
"""
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)
def createInterface(self):
"""
Tworzenie interfejsu - nieistotne dla idei zadania
"""
self.frame_choice = StringVar(self.parent)
self.frame_choice.set(tuple(self.frames.keys())[0])
self.frame_choice.trace("w", self.createBike)
self.frame_options = OptionMenu(self.parent,self.frame_choice,
*self.frames.keys())
Label(self.parent,text="Rama:").pack()
self.frame_options.pack(fill=BOTH, expand=1)
self.fork_choice = StringVar(self.parent)
self.fork_choice.set(tuple(self.forks.keys())[0])
self.fork_choice.trace("w", self.createBike)
self.fork_options = OptionMenu(self.parent,self.fork_choice,
*self.forks.keys())
Label(self.parent,text="Widelec:").pack()
self.fork_options.pack(fill=BOTH, expand=1)
self.wheelset_choice = StringVar(self.parent)
self.wheelset_choice.set(tuple(self.wheelsets.keys())[0])
self.wheelset_choice.trace("w", self.createBike)
self.wheelset_options = OptionMenu(self.parent,self.wheelset_choice,
*self.wheelsets.keys())
Label(self.parent,text="Koła:").pack()
self.wheelset_options.pack(fill=BOTH, expand=1)
self.group_choice = StringVar(self.parent)
self.group_choice.set(tuple(self.groups.keys())[0])
self.group_choice.trace("w", self.createBike)
self.group_options = OptionMenu(self.parent,self.group_choice,
*self.groups.keys())
Label(self.parent,text="Grupa osprzętu:").pack()
self.group_options.pack(fill=BOTH, expand=1)
self.components_choice = StringVar(self.parent)
self.components_choice.set(tuple(self.components.keys())[0])
self.components_choice.trace("w", self.createBike)
self.components_options = OptionMenu(self.parent,self.components_choice,
*self.components.keys())
Label(self.parent,text="Komponenty:").pack()
self.components_options.pack(fill=BOTH, expand=1)
def createBike(self, *args):
"""
Metoda tworząca obiekt roweru na zasadanie dekorowania
obiektu klasy 'Frame'
"""
frame = self.frames[self.frame_choice.get()]
fork = self.forks[self.fork_choice.get()]
fork.decorated = frame
wheelset = self.wheelsets[self.wheelset_choice.get()]
wheelset.decorated = fork
group = self.groups[self.group_choice.get()]
group.decorated = wheelset
components = self.components[self.components_choice.get()]
components.decorated = group
self._bike = components
#.........这里部分代码省略.........
示例9: __init__
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class DropdownList:
def __init__(self, master, filemask='*.mln', default=None, allowNone=False, onselchange=None, directory='.'):
self.allowNone = allowNone
self.directory = directory
self.list_frame = master
self.onchange = onselchange
if type(filemask) != list:
filemask = [filemask]
self.file_mask = filemask
self.updateList()
if havePMW:
self.list = ComboBox(master, selectioncommand=onselchange, scrolledlist_items = self.files)
self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
self.picked_name = self.list
else:
self.picked_name = StringVar()
self.list = OptionMenu(*(master, self.picked_name) + tuple(self.files))
if onselchange is not None:
self.picked_name.trace("w", self.onchange)
if default is not None:
self.select(default)
else:
self.select(self.files[0])
def __getattr__(self, name):
return getattr(self.list, name)
def get(self):
return self.picked_name.get()
def select(self, item):
if item in self.files:
if not havePMW:
self.picked_name.set(item)
else:
self.list.selectitem(item)
def updateList(self):
self.files = []
if self.allowNone:
self.files.append("")
if os.path.exists(self.directory):
for filename in os.listdir(self.directory):
for fm in self.file_mask:
if fnmatch(filename, fm):
self.files.append(filename)
self.files.sort()
if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask))
def makelist(self):
if havePMW:
self.list = ComboBox(self.list_frame,
selectioncommand = self.onSelChange,
scrolledlist_items = self.files,
)
self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS")
self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
self.picked_name = self.list
else:
self.list = OptionMenu(*(self.list_frame, self.picked_name) + tuple(self.files))
self.list.grid(row=0, column=0, sticky="NEW")
self.picked_name.trace("w", self.onSelChange)
self.select(self.files[0])
def setDirectory(self, directory, keep=False):
self.directory = directory
self.updateList()
self.makelist()
# if keep is true, only the files list will be updated but the content of the
# text area will not be altered/removed
if not keep: self.select("")
def onSelChange(self, name, index=0, mode=0):
filename = self.picked_name.get()
if self.onchange != None:
self.onchange(filename)
示例10: __init__
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
#.........这里部分代码省略.........
def setFile(self,*args):
self.dumping_file = os.path.join("CardFiles",self.category.get()+"_monsters.sav")
print ("Change dumping file to ",self.dumping_file)
self.monster_type = self.category.get()
Card.monster_list=readMonsters(self.dumping_file)
#from cardPowers import *
self.refreshWidget()
def refreshWidget(self) :
#print "refresh"
self.card_win.pack_forget()
import unicodedata
#Card window
self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)
#Create the name zone
name_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
name = StringVar()
name.set(self.name)
def modifName(*args) :
try :
assert('"' not in name.get())
name.get().encode('ascii')
except Exception as e:
print ("error on name")
name.set(self.name)
return
old = self.name in Card.blocked_creature
self.name=name.get()
if old or self.name in Card.blocked_creature :
self.refreshWidget()
name.trace("w", modifName)
name_wid=Entry(name_zone, width=30,textvariable=name)
name_wid.pack()
name_zone.add(name_wid)
#Create the cost ad star stringvar
#print int(floor(self.getCost()))
self.cost=StringVar()
self.stars=StringVar()
cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W)
star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E)
self.cost.set(str(int(floor(self.getCost()))))
self.stars.set("*"*self.getStars())
#Add them in name zone
name_zone.add(cost_wid)
name_zone.add(star_wid)
#Create an Image Zone
image_zone=Button(self.card_win, command=self.choosePhoto)
if hasattr(self,"photofile") and self.photofile :
print ("Image: ",self.photofile)
try :
pilImage=Image.open(self.photofile)
img=PhotoImage(pilImage,master=image_zone)
except :
decomp=self.photofile.split('/')
for i in range(1,6) :
try :
fname="/".join(decomp[-i:])
print ("try to open",fname)
pilImage = Image.open(fname)
img=PhotoImage(pilImage,master=image_zone)
self.photofile=fname
示例11: range
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
labels = [label_first_name, label_last_name, label_email]
entries = [entry_first_name, entry_last_name, entry_email]
buttons = [button_first, button_last, button_prev, button_next, button_last, button_quit]
for i in range(3):
labels[i].grid(row = i, column = 0, sticky = 'W')
entries[i].grid(row = i, column = 1, columnspan = 6)
for j in range(6):
buttons[j].grid(row = 3, column = j, sticky = 'E')
# def change1(*arg):
# first_name.set(first_name.get())
# def change2(*arg):
# last_name.set(last_name.get())
# def change3(*arg):
# email.set(email.get())
def callback(email):
global position_track
update_value(position_track)
print (email.get())
# first_name.trace("w", change1)
# last_name.trace("w", change2)
email.trace("w", lambda *args, email = email: callback(email))
window.mainloop()
示例12: Application
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((host, port))
self.grid()
self.columnconfigure(0, minsize=100)
self.columnconfigure(1, minsize=200)
self.columnconfigure(2, minsize=200)
self.columnconfigure(3, minsize=150)
self.columnconfigure(4, minsize=150)
self.columnconfigure(5, minsize=150)
self.columnconfigure(6, minsize=150)
self.create_widgets()
self.settables = self.assemble_settables()
self.gui_logger = logging.getLogger('gui')
self.request_update()
def create_widgets(self):
self.create_monitor()
self.create_check_buttons()
self.create_ranges()
self.create_scales()
self.create_radio_buttons()
self.create_voices()
self.quitButton = Button(self, text='Quit', command=self.quit)
self.quitButton.grid(columnspan=7, sticky=E + W)
def assemble_settables(self):
settables = self.winfo_children()
for w in settables:
settables += w.winfo_children()
return [w for w in settables if w.__class__.__name__ in ['Scale', 'Checkbutton']]
def create_radio_buttons(self):
# Scale related
entries = ['DIATONIC', 'HARMONIC', 'MELODIC', 'PENTATONIC', 'PENTA_MINOR',
'GREEK_CHROMATIC', 'GREEK_ENHARMONIC']
self.scale = StringVar()
self.scale.set('DIATONIC')
self.rb_frame = Frame(self)
for e in entries:
rb = Radiobutton(self.rb_frame, value=e, text=e, anchor=W,
command=self.send_scale, variable=self.scale)
rb.grid(row=len(self.rb_frame.winfo_children()), sticky=W)
self.rb_frame.grid(column=1, row=len(self.grid_slaves(column=1)), rowspan=3)
def create_monitor(self):
self.monitor_frame = LabelFrame(self, text="Monitor and Transport")
this_cycle = Scale(self.monitor_frame, label='cycle_pos', orient=HORIZONTAL,
from_=1, to=16, resolution=1)
this_cycle.disable, this_cycle.enable = (None, None)
this_cycle.ref = 'cycle_pos'
this_cycle.grid(column=0, row=0, sticky=E + W)
self.updateButton = Button(self.monitor_frame,
text='Reload all Settings',
command=self.request_update)
self.updateButton.grid(row=1, sticky=E + W)
self.ForceCaesuraButton = Button(self.monitor_frame,
text='Force Caesura',
command=self.force_caesura)
self.ForceCaesuraButton.grid(row=2, sticky=E + W)
self.saveBehaviourButton = Button(self.monitor_frame,
text='Save current behaviour',
command=self.request_saving_behaviour)
self.saveBehaviourButton.grid(row=3, sticky=E + W)
self.saveBehaviourNameEntry = Entry(self.monitor_frame)
self.saveBehaviourNameEntry.grid(row=4, sticky=E + W)
self.saveBehaviourNameEntry.bind('<KeyRelease>', self.request_saving_behaviour)
self.selected_behaviour = StringVar()
self.selected_behaviour.trace('w', self.new_behaviour_chosen)
self.savedBehavioursMenu = OptionMenu(self.monitor_frame,
self.selected_behaviour, None,)
self.savedBehavioursMenu.grid(row=5, sticky=E + W)
self.monitor_frame.grid(column=0, row=10, sticky=E + W)
def request_update(self):
self.send({'sys': 'update'})
def request_saving_behaviour(self, event=None):
"""callback for save behaviour button and textentry"""
if event and event.widget == self.saveBehaviourNameEntry:
if event.keysym == 'Return':
name = self.saveBehaviourNameEntry.get()
self.saveBehaviourNameEntry.delete(0, len(name))
else:
return
else: # button was pressed
name = self.saveBehaviourNameEntry.get()
if name:
self.send({'sys': ['save_behaviour', name]})
def force_caesura(self):
self.send({'force_caesura': True})
def create_voices(self):
voice_ids = ['1', '2', '3', '4']
SCALES = OrderedDict([
('pan_pos', {'min': -1, 'max': 1, 'start': 0.5, 'res': 0.001}),
#.........这里部分代码省略.........
示例13: Plastey
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class Plastey(Tk):
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
# Set window title
self.wm_title('Plastey Configurator')
# Create GUI driven variables
self._mode = BooleanVar()
self._base = BooleanVar()
self._comm = BooleanVar()
self._pass = StringVar()
self._addressed = StringVar()
self._connected = StringVar()
self._this_host = StringVar()
self._this_port = StringVar()
self._other_host = StringVar()
self._other_port = StringVar()
# Create GUI
self._build_gui()
# Set default values for GUI driven variables
self._mode.set(MODE_SINGLE_PLAYER)
self._base.set(BASE_OPENED_GEOMETRY)
self._comm.set(COMM_SOCKET_SERVER)
self._pass.set('')
self._addressed.set(ADDR_HAVE_ADDRESS if check(COMM_THIS_HOST) else ADDR_NO_ADDRESS)
self._connected.set(CONN_NOT_CONNECTED)
self._this_host.set(COMM_THIS_HOST)
self._this_port.set(COMM_THIS_PORT)
self._other_host.set(COMM_THIS_HOST)
self._other_port.set(COMM_OTHER_PORT)
# Follow changes on password
self._pass.trace('w', self._on_bind_address)
# Create folder structures if they don't exists yet
makedirs(FILE_TEMPORARY_FOLDER, exist_ok=True)
makedirs(FILE_PERMANENT_FOLDER, exist_ok=True)
makedirs(FILE_TEMP_SAVE_FOLDER, exist_ok=True)
makedirs(FILE_AUTO_SAVE_FOLDER, exist_ok=True)
#makedirs(FILE_TEMP_STATE_FOLDER, exist_ok=True)
#makedirs(FILE_TEMP_FEEDS_FOLDER, exist_ok=True)
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def _build_gui(self):
# Create GUI sections
row = 0
col = 0
# Warning text
Label(master = self,
text = WARN_TEXT,
anchor = WEST,
justify = CENTER).grid(row = row,
column = col,
sticky = NORTH_WEST,
rowspan = 16)
# Set column spacing
self.columnconfigure(index = col,
pad = GUI_SECTION_PAD_X)
row = 0
col += 1
# Game mode options
Label(master = self,
text = 'Game Mode:').grid(row = row,
column = col,
sticky = WEST)
row += 1
Radiobutton(master = self,
text = 'Single Player',
value = MODE_SINGLE_PLAYER,
variable = self._mode).grid(row = row,
column = col,
sticky = WEST)
row += 1
Radiobutton(master = self,
text = 'Multi Player',
value = MODE_MULTI_PLAYER,
variable = self._mode).grid(row = row,
column = col,
sticky = WEST)
row += 1
# Base object modes
Label(master = self,
text = 'Base Object:').grid(row = row,
column = col,
sticky = WEST)
row += 1
Radiobutton(master = self,
text = 'Plane mesh',
value = BASE_OPENED_GEOMETRY,
variable = self._base).grid(row = row,
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
#.........这里部分代码省略.........
par.tempdir = tempdir.get()
tempdir.set(par.tempdir)
def update_threshold(*args):
par.threshold = threshold.get()
threshold.set(par.threshold)
def update_threshold_type(*args):
par.threshold_type = threshold_type.get()
threshold_type.set(par.threshold_type)
def update_plotdir(*args):
par.plotdir = plotdir.get()
plotdir.set(par.plotdir)
def update_trigger_interval(*args):
par.trigger_interval = trigger_interval.get()
trigger_interval.set(par.trigger_interval)
# Set some grid parameters
nrows = 25
ncolumns = 3
self.master = master
master.title("EQcorrscan parameter setup")
self.label = Label(master, text="Alpha GUI for default setup")
self.label.grid(column=0, columnspan=ncolumns, row=0)
# Set up parameter input
self.t_names_label = Label(master, text="Template names", anchor='e')
self.t_names_label.grid(column=0, row=1, sticky='e')
template_names = StringVar()
template_names.set(', '.join(par.template_names))
self.t_names_box = Entry(master, bd=2, textvariable=template_names)
self.t_names_box.grid(column=1, row=1)
template_names.trace("w", update_template_names)
self.t_names_lookup = Button(master, text="Lookup",
command=lambda: self.get_template_names(par))
self.t_names_lookup.grid(column=2, row=1)
self.lowcut_label = Label(master, text="Lowcut (Hz)", anchor='e')
self.lowcut_label.grid(column=0, row=2, sticky='e')
lowcut = DoubleVar()
lowcut.set(par.lowcut)
self.lowcut_box = Entry(master, bd=2, textvariable=lowcut)
self.lowcut_box.grid(column=1, row=2)
lowcut.trace("w", update_lowcut)
self.highcut_label = Label(master, text="Highcut (Hz)", anchor='e')
self.highcut_label.grid(column=0, row=3, sticky='e')
highcut = DoubleVar()
highcut.set(par.highcut)
self.highcut_box = Entry(master, bd=2, textvariable=highcut)
self.highcut_box.grid(column=1, row=3)
highcut.trace("w", update_highcut)
self.filt_order_label = Label(master, text="Filter order")
self.filt_order_label.grid(column=0, row=4, sticky='e')
filt_order = DoubleVar()
filt_order.set(par.filt_order)
self.filt_order_box = Entry(master, bd=2, textvariable=filt_order)
self.filt_order_box.grid(column=1, row=4)
filt_order.trace("w", update_filt_order)
self.samp_rate_label = Label(master, text="Sample rate (Hz)")
self.samp_rate_label.grid(column=0, row=5, sticky='e')
samp_rate = DoubleVar()
samp_rate.set(par.samp_rate)
示例15: FilePick
# 需要导入模块: from tkinter import StringVar [as 别名]
# 或者: from tkinter.StringVar import trace [as 别名]
class FilePick(Frame):
def __init__(self, master, file_mask, default_file, user_onChange = None, font = None, dirs = (".", ), allowNone = False):
""" file_mask: file mask or list of file masks """
self.master = master
self.user_onChange = user_onChange
Frame.__init__(self, master)
self.columnconfigure(0, weight=1)
self.unmodified = True
self.file_extension = ""
if "." in file_mask:
self.file_extension = file_mask[file_mask.rfind('.'):]
if type(file_mask) != list:
file_mask = [file_mask]
self.file_masks = file_mask
self.allowNone = allowNone
self.dirs = dirs
# create list of files
self.updateList()
# pick default if applicable
self.set(default_file)
def onSelChange(self, name, index=0, mode=0):
filename = self.picked_name.get()
if self.user_onChange != None:
self.user_onChange(filename)
def updateList(self):
prev_sel = self.get()
# get list of files (paths)
self.files = []
if self.allowNone:
self.files.append("")
for fm in self.file_masks:
for dir in self.dirs:
try:
for filename in os.listdir(dir):
if fnmatch(filename, fm):
if dir != ".":
path = os.path.join(dir, filename)
else:
path = filename
self.files.append(path)
except:
pass
self.files.sort()
if len(self.files) == 0: self.files.append("(no %s files found)" % self.file_masks)
# create list object
self._makelist()
# reselect
self.set(prev_sel)
def getList(self):
""" returns the current list of files """
return self.files
def _makelist(self):
if havePMW:
self.list = ComboBox(self,
selectioncommand = self.onSelChange,
scrolledlist_items = self.files,
)
self.list.grid(row=0, column=0, padx=0, sticky="NEWS")
self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
self.picked_name = self.list
else:
self.picked_name = StringVar()
self.list = OptionMenu(*(self, self.picked_name) + tuple(self.files))
self.list.grid(row=0, column=0, sticky="NEW")
self.picked_name.trace("w", self.onSelChange)
def set(self, filename):
default_file = filename
if default_file in self.files:
if not havePMW:
self.picked_name.set(default_file) # default value
else:
self.list.selectitem(self.files.index(default_file))
self.onSelChange(default_file)
pass
def get(self):
if not hasattr(self, 'picked_name'):
return None
return self.picked_name.get()