简体   繁体   English

Tkinter GUI顶层

[英]Tkinter GUI toplevel

from tkinter import*
import tkinter as tk

def topLevel():
    top=Toplevel()
    top.title("Listbox test")
    notiLabel = Label(text ="----test----", font=('Times', 20))
    notiLabel.pack()
    notiLabel.grid(row=0,column=0, sticky=W)

    noti = Label(text ="----test----", font=('Times', 18))
    noti.pack()
    noti.grid(row=1,column=1, sticky=W)

    f = Label(text ="------test-----")
    f.pack()
    f.grid(row=3,column=0, sticky=W)
    fa = Label()
    fa.pack()
    fa.grid(row=3,column=1, sticky=W)


root=tk.Tk()
root.title("Listbox test")

s = tk.Label(text =">>>test<<<", font=(('Times'),20))
s.pack()
s.grid(row=2,column=0)


N = tk.Label(text =">>>test<<<")
N.pack()
N.grid(row=3,column=0)


LB = tk.Listbox(width=50, selectmode =SINGLE)
LB.pack()
LB.grid(row=4, column=0)


TI = tk.Button(text="b1", width =50, command=topLevel)
TI.pack()
TI.grid(row=5, column=0)

root.mainloop()

When the program runs, after click the command button b1, the information and label in toplevel window still print on the lower level window, how to fix this? 程序运行时,单击命令按钮b1后,顶层窗口中的信息和标签仍显示在较低层窗口中,如何解决?

You have to specify on which frame (the Toplevel() ) to add the new widgets: 您必须指定要在哪个框架上( Toplevel() )添加新的小部件:

from Tkinter import *

def topLevel():
    top=Toplevel()
    top.title("Listbox test")
    notiLabel = Label(top, text ="----test----", font=('Times', 20))
    notiLabel.grid(row=0,column=0, sticky=W)

    noti = Label(top, text ="----test----", font=('Times', 18))
    noti.grid(row=1,column=1, sticky=W)

    f = Label(top, text ="------test-----") # note the 'top' parameter
    # 'top' was your Toplevel widget
    f.grid(row=3,column=0, sticky=W)
    fa = Label(top)
    fa.grid(row=3,column=1, sticky=W)


root=Tk()
root.title("Listbox test")

s = Label(text =">>>test<<<", font=(('Times'),20))
s.grid(row=2,column=0)


N = Label(text =">>>test<<<")
N.grid(row=3,column=0)


LB = Listbox(width=50, selectmode =SINGLE)
LB.grid(row=4, column=0)


TI = Button(text="b1", width =50, command=topLevel)
TI.grid(row=5, column=0)

root.mainloop()

I also got rid of the usage of both .pack() and .grid() , and stuck to only .grid() . 我也摆脱了.pack().grid() ,只使用.grid()

Here is how I solved it, using this reference : 这是我使用此参考资料解决的方法:

top=Toplevel()
notiLabel = Label(top, text ="----test----", font=('Times', 20))

Instead of: 代替:

top=Toplevel()
notiLabel = Label(text ="----test----", font=('Times', 20))

I had to declare "top" in the widget and declare root in root widget. 我必须在小部件中声明“ top”,并在根小部件中声明root。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM