Harsh Rao Dhanyamraju
Harsh Rao Dhanyamraju

Reputation: 89

How to run buttons within functions in Tkinter?

Here I am creating a new window to take data input from the user, however when I press the submit button i.e button 2, nothing happens. It neither prints anything nor are there any error messages.

import tkinter as tk
window = tk.Tk()

# Space for handle click functions starts

def insert_bar_data(event): # To take data entry in a new window
    print("Taking bar graph Data")
    window_BarGraph = tk.Tk()
    btn_bar_Sub = tk.Button(master = window_BarGraph, text = "Submit", width=6,height=2)
    btn_bar_Sub.bind("<Button-2>", submit_bar_data)
    btn_bar_Sub.pack()

def submit_bar_data(event): # To submit data entry for the newely opened window
    print("Submitting Bar Graph Data")

# Space for handle click functions ends

frame_bar = tk.Frame()
btn_bar = tk.Button(master = frame_bar, text = "Insert Bar Graph", width=20,height=2)
btn_bar.bind("<Button-1>", insert_bar_data)
btn_bar.pack()
frame_bar.pack()

window.mainloop()

I would really appreciate if you could help me with this.

Upvotes: 0

Views: 603

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386342

Consider this code:

btn_bar_Sub.bind("<Button-2>", submit_bar_data)

You are binding to the second mouse button rather than the normal mouse button. When I run your code and click the second mouse button, your code works fine. If you want it to work with the primary button, use <Button-1>.

That being said, the best way to call a function from a button is to use the command option of the button.

def submit_bar_data():
    ...
btn_bar_Sub = tk.Button(..., command=submit_bar_data)

Upvotes: 1

Related Questions