您的位置:首页 > 编程语言 > Python开发

Python TKinter Gui: Toplevel window

2010-05-04 22:11 447 查看
#from pp3e Chapter 9.3

#############################################################################
# popup three new window, with style
# destroy() kills one window, quit() kills all windows and app; top-level
# windows have title, icon, iconify/deiconify and protocol for wm events;
# there always is an app root window, whether by default or created as an
# explicit Tk() object; all top-level windows are containers, but never
# packed/gridded; Toplevel is like frame, but new window, and can have menu;
#############################################################################

from Tkinter import *
root = Tk() # explicit root

trees = [('The Larch!', 'light blue'),
('The Pine!', 'light green'),
('The Giant Redwood!', 'red')]

for (tree, color) in trees:
win = Toplevel(root) # new window
win.title('Sing...') # set border
win.protocol('WM_DELETE_WINDOW', lambda:0) # ignore close
win.iconbitmap('py-blue-trans-out.ico') # not red Tk

msg = Button(win, text=tree, command=win.destroy) # kills one win
msg.pack(expand=YES, fill=BOTH)
msg.config(padx=10, pady=10, bd=10, relief=RAISED)
msg.config(bg='black', fg=color, font=('times', 30, 'bold italic'))

root.title('Lumberjack demo')
Label(root, text='Main window', width=30).pack()
Button(root, text='Quit All', command=root.quit).pack() # kills all app
root.mainloop()

一些重要需要注意的地方:

截取关闭: protocol
由于窗口管理器的关闭event,被这个脚本Topleve的方法protocol截取,使得弹出来的三个窗口上的关闭X失去了作用。 标识WM_DELETE_WINDOW代表关闭操作。你可以使用这个接口去禁止关闭操作与你脚本创建的widget分离。这个函数由lambda:0创建,但它什么也不做,只是返回一个0值。

关闭一个窗口: destroy

点击弹出窗口的又大又黑的button,仅仅关闭其本身,不影响其它弹出的窗口。这是 由于调用了destroy方法。

关闭所有窗口: quit

关闭所有窗口,并退出Gui程序。root窗口使用quit方法。

窗口标题: title

使用title方法改变窗口标题。

窗口图标: iconbitmap

使用iconbitmap方法改变顶层窗口使用的图标。

Geometry management

Top-level 窗体是其他widgets的容器,很像Frame。但是与frame不同的是,top-level窗体不会pack(grid,place)它们自己。为了嵌入widgets,这个脚本把他的窗体作为Label和button的构造器的parent的参数。当然也可以获得窗体显示大小的最大值,使用maxsize()方法,也可以初始化窗体的tope-level的函数geometry('widthhxheight+x+y)方法。通常使用Tkinter本身调整窗口大小更简单一点,但是显示大小也许会被用于如图形显示倍化。
此外,top-level窗体还支持其他的我们在后面会用到的protocols:

State

top-level 窗体对象 的方法方法 iconify和方法 withdraw 可以是脚本隐藏和擦除一个窗口,在闲置时。 deiconify方法重绘 一个隐藏或擦掉的窗口。 state方法查询或改变一个窗体的状态。判断状态是否正常或返回 iconic, withdrawn, zoomed (全屏;别的地方使用geometry) and normal (足够大)。lift and lower 方法唤起和挂起一个窗体相关的同属。参考第十章里alarm程序脚本。

Menus

Each top-level window can have its own window menus too; both the Tk and the Toplevel widgets have a menu option used to associate a horizontal menu bar of pull-down option lists. This menu bar looks as it should on each platform on which your scripts are run. We'll explore menus early in Chapter 10.

Most top-level window-manager-related methods can also be named with a "wm_" at the front; for instance, state and protocol can also be called wm_state and wm_protocol.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: