Python Forum

Full Version: python311 tkinter moving mouse event.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi.I am running a tkinter mapview in root window.
Coordinate,pos_x, is shown on a label in full size rootwindow.
However when I move mouse from i.e pos_x= 10 to 9, label shows 90.
I have tried config, giving input of "", but seemes not to work.
I would appreciate any hints howto view the mouse coordinate not to "add" to next coordinate when length of screen distances decreases.
Below is some code involved. Image attached shows result moving mouse from a 4 ciffer posit to a 3 ciffer screen position (The 4th ciffer adding to 3ciffer position). [Image: DC0LLCB]
import tkintermapview
from textholders import *
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *

window = tkinter.Tk()
window.geometry("1920x1200+0+0")
window.minsize(1920, 1200)
window.resizable(False, False)
window.state("normal")
window.title("ROOT")
window.config(background="blue")



map_widget = tkintermapview.TkinterMapView(window, width=1000, height=1000, corner_radius=0)
map_widget.place(x=450, y=100)

def motion(event):
    global pos_x, pos_y
    pos_x = event.x_root
    pos_y = event.y_root

    inp_posskjerm = ttk.Label(window, font=("Ariel",16,"bold"), text=(pos_x))
    
    inp_posskjerm.place(x=115,y=277)
window.bind("<Motion>", motion)


window.mainloop()   
You should not make a new label to change the mouse position display. Instead, change the text value of the existing label. In this example I use a StringVar, but it would work the same if I set the "text" attribute of the label.
import tkinter as tk  # Don't use wildcard imports


# Learn about classes.  Works really well for GUI code.
class MyWindow(tk.Tk):
    """ A window that displays the mouse position. """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.mouse_pos = tk.StringVar(self, 0)
        tk.Label(self, textvariable=self.mouse_pos, font=(None, 100), width=10).pack()
        self.bind("<Motion>", self.motion) 

    def motion(self, event):
        """ Method called when mouse moves in window. """
        self.mouse_pos.set(f"{event.x}, {event.y}")


MyWindow().mainloop()
Adding widgets to a window after it is drawn is rarely done.