我正在制作我的第一个GUI应用程序而且我遇到了一个愚蠢的问题。调整主窗口大小不会调整其内容的大小并留下空白。我已经阅读过TKDocs,他们只说你应该使用粘性和列/行权重属性,但我真的不明白它们是如何工作的。 这是我的代码(只有覆盖小部件的部分,如果你认为问题不在这里,我会发布剩下的部分):
from tkinter import *
from tkinter import ttk
root = Tk()
mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
player1 = StringVar()
player2 = StringVar()
player1.set('Player 1')
player2.set('Player 1')
timer=StringVar()
running=BooleanVar()
running.set(0)
settimer = ttk.Entry(mainframe, width=7, textvariable=timer)
settimer.grid(column=2, row=1, sticky=(N, S))
ttk.Button(mainframe, text="Start", command=start).grid(column=2, row=2, sticky=(N, S))
ttk.Label(mainframe, textvariable=player1, font=TimeFont).grid(column=1, row=3, sticky=(W, S))
ttk.Label(mainframe, textvariable=player2, font=TimeFont).grid(column=3, row=3, sticky=(E, S))
for child in mainframe.winfo_children():
child.grid_configure(padx=80, pady=10)
root.mainloop()
谢谢你的时间!
答案 0 :(得分:8)
也许这会帮助你朝着正确的方向前进。请务必在每个级别配置列/行权重。
import tkinter.ttk
from tkinter.constants import *
class Application(tkinter.ttk.Frame):
@classmethod
def main(cls):
tkinter.NoDefaultRoot()
root = tkinter.Tk()
app = cls(root)
app.grid(sticky=NSEW)
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
root.resizable(True, False)
root.mainloop()
def __init__(self, root):
super().__init__(root)
self.create_variables()
self.create_widgets()
self.grid_widgets()
self.grid_columnconfigure(0, weight=1)
def create_variables(self):
self.player1 = tkinter.StringVar(self, 'Player 1')
self.player2 = tkinter.StringVar(self, 'Player 2')
self.timer = tkinter.StringVar(self)
self.running = tkinter.BooleanVar(self)
def create_widgets(self):
self.set_timer = tkinter.ttk.Entry(self, textvariable=self.timer)
self.start = tkinter.ttk.Button(self, text='Start', command=self.start)
self.display1 = tkinter.ttk.Label(self, textvariable=self.player1)
self.display2 = tkinter.ttk.Label(self, textvariable=self.player2)
def grid_widgets(self):
options = dict(sticky=NSEW, padx=3, pady=4)
self.set_timer.grid(column=0, row=0, **options)
self.start.grid(column=0, row=1, **options)
self.display1.grid(column=0, row=2, **options)
self.display2.grid(column=0, row=3, **options)
def start(self):
timer = self.timer.get()
self.player1.set(timer)
self.player2.set(timer)
if __name__ == '__main__':
Application.main()