Tkinter - 如何在通过函数创建的新窗口中创建按钮?Python 3

0 投票
1 回答
1418 浏览
提问于 2025-04-30 17:57
from tkinter import *

def begin():
    root = Tk()
    root.title("main window")
    root.geometry("1920x1080")  
    return #How would a button be placed in this window made by this function?

root = Tk()
root.title("Start up page")
root.geometry("1920x1080")


BeginButton = Button(app, text = "Begin", command=begin, bg="green")
BeginButton.grid(column = 2, row = 2, sticky = W)
BeginButton.config(height = 10, width = 30 )

root.mainloop()

如果我想在新窗口里创建新的按钮,而这个新窗口是通过一个叫做“begin”的函数来生成的,我该怎么做呢?

任何回复都非常感谢!

暂无标签

1 个回答

0

我觉得你想做的是修改根窗口,而不是创建一个新的窗口。下面是一个简单的示例:

from tkinter import *

root = Tk()

class App:
    def __init__(self):
        root.title("Start up page")
        root.geometry("1920x1080")
        self.beginB = Button(root, text="Begin", command=self.begin,
                        bg="green", height=10, width=30)
        self.beginB.grid(sticky = W)
    def begin(self):
        root.title("main window")
        self.beginB.destroy()
        del self.beginB
        self.goB = Button(root, text='Go on', command=self.go_on,
                                bg='red')
        self.goB.grid(sticky=E)
    def go_on(self):
        self.label = Label(root, text="you have continued")
        self.label.grid(row=1, sticky=S)

App()
root.mainloop()

定义一个类的好处是你可以提前引用它。在你的代码中,你必须在创建开始按钮之前定义开始函数。而使用类的话,我可以把它放在init之后,这样对我来说更符合自然的顺序。通常情况下,初始化代码会调用或绑定多个函数。

撰写回答