有没有一种方法可以使用 .pack() 将 tkinter 按钮并排放置,同时使它们居中对齐?

Is there a way i can place tkinter buttons next to each other using .pack() while keeping them center justified?

我希望在我的条目小部件下有两个 Tkinter 按钮 (ttk.Button) 并排放置,同时仍使它们居中对齐。我已经为框架中的其他小部件使用 .pack() ,所以我不能对它们使用 .grid() 或 .place() 。我知道您可以使用 tk.LEFT、tk.RIGHT 等将它们排成一行,但这会将它们移到最远的边缘。有没有办法我可以使用这样的方法将它们并排放置在 window?

的中心

这是我的代码:

class EmailPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        send_button = ttk.Button(self, text='Send Email\'s', command=lambda: send_email())
        send_button.pack(padx=10, pady=5)

        test_button = ttk.Button(self, text='Test Email', command=lambda: test_email())
        test_button.pack(padx=10, pady=5)

提前致谢

您可以创建一个 tk.Frame,然后将按钮打包在其中:

from tkinter import ttk   
import tkinter as tk

root=tk.Tk()
tk.Label(root,text='These 2 buttons are in centre!').pack()

f1=tk.Frame(root)
f1.pack(expand=1)
b1=ttk.Button(f1,text='Button 1')
b1.pack(expand=True,side=tk.BOTTOM)
b2=ttk.Button(f1,text='Button 2')
b2.pack(expand=True,side=tk.BOTTOM)

root.mainloop()

我已经复制了您的代码并附加了一些必要的方法以使其成为一个工作示例。

在您的示例中,您的按钮命令不需要 lambda,因为您没有向这些方法发送数据。

此外,self. 需要添加到小部件之前,tk.Frame 需要进行管理。


import tkinter as tk
from tkinter import ttk


class EmailPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        entry = tk.Entry( self, width = 40 )
        entry.pack(fill = tk.BOTH, expand = False)

        self.send_button = ttk.Button(self, text='Send Email\'s', command = self.send_email)
        self.send_button.pack(side=tk.RIGHT, fill = tk.BOTH, expand=True)

        self.test_button = ttk.Button(self, text='Test Email', command = self.test_email)
        self.test_button.pack(side=tk.LEFT, fill = tk.BOTH, expand=True)

        self.pack(fill = tk.BOTH, expand = True)

    def send_email( self ):
        pass

    def test_email( self ):
        pass

my_emailer = EmailPage(tk.Tk(), "")
my_emailer.master.mainloop()