我们应该设置一个登录屏幕,我的问题是我不熟悉顶级窗口,也不知道如何在上面添加标签和按钮。
这是我正在使用的代码
import tkinter as tk
from tkinter import ttk
import ttkthemes as th
class App(th.ThemedTk):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.style = ttk.Style(self)
self.config(theme="adapta")
self.hello_label = ttk.Label(self, text="Hello, World!")
self.change_button = ttk.Button(self, text="Click Me", command=self.change_text)
self.window = tk.Label(self,text="New Window")
self.window = tk.Button(self, text="Click Me", command=self.change_text)
self.initialize_widgets()
def initialize_widgets(self):
self.hello_label.pack()
self.change_button.pack()
def change_text(self):
self.hello_label.config(text="I Changed!")
self.window = tk.Toplevel(self)
if __name__ == "__main__":
app = App("Login")
app.mainloop()我认为我可以在init函数下键入标签和命令,但是将它们分配给tk而不是ttk,但是它没有工作。
发布于 2022-10-30 19:20:29
您需要将Label和Button分配给在change_text中创建的新Toplevel。小部件创建函数中的第一个参数是父小部件。下面的change_text方法被修改为打开一个新的Toplevel窗口,并将标签和按钮添加到其中。
import tkinter as tk
from tkinter import ttk
class App( tk.Tk ):
def __init__(self, title: str):
super().__init__()
self.title(title)
self.hello_label = ttk.Label(self, text="Hello, World!")
self.change_button = ttk.Button(self, text="Click Me", command=self.change_text)
# Moved into change_text.
# self.window = tk.Label(self,text="New Window")
# self.window = tk.Button(self, text="Click Me", command=self.change_text)
self.initialize_widgets()
def initialize_widgets(self):
self.hello_label.pack()
self.change_button.pack()
def change_text_tl( self ):
self.tl_label.config( text = 'Now I changed too!')
def change_text(self):
self.hello_label.config(text="I Changed!")
self.window = tk.Toplevel(self)
# parent kwargs ->
self.tl_label = tk.Label( self.window, text="New Window")
self.tl_button = tk.Button( self.window, text="Click Me",
command=self.change_text_tl)
self.tl_label.pack()
self.tl_button.pack()
if __name__ == "__main__":
app = App("Login")
app.mainloop()https://stackoverflow.com/questions/74249873
复制相似问题