Python:未定义名称“entry1”

我写了一个代码,它将窗口的背景颜色保存在文件中,关闭并再次运行程序后,它会记住窗口颜色(它保存在名为“data.txt”的文件中)。


# import modules


from tkinter import*  

from tkinter import messagebox as mb

import os.path


# create a window 

w=Tk()

w.title('My Application')

w.resizable(0,0)

w.geometry('300x300')



# Read files


if not(os.path.exists('data.txt')):       #check is the file exists

    print('file does not exists')

    file = open("data.txt",'w')

    file.close()


file = open("data.txt",'r')  #open a file



filelen=len(file.read())

print(len(file.read()))             #length of the file

file.close()



file = open("data.txt",'a')


print('file length is', filelen)

if filelen==0:               #if the file if empty, write default values

    file.write('0 \n0 \n0')            

    print('written to file')

file.close()


file = open("data.txt", 'r')



a=(file.readlines())



e1=float(a[0].replace(' \n',' '))

e2=float(a[1].replace(' \n',' '))    # remove '\n'

e3=float(a[2].replace(' \n',' '))




def _from_rgb(rgb):

    """translates an rgb tuple of int to a tkinter friendly color code

    """

    return "#%02x%02x%02x" % rgb   



file.close()


w.configure(background=_from_rgb((int(e1), int(e2), int(e3))))   #change the bg color to values from the file



def show_settings():


    settings=Tk()

    settings.geometry('400x200')


    entry1=Entry(settings)

    entry2=Entry(settings)

    entry3=Entry(settings)


    entry1.grid(row=1, column=1)

    entry2.grid(row=2, column=1)

    entry3.grid(row=3, column=1)


    changeInfo1=Label(settings,text='Red:',padx=20).grid(row=1, column=0)

    changeInfo2=Label(settings,text='Green:',padx=20).grid(row=2, column=0)

    changeInfo3=Label(settings,text='Blue',padx=20).grid(row=3, column=0)


当我运行它时,它可以工作,但是当我单击“保存!”时 设置窗口中的按钮它说:


 File "C:/Users *filepath*", line 89, in settings_save

        file.write('\n' + str(entry1.get()) + ' \n' + str(entry2.get()) + '\n' + str(entry3.get()))

    NameError: name 'entry1' is not defined

我怎样才能让它工作?



幕布斯7119047
浏览 184回答 1
1回答

慕姐4208626

该entry1对象是该show_settings()方法的本地对象,因此它在内部不可见settings_save()将对象移动到类中,它将可见# import modulesfrom tkinter import*  from tkinter import messagebox as mbimport os.path...entry1 = None;entry2 = None;entry3 = None;...def show_settings():    settings=Tk()    settings.geometry('400x200')    entry1=Entry(settings)    entry2=Entry(settings)    entry3=Entry(settings)   ...    save=Button(settings,text='SAVE!',command=settings_save)    save.grid(row=6, column=0, columnspan=2)def settings_save():                     #save values to a file    file = open("data.txt",'a')    file.write('\n' + str(entry1.get()) + ' \n' + str(entry2.get()) + '\n' + str(entry3.get()))    file.close()...w.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python