为了账号安全,请及时绑定邮箱和手机立即绑定

Python:未定义名称“entry1”

Python:未定义名称“entry1”

幕布斯7119047 2021-11-09 11:04:21
我写了一个代码,它将窗口的背景颜色保存在文件中,关闭并再次运行程序后,它会记住窗口颜色(它保存在名为“data.txt”的文件中)。# import modulesfrom tkinter import*  from tkinter import messagebox as mbimport os.path# create a window w=Tk()w.title('My Application')w.resizable(0,0)w.geometry('300x300')# Read filesif 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 filefilelen=len(file.read())print(len(file.read()))             #length of the filefile.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 filedef 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我怎样才能让它工作?
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

该entry1对象是该show_settings()方法的本地对象,因此它在内部不可见settings_save()


将对象移动到类中,它将可见


# import modules


from tkinter import*  

from tkinter import messagebox as mb

import 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()


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信