Python - Variable in function not defined

寵の児 提交于 2019-12-02 04:33:38

The error occurs when I reach destroy_window1(), where i get the following message: "NameError: name 'e1' is not defined". How can I solve this problem?

The problem is that the destroy_window1() function doesn't know about the e1 variable, because e1 is defined within the window1() function (and its not global).

A simple fix is to put all the e variables into a list and pass that list as an argument to the destroy_window1() function. Make the list with a simple for loop, this not only solves your problem, but it also makes your code cleaner, easier to read, and easier to change it's functionality in future.

Like so:

def destroy_window1(e_list):
    global Guess
    Guess = []

    for e_item in e_list:
        Guess.append(e_item.get())

    master1.destroy()
    window2()

def window1():

    master1 = Tk()
    master1.title('Lottery')
    Label(master1, text="Guess numbers:").grid(row=0)

    e_list = []

    for i in range(7):
        temp_e = e1 = Entry(master1, width=2)
        temp_e.grid(row=0, column=i, padx=5)
        e_list.append(temp_e)

    master1.grid_columnconfigure(6, minsize=20) # Creates an empty column (nr. 6) with width 20

    Button(master1, text='OK', command=lambda :destroy_window1(e_list)).grid(row=3, column=3, sticky=W, pady=5)

    master1.mainloop()

Part of this solution involves a lambda function. This is because (as you may have noticed) the command option normally can't take arguments for the functions. The use of a lambda functions makes this possible. (Read up on Lambda Functions Here)

SidTheSwimmer

When you set e1=1 you are setting the variable e1 to 1 but the .get() function doesn't apply to an integer because the function has not been defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!