本文整理汇总了Python中tkinter.scrolledtext.ScrolledText.bind方法的典型用法代码示例。如果您正苦于以下问题:Python ScrolledText.bind方法的具体用法?Python ScrolledText.bind怎么用?Python ScrolledText.bind使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.scrolledtext.ScrolledText
的用法示例。
在下文中一共展示了ScrolledText.bind方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class MyGUI:
def __init__(self, reps=3):
self.reps = reps
self.text = ScrolledText()
self.text.pack()
threadChecker(self.text)
self.text.bind('<Button-1>',
lambda event: list(map(self.onEvent, range(6))))
def onEvent(self, i):
myname = 'thread-%s' % i
startThread(action=self.threadaction, args=(i, ),
context=(myname,), onExit=self.threadexit,
onFail=self.threadfail, onProgress=self.threadprogress)
def threadaction(self, id, progress):
for i in range(self.reps):
time.sleep(1)
if progress: progress(i)
if id % 2 == 1: raise Exception
def threadexit(self, myname):
self.text.insert('end', '%s\texit\n' % myname)
self.text.see('end')
def threadfail(self, exc_info, myname):
self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0]))
self.text.see('end')
def threadprogress(self, count, myname):
self.text.insert('end', '%s\tprog\t%s\n' % (myname, count))
self.text.see('end')
self.text.update()
示例2: TextFrame
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class TextFrame(ttk.LabelFrame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._init_ui()
def _init_ui(self):
self.textbox = ScrolledText(self, width=70, height=10)
self.textbox.bind("<1>", lambda event: self.textbox.focus_set())
self.textbox.pack(expand=True, fill='both')
示例3: __init__
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class MyGUI:
def __init__(self, reps=3):
self.reps = reps # uses default Tk root
self.text = ScrolledText() # save widget as state
self.text.pack()
threadChecker(self.text) # start thread check loop
self.text.bind('<Button-1>', # 3.x need list for map, range ok
lambda event: list(map(self.onEvent, range(6))) )
def onEvent(self, i): # code that spawns thread
myname = 'thread-%s' % i
startThread(
action = self.threadaction,
args = (i, ),
context = (myname,),
onExit = self.threadexit,
onFail = self.threadfail,
onProgress = self.threadprogress)
# thread's main action
def threadaction(self, id, progress): # what the thread does
for i in range(self.reps): # access to object state here
time.sleep(1)
if progress: progress(i) # progress callback: queued
if id % 2 == 1: raise Exception # odd numbered: fail
# thread callbacks: dispatched off queue in main thread
def threadexit(self, myname):
self.text.insert('end', '%s\texit\n' % myname)
self.text.see('end')
def threadfail(self, exc_info, myname): # have access to self state
self.text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0]))
self.text.see('end')
def threadprogress(self, count, myname):
self.text.insert('end', '%s\tprog\t%s\n' % (myname, count))
self.text.see('end')
self.text.update() # works here: run in main thread
示例4: create_widgets
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
def create_widgets(self):
url_frame = Frame(self)
url_frame.pack(anchor='w', fill='x')
url_label = Label(url_frame, text='Google Patent URL: ')
url_label.pack(side='left')
url_entry = Entry(url_frame, width=75)
url_entry.pack(side='left', expand=True, fill='x')
url_entry.bind('<Return>', self.analyze_patent)
url_entry.bind('<2>', rClicker)
claim_pane = PanedWindow(self, orient=HORIZONTAL)
claim_pane.pack(anchor='n', fill='both', expand=True)
claim_treeview = Treeview(claim_pane, columns=('Type',), displaycolumns='#all', selectmode='browse')
claim_treeview.column('Type', stretch=True)
claim_treeview.heading('Type', text='Type')
claim_treeview.heading('#0', text='#')
claim_treeview.bind('<<TreeviewSelect>>', self.display_claim)
claim_pane.add(claim_treeview)
claim_text = ScrolledText(claim_pane, font=('Helvetica', 17), wrap='word')
claim_text.bind('<2>', rClicker)
claim_pane.add(claim_text)
self.claim_treeview = claim_treeview
self.claim_text = claim_text
示例5: producer
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
import _thread, queue, time
dataQueue = queue.Queue()
def producer(id):
for i in range(5):
time.sleep(0.1)
print('put')
dataQueue.put('[producer id=%d, count=%d]' % (id, i))
def consumer(root):
try:
print('get')
data = dataQueue.get(block=False)
except queue.Empty:
pass
else:
root.insert('end', 'consumer got => %s\n' % str(data))
root.see('end')
root.after(250, lambda: consumer(root))
def makethreads():
for i in range(4):
_thread.start_new_thread(producer, (i,))
if __name__ == '__main__':
from tkinter.scrolledtext import ScrolledText
root = ScrolledText()
root.pack()
root.bind('<Button-1>', lambda event: makethreads())
consumer(root)
root.mainloop()
示例6: threadaction
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
# thread's main action
def threadaction(id, reps, progress): # what the thread does
for i in range(reps):
time.sleep(1)
if progress: progress(i) # progress callback: queued
if id % 2 == 1: raise Exception # odd numbered: fail
# thread exit/progress callbacks: dispatched off queue in main thread
def threadexit(myname):
text.insert('end', '%s\texit\n' % myname)
text.see('end')
def threadfail(exc_info, myname):
text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0]))
text.see('end')
def threadprogress(count, myname):
text.insert('end', '%s\tprog\t%s\n' % (myname, count))
text.see('end')
text.update() # works here: run in main thread
# make enclosing GUI and start timer loop in main thread
# spawn batch of worker threads on each mouse click: may overlap
text = ScrolledText()
text.pack()
threadChecker(text) # start thread loop in main thread
text.bind('<Button-1>', # 3.x need list for map, range ok
lambda event: list(map(onEvent, range(6))) )
text.mainloop() # pop-up window, enter tk event loop
示例7: Application
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class Application(ttk.Frame):
def __init__(self, master=None):
# ttk.Frame is an old-style class on 2.7
ttk.Frame.__init__(self, master)
self._init_ui()
self.pack()
env = os.environ.copy()
env['RUST_LOG'] = 'info'
self.wrapper = WrapperProcessMonitor(('bin/wrapper',), env=env)
self.wrapper.on_event = self._handle_wrapper_event
module = 'http.server' if py3 else 'SimpleHTTPServer'
self.http = ProcessMonitor((sys.executable, '-u', '-m', module, '8889'),
cwd=os.path.join(os.getcwd(), 'www'))
self.http.on_event = self._handle_http_event
self.repl = ReplConnection()
self.repl.on_event = self._handle_repl_event
self.stopping = 0
self.master.protocol('WM_DELETE_WINDOW', self._handle_close)
self.after(100, self._check_queues)
def _init_ui(self):
frame_top = ttk.Frame(self)
notebook = ttk.Notebook(self)
self.btn_start = ttk.Button(frame_top, text='Start Server', command=self._start)
self.btn_stop = ttk.Button(frame_top, text='Stop Server', command=self._stop)
self.btn_stop.state(['disabled'])
self.btn_start.pack(side='left')
self.btn_stop.pack(side='right')
notebook.add(self._init_status_frame(notebook), text='Status')
notebook.add(self._init_repl_frame(notebook), text='REPL')
self.wrapper_log = ScrolledText(notebook, height=20, width=80)
notebook.add(self.wrapper_log, text='Main Log')
self.http_log = ScrolledText(notebook, height=20, width=80)
notebook.add(self.http_log, text='HTTP Log')
frame_top.pack()
notebook.pack()
def _init_status_frame(self, notebook):
wrapper = ttk.Frame(notebook)
frame = ttk.Frame(wrapper)
ttk.Label(frame, text='Main Server: ').grid(row=0, column=0, sticky='W')
ttk.Label(frame, text='HTTP Server: ').grid(row=1, column=0, sticky='W')
self.status_wrapper = ttk.Label(frame, text='Not running')
self.status_wrapper.grid(row=0, column=1, sticky='W')
self.status_http = ttk.Label(frame, text='Not running')
self.status_http.grid(row=1, column=1, sticky='W')
self.status_extra = ttk.Label(frame, text='')
self.status_extra.grid(row=2, column=0, columnspan=2)
frame.pack()
return wrapper
def _init_repl_frame(self, notebook):
frame = ttk.Frame(notebook)
self.repl_input = ScrolledText(frame, height=15, width=80)
self.repl_input.insert(tk.END,
'-- REPL command input\n'
'-- Press Ctrl-Enter to run command\n'
'client_by_name(\'OP\'):extra().superuser = true')
self.repl_input.bind('<Control-Return>', self._repl_send)
self.repl_input.pack()
self.repl_output = ScrolledText(frame, height=5, width=80)
self.repl_output.pack()
return frame
def _handle_wrapper_event(self, kind, data):
self._log_event(self.wrapper_log, kind, data)
if kind in ('error', 'result'):
if self.stopping > 0:
self.stopping -= 1
stat = 'down'
else:
stat = 'err'
self._update_status(wrapper=stat)
def _handle_http_event(self, kind, data):
self._log_event(self.http_log, kind, data)
if kind in ('error', 'result'):
if self.stopping > 0:
self.stopping -= 1
stat = 'down'
else:
stat = 'err'
self._update_status(http=stat)
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class MarkovDemo:
def __init__(self, master):
self.prompt_size = Label(master, anchor=W, text='Encode Word Size')
self.prompt_size.pack(side=TOP, fill=X)
self.size_entry = Entry(master)
self.size_entry.insert(0, '8')
self.size_entry.pack(fill=X)
self.prompt_plain = Label(master, anchor=W, text='Plaintext Characters')
self.prompt_plain.pack(side=TOP, fill=X)
self.plain_entry = Entry(master)
self.plain_entry.insert(0, '""')
self.plain_entry.pack(fill=X)
self.showframe = Frame(master)
self.showframe.pack(fill=X, anchor=W)
self.showvar = StringVar(master)
self.showvar.set("encode")
self.showfirstradio = Radiobutton(self.showframe,
text="Encode Plaintext",
variable=self.showvar,
value="encode",
command=self.reevaluate)
self.showfirstradio.pack(side=LEFT)
self.showallradio = Radiobutton(self.showframe,
text="Decode Cyphertext",
variable=self.showvar,
value="decode",
command=self.reevaluate)
self.showallradio.pack(side=LEFT)
self.inputbox = ScrolledText(master, width=60, height=10, wrap=WORD)
self.inputbox.pack(fill=BOTH, expand=1)
self.dynamic_var = IntVar()
self.dynamic_box = Checkbutton(master, variable=self.dynamic_var,
text='Dynamic Evaluation',
offvalue=False, onvalue=True,
command=self.reevaluate)
self.dynamic_box.pack()
self.output = Label(master, anchor=W, text="This is your output:")
self.output.pack(fill=X)
self.outbox = ScrolledText(master, width=60, height=10, wrap=WORD)
self.outbox.pack(fill=BOTH, expand=1)
self.inputbox.bind('<Key>', self.reevaluate)
def select_all(event=None):
event.widget.tag_add(SEL, 1.0, 'end-1c')
event.widget.mark_set(INSERT, 1.0)
event.widget.see(INSERT)
return 'break'
self.inputbox.bind('<Control-Key-a>', select_all)
self.outbox.bind('<Control-Key-a>', select_all)
self.inputbox.bind('<Control-Key-/>', lambda event: 'break')
self.outbox.bind('<Control-Key-/>', lambda event: 'break')
self.outbox.config(state=DISABLED)
def reevaluate(self, event=None):
if event is not None:
if event.char == '':
return
if self.dynamic_var.get():
text = self.inputbox.get(1.0, END)[:-1]
if len(text) < 10:
return
text = text.replace('\n \n', '\n\n')
mode = self.showvar.get()
assert mode in ('decode', 'encode'), 'Bad mode!'
if mode == 'encode':
# Encode Plaintext
try:
# Evaluate the plaintext characters
plain = self.plain_entry.get()
if plain:
PC = eval(self.plain_entry.get())
else:
PC = ''
self.plain_entry.delete(0, END)
self.plain_entry.insert(0, '""')
# Evaluate the word size
size = self.size_entry.get()
if size:
XD = int(size)
while grid_size(text, XD, PC) > 1 << 20:
XD -= 1
else:
XD = 0
grid = 0
while grid <= 1 << 20:
grid = grid_size(text, XD, PC)
XD += 1
#.........这里部分代码省略.........
示例9: onEvent
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
def onEvent(i):
myname = 'thread-%s' % i
startThread(action=threadaction, args=(i, 3),
context=(myname, ), onExit=threadexit,
onFail=threadfail, onProgress=threadprogress)
def threadaction(id, reps, progress):
for i in range(reps):
time.sleep(1)
if progress: progress(i)
if id % 2 == 1: raise Exception
def threadexit(myname):
text.insert('end', '%s\texit\n' % myname)
text.see('end')
def threadfail(exc_info, myname):
text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0]))
text.see('end')
def threadprogress(count, myname):
text.insert('end', '%s\tprog\t%s\n' % (myname, count))
text.see('end')
text.update()
text=ScrolledText()
text.pack()
threadChecker(text)
text.bind('<Button-1>', lambda event: list(map(onEvent, range(6))))
text.mainloop()
示例10: reactToClick
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class OptimizerMainWindow:
"""
classdocs
"""
# TODO: change that name
def reactToClick(self, event):
a = AddRestrictionDialog(self)
def __init__(self, optimizer):
# always have a reference to model/controller
self.optimizer = optimizer
# setup main GUI and make stretchable
self.guiRoot = Tk()
self.guiRoot.title("OPTIMIZR")
self.guiRoot.columnconfigure(1, weight=1)
self.guiRoot.rowconfigure(0, weight=1)
# left (settings) and right (sequences) part
self.frameLeft = Frame(self.guiRoot)
self.frameLeft.grid(row=0, column=0, sticky=W + E + N + S)
self.frameLeft.columnconfigure(0, weight=1)
self.frameRight = Frame(self.guiRoot)
self.frameRight.grid(row=0, column=1, sticky=W + E + N + S)
self.frameRight.columnconfigure(0, weight=1)
self.frameRight.rowconfigure(0, weight=1)
self.frameRight.rowconfigure(1, weight=1)
self.frameSpeciesControll = LabelFrame(self.frameLeft, text="Species", pady=10, padx=10)
self.frameSpeciesControll.columnconfigure(1, weight=1)
self.frameOptimizationControll = LabelFrame(self.frameLeft, text="Optimization", pady=10, padx=10)
self.frameRestrictionControll = LabelFrame(self.frameLeft, text="Restriction Enzymes", pady=10, padx=10)
self.frameSpeciesControll.grid(row=0, column=0, sticky=W + E, padx=10, pady=10)
self.frameOptimizationControll.grid(row=1, column=0, sticky=W + E, padx=10, pady=10)
self.frameRestrictionControll.grid(row=2, column=0, sticky=W + E, padx=10, pady=10)
# Species Controll
Label(self.frameSpeciesControll, text="Source:").grid(row=0, column=0)
Label(self.frameSpeciesControll, text="Target:").grid(row=1, column=0)
self.comboSourceSpecies = Combobox(self.frameSpeciesControll, state="readonly")
self.comboSourceSpecies.grid(row=0, column=1, pady=5, sticky="ew")
self.comboTargetSpecies = Combobox(self.frameSpeciesControll, state="readonly")
self.comboTargetSpecies.grid(row=1, column=1, pady=5, sticky="we")
self.buttonSpeciesList = Button(self.frameSpeciesControll, text="Edit Species List")
self.buttonSpeciesList.grid(row=2, column=1, pady=5, sticky="e")
self.comboSourceSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
self.comboTargetSpecies.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
# Optimization Controll
Label(self.frameOptimizationControll, text="Optimization Strategy:").grid(row=0, column=0)
self.comboOptimizationStrategy = Combobox(self.frameOptimizationControll, state="readonly")
self.comboOptimizationStrategy.grid(row=0, column=1)
self.comboOptimizationStrategy["values"] = self.optimizer.possibleOptimizationStrategies
self.comboOptimizationStrategy.bind("<<ComboboxSelected>>", self.actionOptimizerSettingsChanged)
# Restriction Enzymes
self.listRestriction = Listbox(self.frameRestrictionControll)
self.listRestriction.grid(row=0, column=0, columnspan=3, pady=5, sticky=W + E)
self.frameRestrictionControll.columnconfigure(0, weight=1)
self.buttonRestricionAdd = Button(self.frameRestrictionControll, text=" + ")
self.buttonRestricionDel = Button(self.frameRestrictionControll, text=" - ")
self.buttonRestricionAdd.grid(row=1, column=1, padx=5)
self.buttonRestricionDel.grid(row=1, column=2, padx=5)
# Source Sequence Frame
self.frameSourceSequence = LabelFrame(self.frameRight, text="Source Sequence", padx=10, pady=10)
self.frameResultSequence = LabelFrame(self.frameRight, text="Result Sequence", padx=10, pady=10)
self.frameSourceSequence.grid(row=0, column=0, sticky="wens", padx=10, pady=10)
self.frameResultSequence.grid(row=1, column=0, sticky="wens", padx=10, pady=10)
self.buttonSourceLoad = Button(self.frameSourceSequence, text=" Load ")
self.textSourceSeq = ScrolledText(self.frameSourceSequence, height=10)
self.buttonSourceLoad.grid(row=0, column=1, sticky="e", pady=5)
self.textSourceSeq.grid(row=1, column=0, columnspan=2, sticky="wens")
self.frameSourceSequence.columnconfigure(0, weight=1)
self.frameSourceSequence.rowconfigure(1, weight=1)
self.textSourceSeq.frame.columnconfigure(1, weight=1)
self.textSourceSeq.frame.rowconfigure(0, weight=1)
self.buttonOptimize = Button(self.frameResultSequence, text=" OPTIMIZE! ")
self.buttonOptimize.bind("<ButtonRelease>", self.actionOptimize)
self.buttonRemoveRestriction = Button(self.frameResultSequence, text=" RESTRICTION-B-GONE! ")
self.buttonRemoveRestriction.bind("<ButtonRelease>", self.actionRemoveRestricion)
self.buttonSaveResult = Button(self.frameResultSequence, text=" Save ")
self.textResultSequence = ScrolledText(self.frameResultSequence, height=10)
self.buttonOptimize.grid(column=0, row=0, pady=5, sticky="w")
self.buttonRemoveRestriction.grid(column=1, row=0, pady=5, padx=10, sticky="w")
self.textResultSequence.grid(row=1, column=0, columnspan=4, sticky="wens")
self.buttonSaveResult.grid(row=2, column=3, pady=5, sticky="e")
self.frameResultSequence.columnconfigure(2, weight=1)
self.frameResultSequence.rowconfigure(1, weight=1)
self.textResultSequence.frame.columnconfigure(1, weight=1)
self.textResultSequence.frame.rowconfigure(0, weight=1)
#.........这里部分代码省略.........
示例11: MarkovDemo
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class MarkovDemo(Frame):
"MarkovDemo(master=None, **kw) -> MarkovDemo instance"
TEXT = dict(height=2, width=46, wrap=WORD) # Text Options
GRID = dict(padx=5, pady=5) # Grid Options
# Initialize a MarkovDemo instance with a GUI for interaction.
def __init__(self, master=None, **kw):
"Initialize the MarkovDemo instance's widgets and settings."
super().__init__(master, **kw)
self.build_widgets()
self.place_widgets()
self.setup_widgets()
self.grid_rowconfigure(2, weight=1)
self.grid_rowconfigure(3, weight=1)
self.grid_columnconfigure(0, weight=1)
self.key = self.primer = None
def build_widgets(self):
"Build the various widgets that will be used in the program."
# Create processing frame widgets.
self.processing_frame = LabelFrame(self, text='Processing Mode:')
self.mode_var = StringVar(self, 'encode')
self.decode_button = Radiobutton(self.processing_frame,
text='Decode Cipher-Text',
command=self.handle_radiobuttons,
value='decode',
variable=self.mode_var)
self.encode_button = Radiobutton(self.processing_frame,
text='Encode Plain-Text',
command=self.handle_radiobuttons,
value='encode',
variable=self.mode_var)
self.freeze_var = BooleanVar(self, False)
self.freeze_button = Checkbutton(self.processing_frame,
text='Freeze Key & Primer',
command=self.handle_checkbutton,
offvalue=False,
onvalue=True,
variable=self.freeze_var)
# Create encoding frame widgets.
self.encoding_frame = LabelFrame(self, text='Encoding Options:')
self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
self.chain_size_entry = Entry(self.encoding_frame)
self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
self.plain_text_entry = Entry(self.encoding_frame)
# Create input frame widgets.
self.input_frame = LabelFrame(self, text='Input Area:')
self.input_text = ScrolledText(self.input_frame, **self.TEXT)
# Create output frame widgets.
self.output_frame = LabelFrame(self, text='Output Area:')
self.output_text = ScrolledText(self.output_frame, **self.TEXT)
def place_widgets(self):
"Place the widgets where they belong in the MarkovDemo frame."
# Locate processing frame widgets.
self.processing_frame.grid(sticky=EW, **self.GRID)
self.decode_button.grid(row=0, column=0, **self.GRID)
self.encode_button.grid(row=0, column=1, **self.GRID)
self.freeze_button.grid(row=0, column=2, **self.GRID)
# Locate encoding frame widgets.
self.encoding_frame.grid(sticky=EW, **self.GRID)
self.chain_size_label.grid(row=0, column=0, sticky=W, **self.GRID)
self.chain_size_entry.grid(row=0, column=1, sticky=EW, **self.GRID)
self.plain_text_label.grid(row=1, column=0, sticky=W, **self.GRID)
self.plain_text_entry.grid(row=1, column=1, sticky=EW, **self.GRID)
self.encoding_frame.grid_columnconfigure(1, weight=1)
# Locate input frame widgets.
self.input_frame.grid(sticky=NSEW, **self.GRID)
self.input_text.grid(sticky=NSEW, **self.GRID)
self.input_frame.grid_rowconfigure(0, weight=1)
self.input_frame.grid_columnconfigure(0, weight=1)
# Locate output frame widgets.
self.output_frame.grid(sticky=NSEW, **self.GRID)
self.output_text.grid(sticky=NSEW, **self.GRID)
self.output_frame.grid_rowconfigure(0, weight=1)
self.output_frame.grid_columnconfigure(0, weight=1)
def setup_widgets(self):
"Setup each widget's configuration for the events they handle."
self.input_text.bind('<Key>', self.handle_key_events)
self.input_text.bind('<Control-Key-a>', self.handle_control_a)
self.input_text.bind('<Control-Key-/>', lambda event: 'break')
self.output_text['state'] = DISABLED
self.output_text.bind('<Control-Key-a>', self.handle_control_a)
self.output_text.bind('<Control-Key-/>', lambda event: 'break')
########################################################################
# Take care of any special event needing dedicated processing.
def handle_radiobuttons(self):
"Change the interface based on the encoding / decoding setting."
if self.encrypting:
self.freeze_button.grid()
if not self.freeze_var.get():
self.encoding_frame.grid()
else:
#.........这里部分代码省略.........
示例12: ReverseGeolocate
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
def ReverseGeolocate(latitude, longitude):
apiKey = 'AIzaSyCwugFdGLz6QUtcYqD1z0PKKsYJhay3vIg'
apiUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + str(latitude) + ',' + str(longitude) + '&key=' + apiKey
apiCall = requests.get(apiUrl)
status = apiCall.json()['status']
if status == 'OK':
results = apiCall.json()['results']
addressComponents = results[0]['address_components']
return (status, addressComponents)
else:
return (status, 'No Data')
def ProcessCoordinates():
with open('gps_sample_short.csv', newline='') as csvfile:
csvReader = csv.reader(csvfile, delimiter=',')
for row in csvReader:
result = ReverseGeolocate(row[0], row[1])
if (result[0] != 'INVALID_REQUEST'):
resultQueue.put(result)
def StartAPICalls():
thread.start_new_thread(ProcessCoordinates, ())
if __name__ == '__main__':
# main GUI thread, start thread on button click
root = ScrolledText()
root.pack()
root.bind('<Button-1>', lambda event: StartAPICalls())
TkConsumer(root)
root.mainloop()
示例13: SpinDelight
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
class SpinDelight(Frame):
def __init__(self):
Frame.__init__(self)
self.master.geometry("1020x600+150+50")
self.master.title("Spin Delight 1.0 - Copyright (c) Robin Thomas")
self.master.resizable(0,0)
self.grid()
self.brwe = Button(self, text = "Browse", command = self.open_file, width = 10, relief = "groove")
self.rtxt = Label(self, text="Input Text:")
self.txt1 = ScrolledText(self, width = 50, height = 25)
self.txt1.bind("<Control-Key-a>", self.select_all_txt1)
self.txt1.bind("<Control-Key-A>", self.select_all_txt1)
self.spin = Button(self, text = "Spin", command = self.spin_file, width = 10, relief = "groove")
self.stxt = Label(self, text="Spun Text:")
self.txt2 = ScrolledText(self, width = 50, height = 25)
self.txt2.bind("<Control-Key-a>", self.select_all_txt2)
self.txt2.bind("<Control-Key-A>", self.select_all_txt2)
self.brwe.grid(row = 2, column = 2, pady = 15)
self.rtxt.grid(row = 2, column = 0, padx = 25)
self.txt1.grid(row = 3, column = 0, columnspan = 10, padx = 25)
self.spin.grid(row = 3, column = 12)
self.stxt.grid(row = 2, column = 13, padx = 25, pady = 5)
self.txt2.grid(row = 3, column = 13, columnspan = 10, padx = 25)
def select_all_txt1(self,event):
self.txt1.tag_add(SEL, "1.0", END)
self.txt1.mark_set(INSERT, "1.0")
self.txt1.see(INSERT)
return 'break'
def select_all_txt2(self,event):
self.txt2.tag_add(SEL, "1.0", END)
self.txt2.mark_set(INSERT, "1.0")
self.txt2.see(INSERT)
return 'break'
def open_file(self):
fname = askopenfilename(filetypes=(("Text files", "*.txt"), ("All files", "*.*") ))
if fname:
try:
self.txt1.delete(0.0, END)
f = open(fname,'r')
self.txt1.insert(INSERT,f.read())
except:
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
def spin_file(self):
txt = self.txt1.get("1.0", END)
self.txt2.delete(0.0, END)
if len(txt):
try:
words = sub(r'([.,?])+', r' \1 ', sub(r'[^a-zA-Z0-9 .,?]+', ' ', txt)).split()
w1 = words[0]
z = [(words[j - 1], words[j]) for j in range(1, len(words))]
values = self.generate_dict(z, w1)
string = self.generate_sent(values)
if len(string):
self.txt2.insert(INSERT, string)
else:
showerror("Error", "Insufficient data to spin !!")
except:
showerror("Error", "Nothing to spin !!")
def generate_dict(self, x, w1):
values = {'.': [w1]}
for (wa, wb) in x:
if wa in values:
values[wa].append(wb)
else:
values[wa] = [wb]
return values
def generate_sent(self, values):
w1 = '.'
w2 = choice(values[w1])
string = w2
values[w1].remove(w2)
while values:
w1 = w2
if len(values[w1]):
w2 = choice(values[w1])
else:
del values[w1]
w1 = '.'
break
if w2 in ('.', ',', '?'):
string += w2
else:
string += " " + w2
values[w1].remove(w2)
return string
示例14: progress
# 需要导入模块: from tkinter.scrolledtext import ScrolledText [as 别名]
# 或者: from tkinter.scrolledtext.ScrolledText import bind [as 别名]
time.sleep(1) # 模拟长时间工作
if progress:
progress(i) # progress callback: queued
if id % 2 == 1:
raise Exception # odd numbered: fail #奇数则模拟异常,否则正常结束
# thread exit/progress callbacks: dispatched off queue in main thread
def threadexit(myname):
text.insert("end", "%s\texit\n" % myname)
text.see("end")
def threadfail(exc_info, myname):
text.insert("end", "%s\tfail\t%s\n" % (myname, exc_info[0]))
text.see("end")
def threadprogress(count, myname):
text.insert("end", "%s\tprog\t%s\n" % (myname, count))
text.see("end")
text.update() # works here: run in main thread
# make enclosing GUI and start timer loop in main thread
# spawn batch of worker threads on each mouse click: may overlap
text = ScrolledText()
text.pack()
threadChecker(text) # start thread loop in main thread #开始检查到来的生产品
text.bind(
"<Button-1>", lambda event: list(map(onEvent, range(6))) # 3.x need list for map, range ok
) # 按下左键启动6个工作者线程
text.mainloop() # pop-up window, enter tk event loop