web-dev-qa-db-ja.com

grid()を使用してウィジェットを水平方向に中央揃えする方法は?

grid()を使用して、ウィジェットをtkinterウィンドウに配置しています。ウィンドウの水平方向の中央にラベルを付けて、ウィンドウのサイズを変更してもラベルをそのままにしようとしています。どうすればこれを実行できますか?

ちなみに、私はpack()を使いたくありません。 grid()を使い続けたいです。

9
L4undry

トリックはありません。ウィジェットはデフォルトで割り当てられた領域の中央に配置されます。 sticky属性のないセルにラベルを配置するだけで、中央に配置されます。

さて、もう1つの問題は、割り当てられる領域を中央に配置する方法です。それは、他にどのようなウィジェットがあるか、どのように配置されているかなど、他の多くの要因に依存します.

これは、単一の中央揃えされたラベルを示す簡単な例です。これは、行と列がすべての余分なスペースを占めることを確認することによって行われます。ウィンドウをどれほど大きくしても、ラベルは中央揃えのままです。

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This should be centered")
        label.grid(row=1, column=1)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).grid(sticky="nsew")
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    root.mainloop()

すべての行と列に重みを付けると、同様の効果を得ることができますexceptラベルのあるもの。

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This should be centered")
        label.grid(row=1, column=1)

        self.grid_rowconfigure(0, weight=1)
        self.grid_rowconfigure(2, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(2, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).grid(sticky="nsew")
    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)

    root.mainloop()
12
Bryan Oakley

特別なことは何も必要ありません。ウィジェットはその親の真ん中に自動的に配置されます。利用可能なすべてのスペースを埋めるように親に指示するために必要なもの。

from tkinter import *
root = Tk()
root.geometry("500x500+0+0")
frmMain = Frame(root,bg="blue")

startbutton = Button(frmMain, text="Start",height=1,width=4)
startbutton.grid()

#Configure the row/col of our frame and root window to be resizable and fill all available space
frmMain.grid(row=0, column=0, sticky="NESW")
frmMain.grid_rowconfigure(0, weight=1)
frmMain.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

root.mainloop()

これはパックではなくグリッドを使用してウィジェットを配置し、グリッドはウィンドウのサイズ全体を埋めるように構成されています。ボタンはウィンドウのサイズに関係なく中央に表示されます。

1
scotty3785