Python/Tkinter是否将按钮状态写入文件,以便在下次启动时自动重新应用?

2024-04-25 12:30:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将按钮前景色的状态(用户点击后改变)保存到一个.txt文件中,以便在下次运行时自动重新应用前景色。这是我的密码。。。toggle_color可以完美地工作,它还可以将颜色状态写入.txt文件。但是,它不会在启动时自动更改颜色。意思是,我可能把最后一部分搞砸了。我做错了什么

编辑:忘记调用.read()。但是toggle_color(colors = ['white', '#0055C4'])并不是改变先前定义的公认方式。那么,我该如何更改toggle_color的colors变量呢

 def toggle_color(last=[0]): #this is what toggles the fg color of the button
        colors = ['#0055C4', 'white']
        color = colors[last[0]]
        last[0] = (last[0] + 1) % 2
        savepass.config(fg=color)
        with open('loaderstate.txt', 'w') as loader_file:
            loader_file.write(savepass.cget('fg'))


savepasspic = PhotoImage(file="RememberMeBackground.png")
savepass=Button(root, font=('Arial Black',10),image=savepasspic, text="    remember me", compound=CENTER, command=toggle_color, activeforeground="#0055C4", activebackground="#303030", relief=GROOVE)
savepass.config(borderwidth=0, highlightthickness=0, width=120, height=18, fg='white', bg="grey")
savepass.place(x=105, y=287)

def blueoverall(): #changes the fg color of the button, and reverses toggle_color order
savepass.config(fg='#0055C4')
toggle_color(colors = ['white', '#0055C4'])

with open('loaderstate.txt', 'r') as loader_file: #should run automatically on startup and determine color of button fg
    if loader_file.read == '#0055C4':
        blueoverall()
    if loader_file.read == 'white':
        savepass.config(fg='white')

Tags: ofthetxtconfigreadbuttonloaderfile
1条回答
网友
1楼 · 发布于 2024-04-25 12:30:01

.read是一种方法。你应该叫它

另外,read有可能返回一个在末尾有换行符的值,这意味着您应该strip()返回值与颜色值进行比较

if loader_file.read().strip() == '#0055C4':
                   ^^

相关问题 更多 >