【问题标题】:How do I open a new window in TKinter, then add buttons to it?如何在 TKinter 中打开一个新窗口,然后向其中添加按钮?
【发布时间】:2020-11-27 23:56:53
【问题描述】:

我正在尝试在 Tkinter 中打开一个新窗口,然后向其中添加按钮。 新窗口打开没有问题,但是当我尝试向其添加按钮时出现 AttributeError。

这是我当前的代码:

from tkinter import *
from tkinter.ttk import *
import datetime
import time
import random 
import json 

class MainWindow(Toplevel):
    def __init__(self, master = None):
        super().__init__(master = master)
        self.title("Jarvis")
        self.geometry("500x500")
        label = Label(self, text="Please choose one of the options below")
        label.pack()

        numberGenButton = Button(MainWindow, text="Number Generator")
        numberGenButton.pack()

        timeWindowButton = Button(MainWindow, text="Clock")
        timeWindowButton.pack()

        passwordGeneratorButton = Button(MainWindow, text="Generate a password")
        passwordGeneratorButton.pack()

master = Tk()
master.geometry("500x500")

welcome = Label(text="Welcome to Jarvis")
welcome.pack()

Label(text="Please note closing this window will close Jarvis!").pack()

getStarted = Button(master, text="Get Started")
getStarted.bind("<Button>", lambda e: MainWindow(master))
getStarted.pack()

master.mainloop()

错误:

  File "c:\Program Files\Python38\lib\tkinter\ttk.py", line 612, in __init__
    Widget.__init__(self, master, "ttk::button", kw)
  File "c:\Program Files\Python38\lib\tkinter\ttk.py", line 557, in __init__
    tkinter.Widget.__init__(self, master, widgetname, kw=kw)
  File "c:\Program Files\Python38\lib\tkinter\__init__.py", line 2561, in __init__
    BaseWidget._setup(self, master, cnf)
  File "c:\Program Files\Python38\lib\tkinter\__init__.py", line 2530, in _setup
    self.tk = master.tk
AttributeError: type object 'MainWindow' has no attribute 'tk'

这里的任何帮助都会很棒!

【问题讨论】:

  • edit您的问题包含错误。
  • @BryanOakley 已编辑!对不起那个伙伴

标签: python tkinter


【解决方案1】:

您不能像您在这里所做的那样,将一个类作为另一个窗口的主窗口传递:

numberGenButton = Button(MainWindow, text="Number Generator")
timeWindowButton = Button(MainWindow, text="Clock")
passwordGeneratorButton = Button(MainWindow, text="Generate a password")

除了根小部件,每个小部件都需要一些其他小部件作为其主人。您需要使用 instance,在本例中为 self:

numberGenButton = Button(self, text="Number Generator")
timeWindowButton = Button(self, text="Clock")
passwordGeneratorButton = Button(self, text="Generate a password")

【讨论】:

    【解决方案2】:

    我不明白的是您使用master.mainloop() 只需mainloop 就足够了,创建一个新窗口就这样做

    root = Tk()
    window = Tk()
    

    如果我误解了这个问题,请纠正我。

    【讨论】:

    • 这样说也没有错
    猜你喜欢
    • 2020-08-30
    • 2017-06-14
    • 2020-09-17
    • 1970-01-01
    • 2023-01-12
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多