条目空返回(Python)

时间:2019-02-15 10:39:29

标签: python tkinter tkinter-entry

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

# 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',' '))


entry1=Entry()
entry2=Entry()
entry3=Entry()

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)

    entry1.insert(1,e1)
    entry2.insert(1,e2)
    entry3.insert(1,e3)

    print(entry1.get())

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


button=Button(w,text='Settings', command=show_settings).pack()
w.mainloop()

当我运行它时,它可以工作,但是当我单击“保存!”时,在设置窗口中单击按钮,文件内容不会更改。您能请问eplain,我该如何解决?

1 个答案:

答案 0 :(得分:0)

答案是使用

将条目设置为全局
 global entry1
相关问题