![](/img/trans.png)
[英]How do i open a new window on the click of a button with tkinter?
[英]How do I open a new window in TKinter, then add buttons to it?
我正在尝试在 Tkinter 中打开一个新的 window,然后向其添加按钮。 新的 window 打开没有问题,但是当我尝试向其添加按钮时出现 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'
这里的任何帮助都会很棒!
您不能将 class 作为另一个 window 的主设备,就像您在这里所做的那样:
numberGenButton = Button(MainWindow, text="Number Generator")
timeWindowButton = Button(MainWindow, text="Clock")
passwordGeneratorButton = Button(MainWindow, text="Generate a password")
除了根小部件之外,每个小部件都需要一些其他小部件作为其主人。 您需要使用实例,在这种情况下是self
:
numberGenButton = Button(self, text="Number Generator")
timeWindowButton = Button(self, text="Clock")
passwordGeneratorButton = Button(self, text="Generate a password")
我不明白的是你使用master.mainloop()
只需mainloop
就足够了,要创建一个新的 window 就这样做
root = Tk()
window = Tk()
如果我误解了这个问题,请纠正我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.