如何存储用户下次打开程序时使用的背景色


root = Tk()
root['bg'] = '#800080'
def choose_color():
color_code = colorchooser.askcolor(title ="Choose color")
root1['bg']= color_code[1]
button = Button(root, text = "Select Back ground color",
command = choose_color).place(x=400,y=300)
root.mainloop()

代码以紫色背景开始,假设用户将其更改为红色并决定关闭程序,我如何在下次打开程序时存储红色?

@Reti43是绝对正确的。您需要将设置保存到一个文件中。我把一些代码放在一起,以防你更像一个视觉人。对于本例,您需要在与python脚本相同的文件夹中创建一个名为config.txt的文件。

from tkinter import Tk, Button, colorchooser
import os

root = Tk()
# if config.txt exist open up the config file
if os.path.isfile('config.txt'):
with open('config.txt','r') as f:
# if the config.txt is empty set to default purple
if os.stat('config.txt').st_size == 0:
root['bg'] = '#800080'
#otherwise grab the last color setting. Set root['bg'] to that value
else:
root['bg'] = f.read()

def choose_color():
color_code = colorchooser.askcolor(title ="Choose color")
root['bg'] = str(color_code[1])

# save the color value to config.txt every time color is switched with the button
with open('config.txt','w') as f:
f.write( color_code[1])

button = Button(root, text = "Select Back ground color",
command = choose_color).place(x=400,y=300)
root.mainloop()

最新更新