当我单击标签打开外部窗口(第三级.py(时,该窗口会正常打开,但内部为空。我没有收到错误,但我没有看到Tkinter小部件和杂项。
这是辅助窗口,其中有我单击以打开外部窗口的标签。我补充说,仅用于信息目的,此窗口被称为次要,因为它显示在主窗口称为home = tk.Tk()
的框架中(左侧有垂直菜单(。辅助窗口打开并在框架中正确显示。
在辅助窗口中有一个标签,我想打开一个名为三级的外部窗口(不在框架中(
我该如何解决?
次要.py
import tkinter as tk
from tkinter import *
from tkinter import ttk
import other_options
from other_options import form_other_options
class Page2(tk.Frame):
def __init__(self, master, **kw):
super().__init__(master, **kw)
self.configure(bg='white')
bar1=Frame(self, width=2200, height=35, background="#960000", highlightbackground="#b40909", highlightthickness=0) #grigio chiaro #b40909
bar1.place(x=0, y=0)
other_options = Label(self, text="Other Options", bg="#960000", foreground='white', font='Ubuntu 10')
other_options.place(x=1025, y=7)
other_options.bind("<Button-1>", lambda event: other_options.form_other_options(self))
三级.py
from tkinter import *
from tkinter import ttk
import tkinter as tk
def form_other_options(parent):
other_options = tk.Toplevel(parent)
other_options.title("Other options")
other_options.geometry("1000x800")
other_options.config(bg="white")
other_options.state("normal")
other_options.transient(parent)
class checkbox():
def __init__(self, master, **kw):
super().__init__(master, **kw)
labelframe1 = LabelFrame(self, text="checkbox", width=600,height=190, bg="white", foreground='#e10a0a')
labelframe1.place(x=10, y=13)
Checkbutton1 = IntVar()
Button1 = Checkbutton(self, text = "option1",
variable = Checkbutton1,
onvalue = 1,
offvalue = 0,
height = 2,
width = 10)
Button1.pack()
other_options.mainloop()
窗口为空的第一个原因是您从未创建类checkbox
的实例,因此创建小部件的代码从未运行。
因此,第一步是确保创建该类的实例:
other_options = tk.Toplevel(parent)
...
cb = checkbox(other_options)
当你这样做的时候,你会发现代码中的其他错误。创建tkinter小部件时的第一个位置参数必须是另一个小部件。如果希望小部件位于Toplevel
内部,则父级需要是顶层或子级。您使用的self
根本不是一个小部件。
一个简单的修复方法是使用master
而不是self
,因为您将顶层窗口作为master
参数传递:
labelframe1 = LabelFrame(master, ...)
Button1 = Checkbutton(master, ...)
您还需要删除对other_options.mainloop()
的调用。除非有非常令人信服的理由,否则整个应用程序应该只调用mainloop()
一次。
严格来说,代码中还有其他问题与所问问题无关。例如,您要导入tkinter两次:一次作为import tkinter as tk
,一次作为from tkinter import *
。您只需要导入一次tkinter,PEP8建议使用第一种形式:
import tkinter as tk
您需要在调用tkinter函数的每个位置添加前缀tk.
。这将有助于使您的代码更易于理解,并有助于防止全局名称空间的污染。
您还应该使用PEP8命名标准。具体来说,类名应该以大写字符开头。这也将使您的代码更易于理解。
checkbox
类也没有缩进的理由。你应该把它移出函数。
此外,checkbox
不从任何东西继承,然后创建LabelFrame
,而应该只从LabelFrame
继承。这样,您就可以像使用真正的小部件一样使用类,并且在创建其他小部件时可以使用self
而不是master
。
class Checkbox(tk.LabelFrame):
def __init__(self, master, **kw):
super().__init__(master, **kw)
...
button1 = tk.Checkbutton(self, ...)
...
可能还有其他问题,但这些问题是最明显的。