Introduction
We will create a Graphical User Interface using tkinter on python to display messageboxes from radiobuttons. To learn how to use python, you can check these tutorials. If you know python but want to learn how to use tkinter, you can check these tutorials. If you know tkinter but aren’t familiar with messageboxes, you can check that here.
The code to create warning, information and error messages using radio buttons is given below:
from tkinter import *
from tkinter import messagebox as msg
root = Tk()
root.title("Messagebox assignment")
root.iconbitmap("IOTEDU.ico")
def clicked():
if var.get() == 1:
info = msg.showinfo("Show info messagebox", "This message box is used to show information.")
elif var.get() == 2:
warn = msg.showwarning("Show warning messagebox", "This message box is used to show warnings.")
if var.get() == 3:
error = msg.showerror("Show error messagebox", "This message box is used to show errors.")
var = IntVar()
Radiobutton(root, variable = var, text = "Information messagebox", value = 1, command = clicked).grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'w')
Radiobutton(root, variable = var, text = "Warning messagebox", value = 2, command = clicked).grid(row = 1, column = 0, padx = 5, pady = 5, sticky = 'w')
Radiobutton(root, variable = var, text = "Error messagebox", value = 3, command = clicked).grid(row = 2, column = 0, padx = 5, pady = 5, sticky = 'w')
root.mainloop()
Steps along with explanation
- To begin with, we will import tkinter and the messagebox module from tkinter.
from tkinter import *
from tkinter import messagebox as msg
- Then we will create a root window for out radio buttons.
You can also give a title of your choice.
root = Tk()
root.title("Messagebox assignment")
root.iconbitmap("IOTEDU.ico")
- We can then go ahead and create three radio buttons, display them on our root window using the grid and apply padding to it.
We can also use a variable and assign it different values when different radio boxes are selected.
var = IntVar()
Radiobutton(root, variable = var, text = "Information messagebox", value = 1, command = clicked).grid(row = 0, column = 0, padx = 5, pady = 5, sticky = 'w')
Radiobutton(root, variable = var, text = "Warning messagebox", value = 2, command = clicked).grid(row = 1, column = 0, padx = 5, pady = 5, sticky = 'w')
Radiobutton(root, variable = var, text = "Error messagebox", value = 3, command = clicked).grid(row = 2, column = 0, padx = 5, pady = 5, sticky = 'w')
- Then we create a function “clicked” which displays the messageboxes when the radio buttons are selected.
def clicked():
if var.get() == 1:
info = msg.showinfo("Show info messagebox", "This message box is used to show information.")
elif var.get() == 2:
warn = msg.showwarning("Show warning messagebox", "This message box is used to show warnings.")
if var.get() == 3:
error = msg.showerror("Show error messagebox", "This message box is used to show errors.")