1

几周前我开始在 Python 上学习 Tkinter,并想创建一个猜谜游戏。但不幸的是,我遇到了一个问题,使用这段代码,规则的文本(在函数 Rules;text='Here are the rules...中)没有出现在窗口(rule_window)上。


window = Tk()
window.title("Guessing Game")

welcome = Label(window,text="Welcome To The Guessing Game!",background="black",foreground="white")
welcome.grid(row=0,column=0,columnspan=3)

def Rules():
   rule_window = Tk()
   rule_window = rule_window.title("The Rules")
   the_rules = Label(rule_window, text='Here are the rules...', foreground="black")
   the_rules.grid(row=0,column=0,columnspan=3)
   rule_window.mainloop()

rules = Button(window,text="Rules",command=Rules)
rules.grid(row=1,column=0,columnspan=1)

window.mainloop() 

有谁知道如何解决这个问题?

4

2 回答 2

2

在您的代码中,您将任何rule_window内容重置为字符串(在这一行中rule_window = rule_window.title(...):)

试试这个:

from import tkinter *

window = Tk()
window.title("Guessing Game")

welcome = Label(window, text="Welcome To The Guessing Game!", background="black", foreground="white")
welcome.grid(row=0, column=0, columnspan=3)

def Rules():
   rule_window = Toplevel(window)
   rule_window.title("The Rules")
   the_rules = Label(rule_window, text="Here are the rules...", foreground="black")
   the_rules.grid(row=0, column=0, columnspan=3)

rules = Button(window, text="Rules", command=Rules)
rules.grid(row=1, column=0, columnspan=1)

window.mainloop()

当您想要同时拥有 2 个响应式窗口时,您可以使用tkinter.Toplevel().

于 2021-04-08T14:58:16.080 回答
0

在您的代码中,您已经初始化了 Tkinter 框架的新实例,因此您可以创建一个顶级窗口来代替。TopLevel Window 的作用通常是在应用程序中创建一个弹出窗口之类的东西。您还可以触发 Tkinter 按钮来打开新窗口。

from tkinter import *
from tkinter import ttk

#Create an instance of tkinter window
root= Tk()
root.geometry("600x450")

#Define a function
def open_new():
    #Create a TopLevel window
    new_win= Toplevel(root)
    new_win.title("My New Window")

    #Set the geometry
    new_win.geometry("600x250")
    Label(new_win, text="Hello There!",font=('Georgia 15 bold')).pack(pady=30)

#Create a Button in main Window
btn= ttk.Button(root, text="New Window",command=open_new)
btn.pack()

root.mainloop()

于 2021-04-09T09:48:29.470 回答