[source code] Python GUI with Tkinter - 7 - Mouse Click Events

0 Bucky Roberts · September 11, 2014

from tkinter import *

root = Tk()

def leftClick(event):
   print("Left")

def middleClick(event):
   print("Middle")

def rightClick(event):
   print("Right")

frame = Frame(root, width=300, height=200)
# Event is something the user does to the widget, function that gets called
frame.bind("<Button-1>", leftClick)
frame.bind("<Button-2>", middleClick)
frame.bind("<Button-3>", rightClick)
frame.pack()

root.mainloop()

Post a Reply

Replies

Oldest  Newest  Rating
0 Mason Farina · September 13, 2014
I decided to play around more with tkinter before waiting for your next tutorials, and this is what I have. 

from tkinter import *

root = Tk()

def motion(event):
    x, y = event.x, event.y
    print(x,y)

    if x > 50 and x < 100 and y > 50 and y < 100:
        if event.type == "4":
            lab_test = Label(root,width=5,height=5,bg="black")
            lab_test.grid(column=1,row=2)
            print("Clicked at:",x,"",y)
frame_pad = Frame(root,width=300,height=300)
label_red = Label(root,width=1,height=1,fg="red",bg="red")
label_green = Label(root,width=1,height=1,fg="green",bg="green")
frame_pad.bind("<Motion>",motion)
frame_pad.bind("<Button-1>",motion)
label_red.grid(column=0,row=0,sticky=W)
label_green.grid(column=0,row=1,sticky=W)
frame_pad.grid(columnspan=9)

root.mainloop()


It's messy, and the test label doesnt do even close to what i want it to. but it kinda works, and it was fun to make. Thanks bucky!
  • 1

Python

107,123 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator