【问题标题】:Align a button to the bottom, Using Tkinter [duplicate]使用 Tkinter 将按钮与底部对齐 [重复]
【发布时间】:2018-02-10 18:02:04
【问题描述】:

谁能帮我在 Tkinter 中将按钮对齐到屏幕底部。我正在关注一个 youtube 教程,他们在他们的代码中编写了我所写的内容,但它将按钮与底部对齐。我在 mac 上使用 python 3.7

from tkinter import *

root = Tk() #makes a blank popup, under the variable name 'root'

topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

button1 = Button(topFrame, text='Button 1', fg='red')
button2 = Button(topFrame, text='Button 2', fg='blue')
button3 = Button(topFrame, text='Button 3', fg='green')
button4 = Button(topFrame, text='Button 4', fg='pink')

button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack(side=BOTTOM)

root.mainloop() #loops the program forever until its closed

【问题讨论】:

  • 您期望的结果是什么?我得到四个按钮水平对齐,从左到右。你想让它们垂直对齐吗?
  • 底部的按钮应该在bottomFrame,还是应该在bottomFrame的上方或下方?

标签: python tkinter


【解决方案1】:

我认为你应该将button4 添加到bottomFrame

button4 = Button(bottomFrame, text='Button 4', fg='pink')

【讨论】:

    【解决方案2】:

    我建议你使用grid() 而不是pack(),它可以让定位更加可控。

    grid() 方法创建了一种表格,其中包含允许您定位元素的行和列。

    这是我想到的布局:

     -----
    |A|B|C|
     -----
    | |D| |
     -----
    
    • A:第 1 行第 0 列
    • B:第 1 行,第 1 列
    • C:第 1 行,第 2 列
    • D:第 2 行,第 1 列

    如果这不是您希望元素看起来的样子,请编辑您的帖子或评论,我会相应地编辑我的答案。


    考虑到这一点,我们可以将.pack() 更改为这种方法:

    from tkinter import *
    
    root = Tk() #makes a blank popup, under the variable name 'root'
    
    topFrame = Frame(root)
    topFrame.pack()
    bottomFrame = Frame(root)
    bottomFrame.pack(side=BOTTOM)
    
    button1 = Button(topFrame, text='Button 1', fg='red')
    button2 = Button(topFrame, text='Button 2', fg='blue')
    button3 = Button(topFrame, text='Button 3', fg='green')
    button4 = Button(topFrame, text='Button 4', fg='pink')
    
    button1.grid(column=0, row = 1)
    button2.grid(column=1, row = 1)
    button3.grid(column=2, row = 1)
    button4.grid(column=1, row = 2)
    
    root.mainloop() #loops the program forever until its closed
    

    pack()grid() 不能同时使用,您必须使用其中一个。

    我还建议不要使用from tkinter import *,这是不安全的,可能会覆盖函数,并且很可能在某些时候会给您带来问题。

    【讨论】:

    • 独立于首选几何管理器,我一直认为应该将 button4 添加到 bottomFrame。
    • from tkinter import * 怎么不是线程安全的?
    • @davidedb 你说的很对,解决了这个问题。我只是列出另一种解决问题的方法。
    • @Rightleg 我的错误from tkinter import * 是不安全的,可能会覆盖函数,tkinter 不是线程安全的。 stackoverflow.com/questions/14168346/…
    【解决方案3】:

    这在大多数情况下可能被认为是不切实际的,但一种方法是简单地交换以下行:

    button1.pack(side=LEFT)
    

    与:

    button4.pack(side=BOTTOM)
    

    这将使button4 填充第一个空白空间,而不是最后一个,在“腔”中进一步解释here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多