Origin27
Origin27

Reputation: 13

Having Troubles with Python GUI(Tkinter)

Hey guys need some help with Python GUI (Tkinter). The problem im having is that im trying to get each radio button to produce a different message box, the way im trying to solve it is not working and wondering why its not working. (Below is the code im working with)

from tkinter.messagebox import *
from tkinter import *


def button_press():
    if button1:
        showinfo(title="Message", message="You selected to enter a new item.")
    elif button2:
        showinfo(title="Message", message="You selected to remove an item by its element number.")
root_window = Tk()
option_value = IntVar()

button1 = Radiobutton(root_window, text="Enter a new item.", variable=option_value, value=1, command=button_press)
button1.pack(anchor=W)

button2 = Radiobutton(root_window, text="Remove an item by its element number.", variable=option_value, value=2,command=button_press)
button2.pack(anchor=W)

root_window.mainloop()

Upvotes: 0

Views: 128

Answers (2)

Reblochon Masque
Reblochon Masque

Reputation: 36722

You can use a set of options to avoid cascading if statements, and create the radio buttons in a loop:

import tkinter as tk
from tkinter import messagebox


def button_press(option):
    messagebox.showinfo(title="Message", message=f"You selected to {messages[option]}")


if __name__ == '__main__':

    root_window = tk.Tk()
    option_value = tk.IntVar()
    messages = ["enter a new item.",
                "remove an item by its element number."]
    for idx, msg in enumerate(messages):
        tk.Radiobutton(root_window,
                       text=msg,
                       variable=option_value,
                       value=idx+1,
                       command=lambda option=idx: button_press(option)).pack(anchor=tk.W)

    root_window.mainloop()

It is also better not to clutter the namespace with * imports

Upvotes: 2

Negi Babu
Negi Babu

Reputation: 527

You should get the value of your variable option_value inorder to know which radio button is clicked. This can be done using option_value.get().

from tkinter.messagebox import *
from tkinter import *


def button_press():
    if option_value.get() == 1:
        showinfo(title="Message", message="You selected to enter a new item.")
    elif option_value.get() == 2:
        showinfo(title="Message", message="You selected to remove an item by its element number.")
root_window = Tk()
option_value = IntVar()

button1 = Radiobutton(root_window, text="Enter a new item.", variable=option_value, value=1, command=button_press)
button1.pack(anchor=W)

button2 = Radiobutton(root_window, text="Remove an item by its element number.", variable=option_value, value=2,command=button_press)
button2.pack(anchor=W)

root_window.mainloop()

Upvotes: 3

Related Questions