Search code examples
pythonpython-3.xtkinternmap

Activating function on click with tkinter Python


I have a function that creates radio buttons:

def scan_networks():
    net_scan = nmap.PortScanner()
    net_scan.scan(hosts='10.0.0.0/24', arguments='-sn')
    network_scan_window = Tk()
    for i, host in enumerate(net_scan.all_hosts()):
        targetable_hosts_label = Label(text="Targetable Hosts:").grid(row=0)
        hosts_radio = Radiobutton(network_scan_window, value=host, text=host).grid(row=1, column=i)
    network_scan_window.mainloop()

I need to call a function when clicking on one of the hosts radio with it's host.

So lets say the function returned a bunch of radio buttons with different ip's I need to call function x with the parameter of the value of the radio button


Solution

  • When working with Radiobuttons, you should use a variable to group the radiobuttons together and to keep track of the current value. You can use the command option of the Radiobutton to have a function be called when making a selection and get the value of the variable to get the current selection:

    import tkinter as tk
    
    def callback():
        print(v.get())
    
    root = tk.Tk()
    
    list = ['one', 'two', 'three']
    
    v = tk.StringVar()
    v.set(list[0])
    
    for value in list:
        tk.Radiobutton(root, value=value, text=value, variable=v, command=callback).pack()
    
    root.mainloop()