我正在尝试创建一个具有多个屏幕的程序。我有它的工作,如果我点击主屏幕中的按钮,它确实切换屏幕,但一旦在屏幕上,我试图点击其他按钮回到主屏幕,它不工作。我该如何解决这个问题,让它回到主屏幕?
import tkinter as tk
from tkinter import ttk
from tkinter import font
from tkinter import messagebox
win = tk.Tk()
# Screen
screen = tk.Tk()
screen.title('Main Menu')
screen.geometry('600x400')
# Font
style1 = font.Font(size=25)
style2 = font.Font(size=20)
## Direction Screen || Text, Back Button (Returns to main Screen)
class how_to_play(tk.Toplevel):
def __init__(self):
super().__init__()
win.title('How To Play')
win.geometry('600x400')
ttk.Label(self, text = 'Game Insturctions').pack()
ttk.Label(self, text = 'another label').pack()
ttk.Button(self, text = 'Exit', command = main_menu).pack()
# Game Screen || Hang Man, Letter/Word Input, Trys left, Incorrt Answers, Back Button (Returns to Main Screen)
def game():
game = tk.Toplevel()
game.title('Hang Man')
game.geometry('600x400')
ttk.Label(game, text = 'Hang Man').pack()
ttk.Button(game, text = 'Exit', command = main_menu).pack()
ttk.Label(game, text = 'another label').pack(expand = True)
# Main Menu Screen
def main_menu():
menu = tk.Toplevel()
menu.title('Main Menu')
menu.geometry('600x400')
ttk.Label(screen, text = 'Main Menu').pack()
button1 = ttk.Button(screen, text = 'How To Play', command = how_to_play)
button1.pack(expand = True)
button2 = ttk.Button(screen, text = 'Play', command = game)
button2.pack(expand = True)
# run
main_menu()
screen.mainloop()
1条答案
按热度按时间5lhxktic1#
你对所有的
Toplevel
有点困惑。你真的想要单独的Windows吗?如果是这样,那么按照与
how_to_play
相同的方式为game
创建一个类。这样你就可以从主窗口(主菜单)的按钮示例化两者。简单地返回destroy()
顶层,只保留主窗口:多窗口解决方案:
单一窗口解决方案:
但如果你实际上只想改变内容,而不想打开多个窗口,你必须创建单独的框架和
pack()
和pack_forget()
,这取决于你想要显示的内容: