【问题标题】:How to center Button using grid?如何使用网格居中按钮?
【发布时间】:2019-01-30 08:00:28
【问题描述】:

我正在尝试使用 grid() 在 tkinter 框架窗口中将按钮小部件居中。我尝试了几种解决方案,包括weights,但它们都没有以文本“选择文件”将按钮小部件居中。它要么左粘要么右粘。我该怎么做呢?

顺便说一句,我不想​​使用pack()。我想继续使用grid()

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("PDF Merger v0.1")
        self.filenamesopen = []
        self.grid(sticky=W + E + N + S)

        self.button = Button(self, text="Choose files", command=self.load_files, width=10)
        self.button.grid(row=0, column=0,sticky=E+W)

        self.button = Button(self, text="Merge", command=self.merge_files, width=10)
        self.button.grid(row=1, column=0, sticky=W)
        self.labelframe = LabelFrame(self, text="Files to merge:")
        self.labelframe.grid(row=2, column=0, sticky=W)
        self.left = Label(self.labelframe, text="")
        self.left.grid(row=3, column=0, sticky=W)
    def load_files(self):
        try:
            self.filenamesopen = filedialog.askopenfilenames(initialdir="/", title="Choose files to merge...",
                                                filetypes=(("pdf", "*.pdf"), ("All files", "*.*")))
            filenames = [os.path.split(file)[1] for file in self.filenamesopen]
            self.left.configure(text="\n".join(filenames))
        except:
            showerror("Open Source File", "Failed to read files\n")

    def merge_files(self):
        self.merger = PdfFileMerger()
        try:
            for pdf in self.filenamesopen:
                self.merger.append(open(pdf, 'rb'), import_bookmarks=False)
        except:
            showerror("Merger Error", "Failed to merge files\n")
            return
        self.save_files()
    def save_files(self):
        try:
            self.filenamesave = filedialog.asksaveasfilename(initialdir="/", title="Save as...",
                                     filetypes=(("pdf", "*.pdf"), ("All files", "*.*")),
                                                         defaultextension=".pdf")
            with open(self.filenamesave, 'wb') as fout:
                self.merger.write(fout)
        except:
            showerror("Save Source File", "Failed to save file\n")
if __name__ == "__main__":
    MyFrame().mainloop()

【问题讨论】:

  • 在窗口中居中,还是相对于其他小部件居中?您是否希望在调整窗口大小时所有内容都保持居中?
  • 嗨@BryanOakley,我希望它在窗口中居中(当窗口也被调整大小时)。最后,我想将所有内容居中,但首先我尝试将其中一个 Button 小部件居中。

标签: python tkinter


【解决方案1】:

要使用grid() 在窗口或框架内居中小部件,您需要为小部件所在的单元格设置权重。每当大小更改时,小部件将自动居中。请参阅下面的示例:

from tkinter import *

root = Tk()
root.geometry('300x200')
root.columnconfigure(0, weight=1)   # Set weight to row and 
root.rowconfigure(0, weight=1)      # column where the widget is

container = Frame(root, bg='tan')   # bg color to show extent
container.grid(row=0, column=0)     # Grid cell with weight

# A couple of widgets to illustrate the principle.
b1 = Button(container, text='First', width=10)
b1.grid(pady=10, padx=20)
b2 = Button(container, text='second', width=10)
b2.grid(pady=(0,10), padx=20)

root.mainloop()

一个很好的参考:The Tkinter Grid Geometry Manager

【讨论】:

  • 谢谢@figbeam!我在我的代码中实现了你的提示,对代码进行了一些重组,它可以工作。我还是 tkinter 的新手。
猜你喜欢
  • 2012-04-24
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2013-09-13
  • 1970-01-01
  • 2019-09-11
  • 2018-02-08
相关资源
最近更新 更多