在python中使用Tkinter编辑标题栏 [英] Using Tkinter in python to edit the title bar

查看:48
本文介绍了在python中使用Tkinter编辑标题栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向窗口添加自定义标题,但遇到了问题.我知道我的代码不正确,但是当我运行它时,它会创建 2 个窗口,一个只有标题 tk,另一个更大的窗口带有Simple Prog".如何使 tk 窗口具有标题Simple Prog"而不是具有新的附加窗口.我不认为我应该有 Tk() 部分,因为当我在我的完整代码中有它时,就会出现错误

I am trying to add a custom title to a window but I am having troubles with it. I know my code isn't right but when I run it, it creates 2 windows instead, one with just the title tk and another bigger window with "Simple Prog". How do I make it so that the tk window has the title "Simple Prog" instead of having a new additional window. I dont think I'm suppose to have the Tk() part because when i have that in my complete code, there's an error

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self,parent=None):
        Frame.__init__(self,parent)
        self.parent = parent
        self.pack()
        ABC.make_widgets(self)

    def make_widgets(self):
        self.root = Tk()
        self.root.title("Simple Prog")

推荐答案

如果您不创建根窗口,当您尝试创建任何其他小部件时,Tkinter 将为您创建一个.因此,在您的 __init__ 中,由于您在初始化框架时尚未创建根窗口,Tkinter 将为您创建一个.然后,您调用 make_widgets 以创建第二个 根窗口.这就是为什么您会看到两个窗口.

If you don't create a root window, Tkinter will create one for you when you try to create any other widget. Thus, in your __init__, because you haven't yet created a root window when you initialize the frame, Tkinter will create one for you. Then, you call make_widgets which creates a second root window. That is why you are seeing two windows.

编写良好的 Tkinter 程序应始终在创建任何其他小部件之前显式创建根窗口.

A well-written Tkinter program should always explicitly create a root window before creating any other widgets.

当您修改代码以显式创建根窗口时,您最终会得到一个具有预期标题的窗口.

When you modify your code to explicitly create the root window, you'll end up with one window with the expected title.

示例:

from tkinter import Tk, Button, Frame, Entry, END

class ABC(Frame):
    def __init__(self,parent=None):
        Frame.__init__(self,parent)
        self.parent = parent
        self.pack()
        self.make_widgets()

    def make_widgets(self):
        # don't assume that self.parent is a root window.
        # instead, call `winfo_toplevel to get the root window
        self.winfo_toplevel().title("Simple Prog")

        # this adds something to the frame, otherwise the default
        # size of the window will be very small
        label = Entry(self)
        label.pack(side="top", fill="x")

root = Tk()
abc = ABC(root)
root.mainloop()

还要注意使用 self.make_widgets() 而不是 ABC.make_widgets(self).虽然两者最终都做同样的事情,但前者是调用函数的正确方法.

Also note the use of self.make_widgets() rather than ABC.make_widgets(self). While both end up doing the same thing, the former is the proper way to call the function.

这篇关于在python中使用Tkinter编辑标题栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆