我正在创建一个基于GUI的Python游戏。我为正在使用的每个框架都有一个类,但是当我设置行和列以便它们随窗口缩放时,什么也没有发生。该代码将执行,但不会执行应做的事情。我是编码领域的新手,经过几个小时的研究,我找不到解决方案。
我已经在这个网站和Google的其他地方四处寻找答案。我已经测试了我在类和框架之外编写的代码,并且一切正常。再次添加这些东西使其无法正常工作。
from tkinter import *
import sys
class Application(Tk):
def __init__(self):
Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
#This is the starting page
class StartPage(Frame):
def __init__(self, root):
Frame.__init__(self, root)
label_1 = Label(self,text="I exist", font=('Courier', 30))
label_1.grid(row=0, column=1)
label_2 = Label(self, text="Pick a way to play", font=('Courier', 15))
label_2.grid(row=1, column=1)
button_1 = Button(self, text="New Game", fg='black', bg='green', width=25, command=lambda: root.switch_frame(PlayerInfo))
button_1.grid(row=1, column=0)
button_2 = Button(self, text="Load Game", fg='black', bg='yellow', width=25, command=lambda: root.switch_frame(LoadGame))
button_2.grid(row=1, column=2)
button_3 = Button(self, text='Exit Game', fg='black', bg='red', width=25, command=lambda: sys.exit())
button_3.grid(row=2, column=1)
label_3 = Label(self, text='')
label_3.grid(row=1, column=1)
label_4 = Label(self, text='')
label_4.grid(row=2, column=0)
label_5 = Label(self, text='')
label_5.grid(row=2, column=2)
#Here is the configuring problem
self.grid_columnconfigure(0,weight=1)
self.grid_columnconfigure(1,weight=1)
self.grid_columnconfigure(2,weight=1)
self.grid_columnconfigure(3,weight=1)
self.grid_rowconfigure(3, weight=1)
self.grid_rowconfigure(0,weight=1)
self.grid_rowconfigure(1,weight=1)
self.grid_rowconfigure(2,weight=1)
class PlayerInfo(Frame):
def __init__(self, root):
Frame.__init__(self, root)
Label(self, text='Game will start').pack()
class LoadGame(Frame):
def __init__(self, root):
Frame.__init__(self, root)
Label(self, text='Load old game').pack()
#Run it
if __name__ == "__main__":
app = Application()
app.mainloop()
我知道如何使用.grid_rowconfigure(),但是在类中使用它时,它根本没有做任何事情。任何帮助或建议,我们将不胜感激! :)
答案 0 :(得分:1)
问题不在于grid_rowconfigure()
,而是问题pack
。您的框架仅占据所需的空间,因此即使您的窗口扩展了,框架也保持不变。
要使框架也展开,请将另外两个参数传递给您的pack
方法:
self._frame.pack(expand=True,fill="both")