简单的对话框级别的布局一旦决定就不会再调整。但是对于类似IDE开发环境等更大的画面,可能需要动态调整功能分区的大小,这时就需要分栏窗口控件PanedWindow。
使用这个控件调整画面分区大小的视频如下:
这个控件的构建非常简单。代码中设定background属性并不是必须,只是为了表示控件的范围。
paned_window = PanedWindow(root, background="#a0ffa0")
构建左侧的Lisbox分区并设定其动作,这部分代码来自之前的示例。最后一行将Listbox添加到PanedWindow上。
# create fontftiTimes = Font(family='Times', size=24, weight=BOLD)# create a listbox for demo.lb = Listbox(paned_window,activestyle='dotbox',bg="#ffffa0",fg="#ff0000",disabledforeground="#3f3f3f",highlightbackground="#0000ff",font=ftiTimes,height=10, width=20)# add itemsfor i in range(0,20):lb.insert(END, str(i))# bind eventlb.bind('<>',lambda e: label.config(text=str(lb.curselection())))paned_window.add(lb)
构建一个包含一个Text控件和横竖两个滚动条的Frame控件并添加到PanedWindow上。将edit_area添加到paned_window时指定padx和pady属性在加上最前面指定背景色的结果是可以看到edit_area和paned_window之间的边界,实际的开发不一定需要。
edit_area = Frame(paned_window)# create text widget.text = Text(edit_area,background="#a0ffa0", foreground="#000000",wrap=NONE)text.grid(row = 0, column = 0, sticky=W+N+E+S)scroll_ty = Scrollbar(edit_area, orient=VERTICAL, command=text.yview)scroll_ty.grid(row=0, column=1, sticky=N+S)text['yscrollcommand']=scroll_ty.setscroll_tx = Scrollbar(edit_area, orient=HORIZONTAL, command=text.xview)scroll_tx.grid(row=1, column=0, sticky=E+W)text['xscrollcommand']=scroll_tx.setedit_area.grid_rowconfigure(0, weight=1)edit_area.grid_columnconfigure(0, weight=1)paned_window.add(edit_area, sticky=W+N+E+S, padx=2, pady=2)
17行,18行代码的目的是当edit_area的大小发生变化时,Text的控件的大小随之变化而Scrollbar的宽度维持不变。
将paned_window布置在root窗口的第一行:
paned_window.grid(row = 0, column = 0, sticky=N+S+W+E)
第二行布置一个表示信息的标签控件。
label=Label(root)label.grid(row=1, column=0)
设置跟窗口的行列属性以保证拖动root窗口时,paned_window和label的大小可以正确地随着变化。
完整代码可以从下面的链接下载:
https://github.com/xueweiguo/TkinterPrimer/blob/master/Sample/19%20PanedWindow.py
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】,轻松学习每一天!
有任何疑问,欢迎留言提问或讨论。
面向对象设计,面向对象编程,面向对象思考!