In this article, you will learn how to create Python GUI for Random Generator. To understand this program, you should know about the following Python Programming topics: Python Functions.
Problem Definition
Create a Python window containing a grid of 2×2 buttons. In that window, place 4 buttons that have 4 different functionalities:
- Button 1: Pressing Button 1 will print a random integer number.
- Button 2: Pressing Button 2 will print a random float number.
- Button 3: Pressing Button 3 will print a random lowercase word containing a-z
- Button 4: Pressing Button 4 will print a random uppercase word containing A-Z
Tkinter Programming
Tkinter is the standard GUI library for Python. When combined with Python, it provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit, making creating a GUI application easy.
Program
from tkinter import *
from tkinter import messagebox
import random
import string
def printRandomInt():
r_int = random.randint(1,10000000)
messagebox.showinfo("information","Random integer number: "+str(r_int))
def printRandomFloat():
r_float = random.random()
messagebox.showinfo("information","Random float number: "+str(r_float))
def printRandomSmall():
r_small = random.choice(string.ascii_lowercase)
messagebox.showinfo("information","Random lowercase character: "+r_small)
def printRandomCap():
r_float = random.choice(string.ascii_uppercase)
messagebox.showinfo("information","Random uppercase character: "+r_float)
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
#self.pack(fill=BOTH, expand=1)
self.pack()
button1 = Button(self, text = "Print Random Integer", fg = "Black", bg = "White", command = printRandomInt)
button2 = Button(self, text = "Print Random Float", fg = "Black", bg = "White", command = printRandomFloat)
button3 = Button(self, text = "Print Random Small", fg = "Black", bg = "White", command = printRandomSmall)
button4 = Button(self, text = "Print Random Cap", fg = "Black", bg = "White", command = printRandomCap)
button1.grid(row = 1, column = 1,padx=10,pady=50)
button2.grid(row = 1, column = 2,padx=10,pady=50)
button3.grid(row = 2, column = 1,padx=10,pady=10)
button4.grid(row = 2, column = 2,padx=10,pady=10)
root = Tk()
#root.configure(background = "light blue")
root.title("Random Generator")
root.geometry("450x250")
app = Window(root)
root.mainloop()