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

The code starts with a purple background, let's say that the user changes it into red and decides to close the program, how can I store the color red for next time that the program is opened?

1 Answers1

0

@Reti43 is absolutely right. You will need to save your settings to a file. I put some code together in case you are more of a visual person. For this example, to work you will need to create a file called config.txt in the same folder as your python script.

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()
B-L
  • 144
  • 1
  • 8