Changing the Mouse Cursor - Tkinter

Changing the Mouse Cursor - Tkinter

In Tkinter, you can change the mouse cursor for any widget, or even for the entire application window. This can provide a visual indication to the user about the nature of the interaction they're currently engaged in. For instance, you might change the cursor to a hand when hovering over a button that leads to a web link.

Here's a simple way to change the mouse cursor for different widgets in a Tkinter application:

import tkinter as tk def on_button_hover(event): event.widget.config(cursor="hand2") def on_button_leave(event): event.widget.config(cursor="") root = tk.Tk() label = tk.Label(root, text="Hover over the button!") label.pack(pady=20) # The button starts with the arrow cursor. button = tk.Button(root, text="Hover over me!") button.pack(pady=20) # Change cursor when mouse hovers over the button button.bind("<Enter>", on_button_hover) button.bind("<Leave>", on_button_leave) root.mainloop() 

In this code:

  • The <Enter> event is triggered when the mouse enters the widget's area, and <Leave> is triggered when the mouse leaves the widget's area.

  • We change the cursor to a hand (hand2) when the mouse hovers over the button, and revert back to the default cursor when it leaves.

Tkinter supports a variety of cursors like arrow, circle, cross, dot, watch, hand2, and more. You can set the cursor for any widget by using the cursor option:

widget.config(cursor="cursor_type") 

Replace widget with the name of your widget (e.g., button, label, etc.) and cursor_type with the desired cursor type.


More Tags

value-initialization url-encoding ngx-cookie-service datasource openhardwaremonitor firefox-addon vuejs2 angular-data binning grafana

More Programming Guides

Other Guides

More Programming Examples