A tutorial on generating a random background color in tkinter
Python:
''' First we import the needed modules for our script '''
import tkinter as tk
from random import choices
''' Initiate tkinter and start its mainloop '''
root = tk.Tk()
'''
It's usually best not to give a fixed but, for this tutorial we will.
We will set our window size with the geometry method.
We will set the width to 400 and height to 300.
The +350+350 will get the window out of the top left corner of the screen.
We will give our root window a title "Random hex color"
'''
root.geometry('400x300+350+350')
root.title('Random Hex Color')
def color():
'''
First we will use list comprehension to get the needed characters
Second from the random module we will use choice to get six random
characters for our hex color
We will set a variable called bgcolor and attach a joined list
to get the hex color
We then assign the string to tkinters label background variable
We will assign the hex string to tkinters labelframe text variable
And last we will call the root window with the after method and set
the time argument to 3000. (Every 1000 millisecond equals 1 second)
We then call the function itself.
'''
characters = [char for char in '0123456789abcdef']
sample = choices(characters, k=6)
bgcolor = f'#{"".join(sample)}'
label['bg'] = bgcolor
labelframe['text'] = f'Random hex color: {bgcolor}'
root.after(3000, color)
'''
We create a labelframe to hold our label and display the random
hex string.
Next we create our label that will display the random background color.
Finally we call the root windows after method to get our function call started.
'''
labelframe = tk.LabelFrame(root, text='Random hex color: #cecece', font=(None, 16, 'bold'))
labelframe['bg'] = '#555555'
labelframe['fg'] = '#eeeeee'
labelframe.pack(expand=True, fill='both')
label = tk.Label(labelframe, bg='#cecece')
label.pack(expand=True, fill='both')
root.after(3000, color)
root.mainloop()