1+ import tkinter
2+ from PIL import Image , ImageTk
3+ import random
4+
5+ # toplevel widget which represents the main window of an application
6+ root = tkinter .Tk ()
7+ root .geometry ('400x400' )
8+ root .title ('Roll the Dice By Soumyajit' )
9+
10+ # Adding label into the frame
11+ l0 = tkinter .Label (root , text = "" )
12+ l0 .pack ()
13+
14+ # adding label with different font and formatting
15+ l1 = tkinter .Label (root , text = "Hello from Soumyajit!" , fg = "light green" ,
16+ bg = "dark green" ,
17+ font = "Helvetica 16 bold italic" )
18+ l1 .pack ()
19+
20+ # images
21+ dice = ['die1.png' , 'die2.png' , 'die3.png' , 'die4.png' , 'die5.png' , 'die6.png' ]
22+ # simulating the dice with random numbers between 0 to 6 and generating image
23+ image1 = ImageTk .PhotoImage (Image .open (random .choice (dice )))
24+
25+ # construct a label widget for image
26+ label1 = tkinter .Label (root , image = image1 )
27+ label1 .image = image1
28+
29+ # packing a widget in the parent widget
30+ label1 .pack ( expand = True )
31+
32+ # function activated by button
33+ def rolling_dice ():
34+ image1 = ImageTk .PhotoImage (Image .open (random .choice (dice )))
35+ # update image
36+ label1 .configure (image = image1 )
37+ # keep a reference
38+ label1 .image = image1
39+
40+
41+ # adding button, and command will use rolling_dice function
42+ button = tkinter .Button (root , text = 'Roll the Dice' , fg = 'blue' , command = rolling_dice )
43+
44+ # pack a widget in the parent widget
45+ button .pack ( expand = True )
46+
47+ # call the mainloop of Tk
48+ # keeps window open
49+ root .mainloop ()
0 commit comments