简体   繁体   English

窗口标签未打印:Python

[英]window label is not printing : Python

I want to create two windows. 我想创建两个窗口。

Behaviour of windows: Windows的行为:

Window1 has a label and a button . Window1有一个label和一个button When I click on that button , 2nd window has to open. 当我单击该button ,必须打开第二个窗口。 2nd window have a label . 第二个窗口有一个label

Problem: 问题:

Label in 2nd window is not appearing. 第二窗口中的Label未出现。

Code: 码:

def window1():
    root = tkinter.Tk()
    root.geometry("200x200")
    root.title("Window1")
    var = tkinter.StringVar()

    tkinter.Label(root,  textvariable = var, bg = "red").grid(row = 0, column = 0)
    var.set("This is window1")

    tkinter.Button(root, text = "Button1", command = OnBut).grid(row =  0, column = 1)

    root.mainloop()

def OnBut():
    window2()

def window2():
    root = tkinter.Tk()
    root.title("Window2")
    root.geometry("250x250")

    var = tkinter.StringVar()

    tkinter.Label(root,  textvariable = var, bg = "blue").grid(row = 1, column = 0, padx = 3, pady = 3)
    tkinter.Button(root, text = "Button", command = OnBut).grid(row =  0, column = 1, padx  =3, pady = 3)
    var.set("This is window2")       #not appearing <-- problem

    root.mainloop()

window1()

when I call window2 seperately, its working fine. 当我分别调用window2 ,它的工作正常。 Why label not printing in 2nd window, by clicking on button ? 为什么通过单击button不能在第二个窗口中打印label

You don't really need a real function for your command in this case. 在这种情况下,您实际上不需要command的实际功能。 This is what lambda s are made for -- callbacks! 这就是lambda的用途-回调!

Remove your onBut function (which is the problem anyway, since root isn't defined there) and replace your command in each button with: 删除onBut函数(由于没有在其中定义root ,所以仍然是问题),并用以下command替换每个按钮中的command

command = lambda: window2(root)

Currently, when you call onBut , it tries to do: 当前,当您调用onBut ,它会尝试执行以下操作:

window2(root)
# HELP I DON'T KNOW WHAT root IS!!

This throws a NameError on my copy. 这会在我的副本上引发NameError Your code may vary. 您的代码可能会有所不同。

Since you're editing willy nilly, let me just write you some working code. 由于您正在编辑willy nilly,所以让我为您编写一些工作代码。

import tkinter

def run():
    root = tkinter.Tk()
    root.title("Window1")
    s_var = tkinter.StringVar()
    tkinter.Label(root, textvariable = s_var).pack()
    tkinter.Button(root, text = "Button", command = lambda: makewindow(root)).pack()
    s_var.set("Window #1")

def makewindow(root):
    top = tkinter.Toplevel(root)
    top.title("Window2")
    s_var = tkinter.StringVar()
    tkinter.Label(top, textvariable = s_var).pack()
    tkinter.Button(top, text = "Button", command = lambda: makewindow(root)).pack()
    s_var.set("Window #2")

if __name__ == "__main__":
    run()

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

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