[英]Resizing listbox with Python Tkinter and grid layout manager
I am trying to write a simple app with two side-by-side scrollable listboxes. 我正在尝试编写一个带有两个并排可滚动列表框的简单应用程序。 I want them each to take up half the window irrespective of the window size. 我希望他们每个人都占用一半的窗口,而不管窗口大小如何。 While my window is resizable, the listboxes remain the same size and just get centered horizontally in their respective halves. 虽然我的窗口可调整大小,但列表框的大小保持不变,只是在各自的一半中水平居中。 What am I doing wrong? 我究竟做错了什么?
from Tkinter import *
import os
import sys
class ScrollableList(Frame):
def __init__(self, parent, vscroll=True, hscroll=False):
Frame.__init__(self, parent)
self.grid(sticky=NSEW)
if vscroll:
self.vScrollbar = Scrollbar(self, orient=VERTICAL)
self.vScrollbar.grid(row=0, column=1, sticky=N+S)
if hscroll:
self.hScrollbar = Scrollbar(self, orient=HORIZONTAL)
self.hScrollbar.grid(row=1, column=0, sticky=E+W)
self.listbox = Listbox(self, selectmode=SINGLE)
self.listbox.grid(row=0, column=0)
if vscroll:
self.listbox['yscrollcommand'] = self.vScrollbar.set
self.vScrollbar['command'] = self.listbox.yview
if hscroll:
self.listbox['xscrollcommand'] = self.hScrollbar.set
self.hScrollbar['command'] = self.listbox.xview
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=0)
self.grid_rowconfigure(0, weight=1)
self.grid_rowconfigure(0, weight=0)
class Application(Frame):
@classmethod
def main(cls):
NoDefaultRoot()
root = Tk()
app = cls(root)
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.resizable(True, True)
root.mainloop()
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.grid(sticky=NSEW)
options = dict(sticky=NSEW, padx=3, pady=4)
self.list1 = ScrollableList(self)
self.list2 = ScrollableList(self)
self.list1.grid(row=0, column=0, **options)
self.list2.grid(row=0, column=1, **options)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
self.grid_columnconfigure(1, weight=1)
if __name__ == "__main__":
Application.main()
您在将实际的列表框添加到其父级时会忘记设置sticky
属性,这会导致列表框的边缘“粘连”到为其分配的区域的边缘。
self.listbox.grid(..., sticky="nsew")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.