Python GUI编程入门(30)-Sizegrip控件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/craftsman1970/article/details/102670813

Sizegrip就是下图右下角红圈中那个用来调整窗口大小的小控件。

先看动作视频:

视频链接

从视频中可以看到,一切都是那么的自然。但是由于Tkinter中调整窗口的逻辑多少有些另类,本来简单的事情实际上并不简单。首先是构建主窗口。

root = Tk()root.title('Tkinter Sizegrip Demo V1.0')
screen_w = root.winfo_screenwidth()screen_h = root.winfo_screenheight()root.maxsize(width=screen_w, height=screen_h)rw = int(screen_w / 2)rh = int(screen_h / 2)root.geometry('{}x{}+{:g}+{:g}'.format(rw, rh, rw / 2, rh / 2))

代码中除了指定了窗口标题之外,还对窗口进行了居中处理。接下来是构建退出菜单:

top_menu = Menu(root)root.config(menu=top_menu)
file_menu = Menu(top_menu, tearoff=False)top_menu.add_cascade(label='File', menu=file_menu)file_menu.add_command(label="Exit", command=root.quit)

为了方便管理,首先生成一个管理编辑器控件的Frame控件:

edit_area = Frame(root)edit_area.grid(row=1, column=0)
 

生成Text控件时同时调整了控件的尺寸。由于Text的高度和宽度都是以字符为单位指定,因此多费了不少周折。如果不调大Text的尺寸,当root窗口的尺寸大到某个值的时候,Text就不再跟随窗口的尺寸。

# create text widget.
font = Font(family='Arial', size=15),text = Text(edit_area, font=font, height=80, wrap=NONE)text.config(width=int(text['width']* screen_w / text.winfo_reqwidth()),            height=int(text['height']* screen_h / text.winfo_reqheight()))text.grid(row=0, column=0, sticky='nsew')

text.config的执行结果是将Text控件的大小调整为和屏幕同样大小。接下来构建滚动条控件,都是标准做法。

scroll_ty = Scrollbar(edit_area, orient=VERTICAL, command=text.yview)scroll_ty.grid(row=0, column=1, sticky=N+S)text['yscrollcommand']=scroll_ty.set
scroll_tx = Scrollbar(edit_area, orient=HORIZONTAL, command=text.xview)scroll_tx.grid(row=1, column=0, sticky=E+W)text['xscrollcommand']=scroll_tx.set

Sizegrip本身很简单:

Sizegrip(edit_area).grid(row=1, column=1)

接下来的代码用户控制Text控件充满Frame控件,而Frame控件又填满root窗口。

完整代码可以从以下地址下载:

https://github.com/xueweiguo/TkinterPrimer/blob/master/Sample/30%20Editor.py

觉得本文有帮助?请分享给更多人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/102670813