【问题标题】:Placing multiple buttons in same column - Tkinter using grid在同一列中放置多个按钮 - Tkinter 使用网格
【发布时间】:2021-06-27 05:52:45
【问题描述】:

我正在尝试创建一个用于显示数据的 GUI,用户可以使用底部的页面按钮(第 1、2、3 页等)翻阅页面。问题是目前我制作的整个窗口有两列等宽。如果我添加显示“1”“2”“3”“4”的按钮,它们会分散在两列中。我尝试了粘性选项,但看起来仍然不正确。我希望将四个按钮并排放置在窗口底部的中间。有什么方法可以做到这一点而不必更改上面的列数?

我尝试创建一个框架并尝试查看是否可以在该框架中容纳更多列,但最终只是将这些列添加到其他两列的右侧。

    fr=tk.Frame(master).grid(row=23,column=0, rowspan=1, columnspan=4)
    b=tk.Button(fr,text='1',command=page1)
    b.grid(row=23, column=1, sticky=tk.W)
    b1=tk.Button(fr,text='2', command=page2)
    b1.grid(row=23, column=1, sticky=tk.E)
    b2=tk.Button(fr,text='3', command=page3)
    b2.grid(row=23, column=2, sticky=tk.W)
    b3=tk.Button(fr,text='4', command=page4)
    b3.grid(row=23, column=2, sticky=tk.E)

【问题讨论】:

    标签: user-interface tkinter grid-layout


    【解决方案1】:

    您可以简单地创建一个新框架并将其作为您的主框架作为父框架,然后您可以在其中创建所需的列数并使用它。 这是一个简单的例子:

    app = tk.Tk()
    fr=tk.Frame(app)
    fr.grid(rowspan=2, columnspan=2)
    
    # this represents what you have in the page above
    something_large = tk.Button(fr, text="HELLO WORLD")
    something_large_too = tk.Button(fr, text="Hello world")
    something_large.grid(row=0, column=0)
    something_large_too.grid(row=0, column=1)
    
    bottom_frame = tk.Frame(fr)
    bottom_frame.grid(row=1, columnspan=2)
    b=tk.Button(bottom_frame,text='1')
    b.grid(row=0, column=0)
    b1=tk.Button(bottom_frame,text='2')
    b1.grid(row=0, column=1,)
    b2=tk.Button(bottom_frame,text='3')
    b2.grid(row=0, column=2)
    b3=tk.Button(bottom_frame,text='4')
    b3.grid(row=0, column=3)
    app.mainloop()
    

    如果您希望按钮之间有一些空间,只需在网格化它们时更改它们的 padx 属性。

    【讨论】:

    • 非常感谢,这有帮助。我只是复制了你的方法,最后把按钮放在一起;但是,当我添加不同的列号时,它会一直将它们放在同一个位置。例如,我尝试了第 0 列中的按钮 1、第 0 列中的按钮 2、第 10 列中的按钮 5 和按钮 3。它仍然将它们都放在同一个位置,就好像我没有更改列号一样。你知道为什么会这样吗?我什至尝试将权重添加到十列,但没有奏效。
    • 我认为这可能是您正在寻找的。 stackoverflow.com/q/28019402/13962302
    猜你喜欢
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多