【问题标题】:Tkinter grid layout won't expandTkinter 网格布局不会扩展
【发布时间】:2015-08-07 19:26:37
【问题描述】:

我正在尝试设计类似于 Google 的大多数侧边栏菜单的侧边栏(例如在收件箱或播放音乐、浏览器版本中)。 我正在使用网格布局,但它不会扩展。我查了一下,尽管添加了sticky = "nesw"rowconfigure(0, weigth = 1),但右侧的框架不会扩展并填充根。

from tkinter import *
from tkinter import ttk

buttons = ["Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button"]  # List of contacts

root = Tk()
root.title('MyApp v0.1')
root.geometry('800x600')
#root['bg'] = "white"

# Side menu
frame = Frame(root, background = "white")
for i in range(len(buttons)):
    Button(frame, background = "white", text = buttons[i], command = None).grid(row = i, column = 0)
frame.rowconfigure(0, weight = 1)
frame.grid(row = 0, column = 0, sticky = "nesw")

sep = ttk.Separator(root, orient = "vertical")
sep.rowconfigure(0, weight = 1)
sep.columnconfigure(1, weight = 1)
sep.grid(row = 0, column = 1, padx = 5, sticky = "nesw")

root.mainloop()

这就是我得到的。我左边的按钮应该在白色背景框架上。 Frame 和分隔符应位于应用程序窗口的底部。

提前致谢。

【问题讨论】:

    标签: python user-interface python-3.x tkinter python-3.4


    【解决方案1】:

    如果您希望 Buttons 的容器从窗口顶部一直延伸到底部,请尝试在根目录上调用 rowconfigure。如果您希望按钮均匀分布,而不是调用frame.rowconfigure(0, weight = 1),请为从0 到len(buttons) 的帧的每一 行调用frame.rowconfigure

    from tkinter import *
    from tkinter import ttk
    
    buttons = ["Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button", "Button"]  # List of contacts
    
    root = Tk()
    root.title('MyApp v0.1')
    root.geometry('800x600')
    #root['bg'] = "white"
    root.rowconfigure(0, weight=1)
    
    # Side menu
    frame = Frame(root, background = "white")
    for i in range(len(buttons)):
        Button(frame, background = "white", text = buttons[i], command = None).grid(row = i, column = 0)
        frame.rowconfigure(i, weight = 1)
    frame.grid(row = 0, column = 0, sticky = "nesw")
    
    sep = ttk.Separator(root, orient = "vertical")
    sep.rowconfigure(0, weight = 1)
    sep.columnconfigure(1, weight = 1)
    sep.grid(row = 0, column = 1, padx = 5, sticky = "nesw")
    

    结果:

    【讨论】:

    • 这是正确但不好的做法,如果我在根内有 2 层,我只想将最后一层拉伸到底部而不拉第一层怎么办?
    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多