Dan*_*Dan 54 python tkinter titlebar
我正在尝试向窗口添加自定义标题,但我遇到了麻烦.我知道我的代码不对,但是当我运行它时,它会创建2个窗口,一个只有标题tk,另一个更大的窗口有"Simple Prog".如何使tk窗口具有标题"Simple Prog"而不是具有新的附加窗口.我不认为我想要有Tk()部分,因为当我在我的完整代码中有这个时,会出现错误
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")
Run Code Online (Sandbox Code Playgroud)
Bry*_*ley 83
如果您不创建根窗口,当您尝试创建任何其他窗口小部件时,Tkinter将为您创建一个窗口.因此,在你的__init__,因为你初始化框架时还没有创建一个根窗口,Tkinter将为你创建一个.然后,调用make_widgets哪个创建第二个根窗口.这就是你看到两个窗户的原因.
在创建任何其他小部件之前,编写良好的Tkinter程序应始终显式创建根窗口.
修改代码以显式创建根窗口时,最终会得到一个带有预期标题的窗口.
例:
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()
Run Code Online (Sandbox Code Playgroud)
还要注意使用self.make_widgets()而不是ABC.make_widgets(self).虽然两者最终都做同样的事情,但前者是调用函数的正确方法.
小智 28
我不确定我是否正确,但这是你想要的吗?
root = tkinter.Tk()
root.title('My Title')
Run Code Online (Sandbox Code Playgroud)
根是你创建的窗口,其余的是非常自我解释的.
lug*_*098 13
尝试类似的东西:
from tkinter import Tk, Button, Frame, Entry, END
class ABC(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
root = Tk()
app = ABC(master=root)
app.master.title("Simple Prog")
app.mainloop()
root.destroy()
Run Code Online (Sandbox Code Playgroud)
现在您应该有一个带标题的框架,然后您可以根据需要为不同的小部件添加窗口.
必须强调的一点是: .title() 方法必须位于 .mainloop() 之前
例子:
# A simple hello world software
from tkinter import *
# Instantiating/Creating the object
main_menu = Tk()
# Set title
main_menu.title("Hello World")
# Infinite loop
main_menu.mainloop()
Run Code Online (Sandbox Code Playgroud)
否则,可能会出现此错误:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 2217, in wm_title
return self.tk.call('wm', 'title', self._w, string)
_tkinter.TclError: can't invoke "wm" command: application has been destroyed
Run Code Online (Sandbox Code Playgroud)
并且标题不会显示在顶部框架上。
小智 5
这是一个例子:
from tkinter import *;
screen = Tk();
screen.geometry("370x420"); //size of screen
Run Code Online (Sandbox Code Playgroud)
更改窗口名称
screen.title('Title Name')
Run Code Online (Sandbox Code Playgroud)
运行:
screen.mainloop();
Run Code Online (Sandbox Code Playgroud)