简体   繁体   English

其他功能无法识别 Tkinter GUI 窗口

[英]Tkinter GUI window not recognised in other functions

I am making a simple program that saves someone's name and their email address in a file.我正在制作一个简单的程序,将某人的姓名和他们的电子邮件地址保存在一个文件中。 I am coding in python idle.我在 python idle 中编码。 My code is:我的代码是:

import random
from tkinter import *

num = (random.randint(1,3))
NOSa = open("CN.txt", "r")
NOS = (NOSa.read())
NOSa.close()
NOSa = open("CN.txt", "w")
if num == ("1"):
    NOS = NOS + "a"
elif num == ("2"):
    NOS = NOS + "v"
else:
    NOS = NOS + "x"
NOSa.write(NOS)
NOSa.close()

def efg():
        window2.destroy()
        window2.mainloop()
        exit()

def abc():
    name = entry.get()
    email = entry2.get()
    window.destroy()
    window2 = Tk()
    window2.title("OP")
    OT = Text(window2, width=30, height=10, wrap=WORD, background="yellow")
    OT.grid(row=0, column=0, sticky=W)
    OT.delete(0.0, END)
    MT = "We have logged your details " + name
    MT2 = ". We have a file saved called " + NOS
    MT3 = ". Go check it out!"
    OT.insert(END, MT)
    OT.insert(END, MT2)
    OT.insert(END, MT3)
    new_file = open(NOS, "a")
    new_file.write("This is ")
    new_file.write(name)
    new_file.write(" email address.")
    new_file.write(" ")
    new_file.write(email)
    button2 = Button(window2, text="OK", width=5, command=efg)
    button2.grid(row=1, column=0, sticky=W)
    window.mainloop()
    window2.mainloop()

window = Tk()
window.title("EN")
label = Label(window, text="Enter your name: ")
label.grid(row=0, column=0, sticky=W)
entry = Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)
label2 = Label(window, text="Enter your email address: ")
label2.grid(row=2, column=0, sticky=W)
entry2 = Entry(window, width=25, bg="light green")
entry2.grid(row=3, column=0, sticky=W)
button = Button(window, text="SUBMIT", width=5, command=abc)
button.grid(row=4, column=0, sticky=W)
window.mainloop()

When I run the code my first 2 boxes appear and run their code perfectly.当我运行代码时,我的前两个框出现并完美地运行它们的代码。 However, when I click the button 'OK' I get this error: NameError: name 'window2' is not defined但是,当我单击“确定”按钮时,出现此错误:NameError: name 'window2' is not defined

I use python-idle.我使用 python 空闲。

You may make windows2 global您可以将windows2全局

window2 = None

def efg():
        global window2

and later然后

def abc():
    global window2

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

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