首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我正在为我正在做的项目编辑toplevel窗口。

我正在为我正在做的项目编辑toplevel窗口。
EN

Stack Overflow用户
提问于 2022-10-30 01:00:46
回答 1查看 33关注 0票数 -2

我们应该设置一个登录屏幕,我的问题是我不熟悉顶级窗口,也不知道如何在上面添加标签和按钮。

这是我正在使用的代码

代码语言:javascript
复制
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,但是它没有工作。

EN

回答 1

Stack Overflow用户

发布于 2022-10-30 19:20:29

您需要将LabelButton分配给在change_text中创建的新Toplevel。小部件创建函数中的第一个参数是父小部件。下面的change_text方法被修改为打开一个新的Toplevel窗口,并将标签和按钮添加到其中。

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74249873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档