我目前正在使用tkinter在GUI上工作,它允许用户在不同框架之间导航。我的代码结构基于this user response。
我现在的问题是在更改框架时自动将tkinter的窗口调整为其内容。我希望窗口的边框适合红色箭头之后的小部件,如here和here(下面的示例代码的输出),以便每个窗口中都没有这样的“空白”框架。
代码的工作方式为方法show_frame
允许在两个定义的帧之间进行更改。
from tkinter import *
class WindowController(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(root)
container.grid()
self.frames = {}
for F in (FirstWindow, SecondWindow):
frame = F(parent=container, controller=self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(FirstWindow)
self.destroy()
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class FirstWindow(Frame):
def __init__(self, parent, controller):
self.controller = controller
self.parent = parent
Frame.__init__(self, parent)
# Widgets:
# "Do Nothing" Button
self.Title0 = Button(self, text='Do nothing')
self.Title0.grid(row=0, column=0)
# "Do Nothing" Button
self.Title1 = Button(self, text='Do Nothing')
self.Title1.grid(row=1, column=0)
# Change Frame Button
self.Title2 = Button(self, text='To Second Window', command=lambda: self.controller.show_frame(SecondWindow))
self.Title2.grid(row=2, column=0)
class SecondWindow(Frame):
def __init__(self, parent, controller):
self.controller = controller
self.parent = parent
Frame.__init__(self, parent)
# Widgets:
# "Do Nothing" Button
self.Title0 = Button(self, text='Do nothing')
self.Title0.grid(row=0, column=0)
# "Do Nothing" Button
self.Title1 = Button(self, text='Do Nothing')
self.Title1.grid(row=0, column=1)
# Change Frame Button
self.Title2 = Button(self, text='To First Window', command=lambda: self.controller.show_frame(FirstWindow))
self.Title2.grid(row=0, column=2)
if __name__ == "__main__":
root = Tk()
root.resizable(width=False, height=False)
app = WindowController()
app.mainloop()
我的问题似乎与here中的问题类似,但没有解决。
这是我的第一个问题,非常感谢批评。
答案 0 :(得分:1)
答案是问题Tkinter Frame Resize:由于两个框架都被网格化,因此窗口将扩展为包含两个框架。
要使窗口更改大小,一次只需要网格化一帧即可。
要从窗口中删除框架并仍然记住其属性,请使用:
frame.grid_remove()
要再次显示框架,请使用:
frame.grid() # Will remember grid settings
此代码有效,但您可能可以改善其美观性:
class WindowController(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(root)
container.grid()
self.frames = {}
for F in (FirstWindow, SecondWindow):
frame = F(parent=container, controller=self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
frame.grid_remove() # Remove all frames
self.show_frame(FirstWindow)
self.destroy()
def show_frame(self, cont):
for fme in self.frames: # Remove all frames
self.frames[fme].grid_remove()
frame = self.frames[cont]
frame.grid() # Display frame