在 Tkinter 中打包和解包框架时遇到问题

Having trouble with packing and unpacking frames in Tkinter

我正在 Python 中编写一个相当简单的程序,但它使用 Tkinter,我在使用 pack()pack_forget() 时遇到了一些问题。我在 Python 3.4。本质上,我目前有一个简单的程序,只有三个按钮:播放、说明和设置。没问题。播放按钮命令仅在具有三个按钮的 Frame(main) 上执行 pack_forget()

因此,每个播放按钮我需要三个单独的 play() 命令,因为每个命令在不同的帧上调用 pack_forget()。有没有一种方法可以在当前打包的任何帧上执行 pack_forget(),这样我就可以只调用一个 play() 函数来调用所有三个播放按钮?

(这是代码的样子,当然是经过简化的):

def play_1():
    title.pack_forget()
    game.pack()

def play_2():
    instructions.pack_forget()
    game.pack()

def play_3():
    settings.pack_forget()
    game.pack()

from tkinter import *
main = Tk()

title = Frame(main).pack()
instructions = Frame(main)
settings = Frame(main)

play_button1 = Button(title, text="Play", command=play_1)
play_button2 = Button(instructions, text="Play", command=play_2)
play_button3 = Button(settings, text="Play", command=play_3)

我只是在寻找一种解决方案,可以将 play_1()play_2()play_3() 组合成一个函数。

使用变量 currentFrame 和当你写的例子

instructions.pack()

添加

currentFrame = instructions

那么你可以使用这个功能:

def play():
    currentFrame.pack_forget()
    game.pack()