我正在尝试使用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()
答案 0 :(得分:0)
要使用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