本文整理汇总了Python中Tkinter.Tk.update_idletasks方法的典型用法代码示例。如果您正苦于以下问题:Python Tk.update_idletasks方法的具体用法?Python Tk.update_idletasks怎么用?Python Tk.update_idletasks使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Tkinter.Tk
的用法示例。
在下文中一共展示了Tk.update_idletasks方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error_and_exit
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
def error_and_exit(title, main_text):
"""
Show a pop-up window and sys.exit() out of Python.
:param title: the short error description
:param main_text: the long error description
"""
# NOTE: We don't want to load all of these imports normally.
# Otherwise we will have these unused GUI modules loaded in the main process.
from Tkinter import Tk, Canvas, DISABLED, INSERT, Label, Text, WORD
root = Tk()
root.wm_title("Tribler: Critical Error!")
root.wm_minsize(500, 300)
root.wm_maxsize(500, 300)
root.configure(background='#535252')
# Place the window at the center
root.update_idletasks()
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
size = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
x = w / 2 - 250
y = h / 2 - 150
root.geometry("%dx%d+%d+%d" % (size + (x, y)))
Canvas(root, width=500, height=50, bd=0, highlightthickness=0, relief='ridge', background='#535252').pack()
pane = Canvas(root, width=400, height=200, bd=0, highlightthickness=0, relief='ridge', background='#333333')
Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack()
Label(pane, text=title, width=40, background='#333333', foreground='#fcffff', font=("Helvetica", 11)).pack()
Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack()
main_text_label = Text(pane, width=45, height=6, bd=0, highlightthickness=0, relief='ridge', background='#333333',
foreground='#b5b5b5', font=("Helvetica", 11), wrap=WORD)
main_text_label.tag_configure("center", justify='center')
main_text_label.insert(INSERT, main_text)
main_text_label.tag_add("center", "1.0", "end")
main_text_label.config(state=DISABLED)
main_text_label.pack()
pane.pack()
root.mainloop()
# Exit the program
sys.exit(1)
示例2: _init_ui
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
def _init_ui(self):
root = Tk()
root.title("pylens")
root.bind("<FocusOut>", self.close)
root.bind("<Escape>", self.close)
# center the window
root.withdraw()
root.update_idletasks() # Update "requested size" from geometry manager
x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
root.geometry("+%d+%d" % (x, y))
root.deiconify()
text = Text(root)
text.config(width=60, height=1)
text.pack(side=LEFT, fill=Y)
text.bind("<Return>", self.handle_query)
text.focus_force()
return root, text
示例3: Tk
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
from Tkinter import Tk
import urllib2
import re
import json
# set to 1 for debugging
debug = 0
r = Tk()
r.withdraw()
try:
url = r.selection_get(selection = "CLIPBOARD")
r.update_idletasks()
r.destroy()
except BaseException as e:
url = "http://video.toggle.sg/en/series/fighting-spiders-s1/ep1/275423"
# sample (m3u8 and mp4) links
#url = "http://video.toggle.sg/en/series/sabo/ep4/326841"
# sample wvm link
#url = "http://video.toggle.sg/en/series/marvel-s-agents-of-s-h-i-e-l-d-yr-2/ep6/327671"
print "\n[i] Given Toggle URL = %s" % (url)
urlsplit = url.split('/')
mediaID = urlsplit[-1]
if (debug):
print "[*] Obtained mediaID = %s" % (mediaID)
print "[i] Performing HTTP GET request on Toggle URL ..."
urlresp = urllib2.urlopen(url).read()
示例4: Visualiser
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
#.........这里部分代码省略.........
self.tk_frameStep.config(to=maxFrame)
def jumpTo(self, frame):
'''
Jump to a given frame. If frame is a function, jump to the
return value of frame().
'''
oldFrame = self.vis_frame
if hasattr(frame, '__call__'):
self.vis_frame = frame()
else:
self.vis_frame = frame
maxFrame = self.getMaxFrameNumber()
if self.vis_frame < 0:
self.vis_frame = 0
elif self.vis_frame > maxFrame:
self.vis_frame = maxFrame
self.vis_paused = True
self.tk_pause.config(text='Resume')
self.tk_frame.set(self.vis_frame)
self.redraw(oldFrame != self.vis_frame)
def redraw(self, update=False):
self.resetSliders()
for feature in [ f for f in self.vis_features if not f.dynamic ]:
feature.draw(self.vtk_renderer)
if update:
for feature in [ f for f in self.vis_features if f.dynamic]:
f.redraw(self.vtk_renderer)
self.tk_renderWidget.GetRenderWindow().Render()
self.tk_root.update_idletasks()
### Gui events ###
def destroyed(self, event):
if event.widget == self.tk_root:
self.shutdown()
def shutdown(self):
self.tk_root.withdraw()
self.tk_root.destroy()
def animate(self):
if not self.vis_paused:
self.jumpTo(self.vis_frame + self.vis_frameStep)
if self.vis_recording and self.vis_recordPattern is not None:
self.save_image()
self.tk_root.after(100, self.animate)
def save_image(self):
extmap = {'.jpg' : vtkJPEGWriter,
'.jpeg' : vtkJPEGWriter,
'.png' : vtkPNGWriter,
'.pnm' : vtkPNMWriter}
_, ext = splitext(self.vis_recordPattern)
try: writer = extmap[ext.lower()]()
except KeyError:
print 'ERROR: Can\'t handle %s extension. Recording disabled.' % ext
self.vis_recordPattern = None
return
win = self.vtk_renderer.GetRenderWindow()
w2i = vtkWindowToImageFilter()
示例5: AmberMdout
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
for f in arg:
try:
mdout += AmberMdout(f)
except NameError:
mdout = AmberMdout(f)
app = MdoutAnalyzerApp(root, mdout)
app.pack(fill=BOTH)
# Update idle tasks here to make sure the whole app is filled in before making
# our window non-resizable. In some instances, this can chop off the second
# frame
app.update_idletasks()
# Now make our window non-resizable
root.resizable(False, False)
root.update_idletasks()
# Load up the graph options window and move it to the right of the root window
rootgeo = [int(i) for i in geore.match(root.geometry()).groups()]
graphprops = GraphControlWindow(root, app.graph_props)
root.update_idletasks()
ggeo = [int(i) for i in geore.match(graphprops.geometry()).groups()]
graphprops.geometry(geoformat % (ggeo[0], ggeo[1], rootgeo[2] + rootgeo[0] + 5,
rootgeo[3])
)
# For some reason it seems like mainloop is not exited properly if we simply
# call root.destroy(). Therefore, we'll replace WM_DELTE_WINDOW with root.quit()
# to bust out of the mainloop.
root.protocol('WM_DELETE_WINDOW', root.quit)
# Enter our mainloop
示例6: TkApplicationWindow
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
#.........这里部分代码省略.........
w = event.widget
st = w.config()["text"][-1]
dialog = TkAddSynthDialog(self.root, self.app, st, False)
self.root.wait_window(dialog)
def _show_add_efx_dialog(self, event):
w = event.widget
st = w.config()["text"][-1]
dialog = TkAddSynthDialog(self.root, self.app, st, is_efx=True, is_controller=False)
self.root.wait_window(dialog)
def _show_add_controller_dialog(self, event):
w = event.widget
st = w.config()["text"][-1]
dialog = TkAddSynthDialog(self.root, self.app, st, is_efx=False, is_controller=True)
self.root.wait_window(dialog)
def _add_synth_group(self):
sh = self.app.ls_parser.synthhelper
sh.new_group()
def add_synth_group(self, name=None):
gw = GroupWindow(self.app, self.root, name)
# gw.transient(self.root) # If executed keeps main app window behind all other windows.
self.group_windows.append(gw)
self.status("Added new Synth Group Window")
return gw
def display_synth_editor(self, sid):
try:
swin = self[sid]
grpid = swin.group_index
grp = self.group_windows[grpid]
#grp.deiconify()
grp.show_synth_editor(sid)
except (KeyError, IndexError):
msg = "Can not find editor for %s" % sid
self.warning(msg)
def update_progressbar(self, count, value):
self._progressbar.config(mode="determinate", maximum=count)
self._progressbar.step()
self.root.update_idletasks()
def busy(self, flag, message=""):
if message:
self.status(message)
self._progressbar.config(mode="indeterminate")
if flag:
self._progressbar.grid(row=0, column=PROGRESSBAR_COLUMN, sticky='w', padx=8)
self._progressbar.start()
else:
self._progressbar.stop()
# self._progressbar.grid_remove()
self.root.update_idletasks()
def save_scene(self, *_):
options = {'defaultextension' : '.llia',
'filetypes' : [('Llia Scenes', '*.llia'),
('all files', '*')],
'initialfile' : self._scene_filename,
'parent' : self.root,
'title' : "Save Llia Scene"}
filename = tkFileDialog.asksaveasfilename(**options)
if filename:
try:
self.app.ls_parser.save_scene(filename)
self._scene_filename = filename
self.status("Scene saved as '%s'" % filename)
except Exception as ex:
self.warning(ex.message)
else:
self.status("Scene save canceld")
def load_scene(self, *_):
options = {'defaultextension' : '.llia',
'filetypes' : [('Llia Scenes', '*.llia'),
('all files', '*')],
'initialfile' : self._scene_filename,
'parent' : self.root,
'title' : "Load Llia Scene"}
filename = tkFileDialog.askopenfilename(**options)
if filename:
try:
self.app.ls_parser.load_scene(filename)
self.status("Scene '%s' loaded" % filename)
self._scene_filename = filename
except Exception as ex:
self.warning(ex.message)
else:
self.status("Load scene canceld")
def tabula_rasa(self):
for grp in self.group_windows:
grp.tabula_rasa()
self.group_windows = []
def _interactive_tabula_rasa(self, *_):
# ISSUE: Check config and ask user confirmation before existing
self.app.ls_parser.tabula_rasa()
示例7: __init__
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
class VisualizerUI:
def __init__(self, width, height, pixelSize, top=False):
self._maxWindowWidth = 1024
self._master = Tk()
self._q = Queue.Queue()
self._hasFrame = False
self.x = width
self.y = height
self._count = self.x * self.y
self._values = []
self._leds = []
self._pixelSize = pixelSize
self._pixelPad = int(pixelSize / 2)
self._pixelSpace = 0
self.initUI()
self.configure(self.x, self.y)
self.checkQ()
self._master.attributes("-topmost", top)
def checkQ(self):
if not self._q.empty():
data = self._q.get_nowait()
self.updateUI(data)
wait = 0
if "darwin" in platform.system().lower():
wait = 1
self._master.after(wait, self.checkQ)
self._master.update_idletasks()
def mainloop(self):
self._master.mainloop()
def updateUI(self, data):
size = len(data) / 3
if size != self._count:
log.warning("Bytecount mismatch")
return
for i in range(size):
r = data[i * 3 + 0]
g = data[i * 3 + 1]
b = data[i * 3 + 2]
self._values[i] = self.toHexColor(r, g, b)
try:
for i in range(self._count):
self._canvas.itemconfig(self._leds[i], fill=self._values[i])
except TclError:
# Looks like the UI closed!
pass
def toHexColor(self, r, g, b):
return "#{0:02x}{1:02x}{2:02x}".format(r, g, b)
def update(self, data):
self._q.put(data)
def hasFrame(self):
return not self._q.empty()
def configure(self, x, y):
self._type = type
self.x = x
self.y = y
self._count = x * y
self._values = []
# init colors to all black (off)
for i in range(self._count):
self._values.append("#101010")
c = self._canvas
c.delete(ALL)
self._leds = []
for i in range(self._count):
index = c.create_rectangle(
0, 0, self._pixelSize, self._pixelSize, fill=self._values[i])
self._leds.append(index)
self.layoutPixels()
def layoutPixels(self):
if len(self._leds) == 0:
return
x_off = 0
row = 0
count = 0
w = 0
#.........这里部分代码省略.........
示例8: download
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
tkMessageBox.showinfo('Warning', u'网址读取错误,请尝试使用浏览器读取网址判断是否可以打开')
return
if not title:
tkMessageBox.showinfo('Warning', u'检测到非微信文章页面')
return
thread.start_new_thread(download, (url, title, picUrl))
tkMessageBox.showinfo('Info', u'已经成功加入队列')
def download(url, title, picUrl):
for sk in (r'\/:*?"<>|'): title = title.replace(sk, '')
title = title.replace(' ', ' ')
if not os.path.exists(title.encode('cp936')): os.mkdir(title.encode('cp936'))
download_pic_from_url(picUrl, os.path.join(title, u'标题图'))
for i, picUrl in enumerate(get_pic_url_from_url(url), 1):
download_pic_from_url(picUrl, os.path.join(title, str(i)))
TASK_STORAGE.append(title)
mainWindow = Tk()
button = Button(mainWindow, cnf = {'command': button_clicked, 'text': 'Download', 'justify': 'right', })
inputEntry = Entry(mainWindow, width=70)
inputEntry.pack()
button.pack()
mainWindow.title(u'微信图片下载器')
while 1:
mainWindow.update_idletasks()
mainWindow.update()
try:
tkMessageBox.showinfo('Info', u'读取成功,请打开"%s"文件夹查看'%TASK_STORAGE.pop())
except:
pass
示例9: TKEA_win
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
#.........这里部分代码省略.........
for el in vl:
if not hasattr(self.ea,el['name']):
raise TypeError('you try to set up an entry for a name which is no attribute of the chosen EA')
fr=Frame(self.f_actn); fr.pack()
lab=Label(fr,text=el['name']); lab.pack()
e = Entry(fr); e.pack(); e.insert(0,str(el['inival'])) # number of generations
el['Entry']=e
def draw_ini_solu(self):
self.frontman.plot_into_axes(self.sp1)
txt='initial DNA'.format(self.frontman.DNA)
self.sp1t.set_text(txt)
def draw_solu(self,dude):
self.frontman.copy_DNA_of(dude,copyscore=True,copyparents=True,copyancestcode=True)
self.frontman.evaluate()
self.frontman.update_plot(self.sp1)
txt='generation {}: score is {:.3f} after {} function calls'.format(self.p.gg,self.ea.bestdude.score,self.ea.tell_neval())
#self.sp1t.set_text(txt)
self.sp1.set_title(txt)
self.c.draw()
def mainloop(self):
self.mwin.mainloop()
def randini(self):
self.p.reset()
self.rec.clear()
self.ea.bestdude=None
self.ea.zeroth_generation(random_ini=True)
self.draw_solu(self.ea.bestdude)
self.c.draw()
def run_with_readout(self):
for el in self.vl:
if el['type'] is float:
val=float(el['Entry'].get())
exec('self.ea.'+el['name']+'='+str(val))
elif el['type'] is int:
val=int(float(el['Entry'].get()))
exec('self.ea.'+el['name']+'='+str(val))
elif el['type'] is str:
val=el['Entry'].get()
exec('self.ea.'+el['name']+"='"+val+"'")
elif el['type'] is list:
val=el['Entry'].get()
exec('self.ea.'+el['name']+"="+val)
print 'string {} and what resulted {}'.format(val,eval('self.ea.'+el['name']))
else:
raise NotImplementedError('only float and int parameters cared for at this point')
self.ea.run(int(float(self.e_gg.get())))
def run_no_readout(self):
self.ea.run(int(float(self.e_gg.get())))
def update_solu_canvas(self,eaobj):
if np.mod(self.p.gg,self.update_freq)==0:
self.draw_solu(self.ea.bestdude)
def ini_mstep_bar(self):
fg_color=bluered4hex(0.36); #textcolor='white'
self.c2.create_rectangle(43,0,57,140,fill='white',outline='white')
mstep_barheight=int(-0.25*log10(self.ea.mstep)*140); mstep_barheight=clip(mstep_barheight,0,140)
self.mstep_bar=self.c2.create_rectangle(43,mstep_barheight,57,140,fill='green',outline='green')
for h in [2,35,70,105,140]:
self.c2.create_line(40,h,60,h,width=2,fill=fg_color)
for h,poww in zip([6,30,65,100,130],['0','-1','-2','-3','-4']):
self.c2.create_text(20,h,text='10**'+poww,font=('Courier','6'))
def update_mstep_bar(self,eaobj):
mstep_barheight=int(-0.25*log10(self.ea.mstep)*140); mstep_barheight=clip(mstep_barheight,0,140)
self.c2.coords(self.mstep_bar,43,mstep_barheight,57,140)
self.mwin.update_idletasks()
def rec_save_status(self,eaobj):
self.rec.save_status()
def acp_ini(self,whiggle=0):
x=[]; y=[]; farbe=[]
for i,g in enumerate(self.rec.gg):
for j in range(self.p.psize):
x.append(g)
y.append(self.rec.adat['scores'][i][j])
farbe.append(self.rec.adat['ancestcodes'][i][j])
x.append(0); y.append(0); farbe.append(0.) # for normalisation of color map
x.append(0); y.append(0); farbe.append(1.) # for normalisation of color map
x=flipud(array(x)); y=flipud(array(y)); farbe=flipud(array(farbe))
if whiggle: x=x+whiggle*npr.rand(len(x))-0.5*whiggle
self.acdots=self.sp2.scatter(x,y,marker='o',c=farbe,cmap=ancestcolors,zorder=True)
if self.acp_type=='semilogy':
self.sp2.semilogy()
if self.acp_ylim:
self.sp2.axis((0,self.p.gg,self.acp_ylim[0],self.acp_ylim[1]))
else:
self.sp2.axis((0,self.p.gg,0,np.max(y)))
def acp_update(self,eaobj,whiggle=0):
if np.mod(self.p.gg,self.acp_freq)==0:
self.sp2.cla()
self.acp_ini(whiggle=whiggle)
self.c.draw()
示例10: xrange
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
errors=set()
for xx in xrange(-W,W): #frange(-W/CELLSIZE,W/CELLSIZE,0.05): # перебор значений Х слева направо
x=xx/CELLSIZE
try:
y=f(x) # вычисляем
if isinstance(y,bool) or y is None or not isinstance(y,(float,int,long)):
line=0
continue
# try: float(y)
# except TypeError:
# line=0
# continue
if line: # если предыдущая точка существует
L.append(c.create_line((px*CELLSIZE)+W/2,(-py*CELLSIZE)+H/2,(xx)+W/2,(-y*CELLSIZE)+H/2,width=1))
# то рисует линию из той в текущую точку
r.update_idletasks() # обновляем вид, чтоб на кпк не зависало
#print (px,py),(x,y)
px,py=x,y # сохраняем точку
line=1 # как существующую
except (ArithmeticError,ValueError),e:
line=0
continue
except Exception,e: # если ошибка
line=0 # то этой точки в графике не будет
# print e
errors.add('%s: %s'%(e.__class__.__name__,e))
continue
if errors: #len(L)==prevlen and
import tkMessageBox
s=u'Ошибки при вычислении:\n'
for e in errors: s+=' %s\n'%e
示例11: Widget
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
self._table[row][col] = Widget(master=self._tableFrame)
self._table[row][col].settext("(%d, %d)" % (row, col))
self._table[row][col].grid(row=row, column=col, sticky=E+W)
# For debugging
self._canvas.config(background="blue")
self._tableFrame.config(background="red")
yScroll.pack(side=RIGHT, fill=Y)
xScroll.pack(side=BOTTOM, fill=X)
self._canvas.create_window(0, 0, window=self._tableFrame, anchor=N+W)
self._canvas.pack(side=LEFT, fill=BOTH, expand=True)
tkRoot = Tk()
# Application Size and Center the Application
appSize = (800, 600)
w = tkRoot.winfo_screenwidth()
h = tkRoot.winfo_screenheight()
x = w / 2 - appSize[0] / 2
y = h / 2 - appSize[1] / 2
tkRoot.geometry("%dx%d+%d+%d" % (appSize + (x, y)))
tkRoot.update_idletasks() # Force geometry update
app = Application(5, 5, master=tkRoot)
app.pack(side=TOP, fill=BOTH, expand=True)
tkRoot.mainloop()
示例12: Tk
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
# Прорисовка окна, основы для прямоугольников и самих прямоугольников,
# кнопок для пуска и выхода
tk = Tk()
tk.title("Соревнование потоков")
c = Canvas(tk, width=distance, height=nrunners*h, bg="White")
c.pack()
rects = [c.create_rectangle(0, i*h, 0, i*h+h2, fill=colors[i])
for i in range(nrunners)]
go_b = Button(text="Go", command=tk.quit)
go_b.pack(side=LEFT)
quit_b = Button(text="Quit", command=quit)
quit_b.pack(side=RIGHT)
# Замок, регулирующий доступ к функции пакета Tk
graph_lock = threading.Lock()
# Цикл проведения соревнований
while 1:
go_b.config(state=NORMAL), quit_b.config(state=NORMAL)
tk.mainloop() # Ожидание нажатия клавиш
champion = None
ready_steady_go()
go_b.config(state=DISABLED), quit_b.config(state=DISABLED)
# Главный поток ждет финиша всех участников
while sum(positions) < distance*nrunners:
update_positions()
update_positions()
go_b.config(bg=champion) # Кнопка окрашивается в цвет победителя
tk.update_idletasks()
示例13: exit
# 需要导入模块: from Tkinter import Tk [as 别名]
# 或者: from Tkinter.Tk import update_idletasks [as 别名]
# everything beyond this point.
if update_mode:
fname = file_name.search(url).group(0)
if fname in latest_image:
exit(0)
download_from_url(url, output_directory,
serialize, post_count-processed)
processed += 1
driver.close()
top = Tk()
top.title('Instagram Downloader')
top.update_idletasks()
# Username or url label and entry box
L_username = Label(top, text="Username or url")
L_username.grid(row=0, column=0, sticky=N+S+E+W)
E_username_text = StringVar()
E_username = Entry(top, bd=2, textvariable=E_username_text)
E_username.grid(row=0, column=1, columnspan=2, sticky=N+S+E+W)
# Download path label, file browser button, and download path entry box
L_path = Label(top, text="Download path")
L_path.grid(row=1, column=0, sticky=N+S+E+W)