Welcome folks today in this post we will be generating a random color
in hexadecimal code and change background color
using random library in python. All the full source code of the application is shown below.
Get Started
In order to get started we need to install the following library using the pip
command as shown below
pip install random
After installing the library make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
''' This is the source code for making GUI in Python assignment ''' # Import libraries from tkinter import * import random # Initialize Tkinter w = Tk() w.title('Color') w.geometry('300x200') w['bg'] = '#ffffff' # Variable label_text = StringVar() color_entry = StringVar() # Functions to apply color def apply_color(): color = color_entry.get() w['bg'] = '#{}'.format(color) # Function to random color generator def generate_color(): # randomize the hex code r = lambda: random.randint(0,255) color_entry.set('%02X%02X%02X' % (r(),r(),r())) # Apply color apply_color() # Label label = Label( w, textvariable=label_text, anchor=CENTER ) label_text.set('Enter color hex code') label.pack() # Entry Widget entry = Entry( w, textvariable=color_entry, width=20 ) entry.insert(0, 'ffffff') entry.pack() # Apply color button button = Button( w, text='Apply', width=15, command=apply_color ) button.pack() # Random color generator button # Button button = Button( w, text='Random', width=15, command=generate_color ) button.pack() w.columnconfigure(0, weight=1) w.rowconfigure(0, weight=1) # Run the program infinitely w.mainloop() |
Now execute the above python script by typing the below command as shown below
python app.py
And now you can see that we are generating the random
hex code and we have changed the background color inside the desktop app