I am trying to make a window that would show the location of the mouse at all times by using pyautogui and tkinter. I am new to tkinter and python overall so I am not quite sure how to make it so that the values would keep updating in the window, if it is even possible. Here is my code so far:
from tkinter import *
import pyautogui as pag
window = Tk()
window.geometry("200x200")
window.title("window")
window.config(background="#4ceefc")
coordinates = pag.position()
label1 = Label(window, text="mouse coordinates:")
label1.place(x=20, y=50)
label2 = Label(window, text=coordinates)
label2.place(x=30, y=90)
window.mainloop()
I tried using a while loop on the labels and window.mainloop() function but this did not work
Create a StringVar() to store the coords, and then assign it to the label's textvariable. You can then bind a '<Motion>' handler to your root window to update the label whenever the mouse moves.
coord_var = StringVar(window)
def on_mousemove(event):
coord_var.set(f'Mouse coordinates: {event.x}, {event.y}')
label1 = Label(window, textvariable=coord_var)
label1.place(x=20, y=50)
window.bind('<Motion>', on_mousemove)
Unless you're using pyautogui for something else, you can get away without it for this.
Related
from tkinter import *
from tkinter import messagebox, Tk, Button, Canvas, Frame, BOTH
master = Tk() #tkinter name
click = 0 #click variable
label1 = Label(master, textvariable = click, font=('Times 14'), width=20, height=5) #label itself with font and a width with height
label1.pack()
for i in range(6):
time.sleep(1) # sleeping time 1 second
master.update_idletasks() #updates the label every second in order to see the change of the variable click
I tried a lot of methods, but the label just stays empty and there are no numbers or letters on it. I also think about making a label transparent so I can see only numbers in there.
Hey im pretty new to python and im taking a class in high school. For an assignment im working on we have to make a tkinter gui that includes the widgets, label, buttons, entry box, radio or check buttons, frames, and a display box. I am making a kilometers to miles converter that can do the opposite if chosen, there will be radio buttons that the user can choose to choose which one they would like to calculate, but i am having a lot of trouble on the calculation part because i cant get the entry box number to multiple or divide by 1.609 or any number.
Heres the code i have now, I apologize for the mess and how bad it probably
import tkinter as tk
import tkinter.messagebox
# Customize main window
root = tk.Tk()
root.title('GUI Assignment')
# Create the frames, right, left, and bottom, and pack them
bframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
bframe.pack(side='bottom')
rframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
rframe.pack(side='right')
lframe = tk.LabelFrame(root, highlightthickness=0, borderwidth=0, padx=100, pady=50)
lframe.pack(side='left')
# Make the label and the entry box for the right frame
dlabel = tk.Label(rframe, text = 'Enter the distance', )
dentry = tk.Entry(rframe, width=75)
# Pack the label and entry
dlabel.pack(side='left')
dentry.pack(side="right")
dist = 3.0
temp =(dentry.get())
# Create the convert command
def convert():
if radio_var.get()==1:
tkinter.messagebox.showinfo('Distance',temp / dist )
# Make the convert and quit buttons
b = tk.Button(bframe, text="Convert", command=convert)
quit = tk.Button(bframe, text='Quit', command=root.destroy)
# Pack the buttons
b.pack(side='left')
quit.pack(side='right')
# Make the radio variable
radio_var = tk.IntVar()
radio_var.set(1)
# Make the radio buttons for the left frame
rb = tk.Radiobutton(lframe, text='Km to Miles', variable=radio_var, value=1)
rb2 = tk.Radiobutton(lframe, text='Miles to Km', variable=radio_var, value=2)
# Pack The Radio Buttons
rb.pack()
rb2.pack()
root.mainloop()
The issue you're having here is that you're trying to divide temp, a string, by dist, a float. You need to convert temp to a float before converting it using float(temp). Also, since you set temp once during your script, it will only ever refer to the value that was in the input box as soon as the variable was assigned. In order to fix this, you have to call dentry.get() inside of your convert() function rather than outside of it.
I have a following question. I want to make a button in tkinter that will delete existing changes and the window will looks like the initial window.
This is my initial Window 1:
This is how the window looks like when I click on the first two buttons, Window 2:
Now I would like to click on the "Zpět" button and I want to see Window 1 again.
Here is my code:
import tkinter as tk
root = tk.Tk()
home_frame = tk.Frame(root)
home_frame.grid(row=0, column=0, sticky="news")
def raise_new_payment():
tk.Label(text=f"Stav bilance k 2021-09-09").grid()
def back():
"""I would like to this function to clean everything."""
tk.Label().destroy()
platba = tk.Button(
home_frame,
text="Zadej novou platbu",
command=lambda: raise_new_payment(),
)
platba.pack(pady=10)
zpet = tk.Button(
home_frame,
text="Zpět",
command=back,
)
zpet.pack(pady=10)
I don't know how to use the back() function. I tried to delete the tk.Label as created in raise_new_payment(), but it did not work. Can you help me please? Thanks a lot.
I would suggest you create the label once and don't call .pack() on it first, i.e. it is not visible initially.
Then update it inside raise_new_payment() and call .pack() to show it.
You can call .pack_forget() to hide it again inside back().
import tkinter as tk
root = tk.Tk()
home_frame = tk.Frame(root)
home_frame.grid(row=0, column=0, sticky="news")
def raise_new_payment():
# update label and show it
lbl.config(text=f"Stav bilance k 2021-09-09")
lbl.pack()
def back():
# hide the label
lbl.pack_forget()
platba = tk.Button(
home_frame,
text="Zadej novou platbu",
command=lambda: raise_new_payment(),
)
platba.pack(pady=10)
zpet = tk.Button(
home_frame,
text="Zpět",
command=back,
)
zpet.pack(pady=10)
# create the label and initially hide it
lbl = tk.Label(home_frame)
root.mainloop()
Is it possible to track what widgets I enter with my mouse into while it's pressed?
I want to create a chain-like effect that the background of the label\button change while click and drag the mouse and moving from widget to widget.
Thanks :)
You can bind to the <B1-Motion> event, and then use winfo_containing to get the widget under the cursor.
Here's a simple example:
import tkinter as tk
root = tk.Tk()
current_label = tk.Label(root, text="", anchor="w", width=100)
current_label.pack(side="top", fill="x")
def show_widget(event):
widget = event.widget.winfo_containing(event.x_root, event.y_root)
current_label.configure(text=f"widget: {str(widget)}")
for x in range(10):
name = f"Label #{x+1}"
label = tk.Label(root, text=name)
label.pack(padx=10, pady=10)
label.bind("<B1-Motion>", show_widget)
root.mainloop()
I've done stuff like tracking entry/exit for a specific widget:
widget.bind("<Enter>", enter_func)
widget.bind("<Leave>", exit_func)
you may be able to do something cute with that
I want to ask u guys if there is a way of getting name or some id of widget which is mouse pointer currently on. Is there a way of doing this? Thanks for any response.
Normally you get this information from a binding. However, if you want to poll the system at any point to find out which widget is under the mouse, you can use winfo_pointerxy to get the coordinates of the mouse, and then pass those to winfo_containing to get the widget under those coordinates.
Here's an example program that continuously prints out the widget under the mouse:
import tkinter as tk
def print_widget_under_mouse(root):
x,y = root.winfo_pointerxy()
widget = root.winfo_containing(x,y)
print("widget:", widget)
root.after(1000, print_widget_under_mouse, root)
root = tk.Tk()
label_foo = tk.Label(root, text="Foo", name="label_foo")
label_bar = tk.Label(root, text="Bar", name="label_bar")
button = tk.Button(root, text="Button", name="button")
button.pack(side="bottom")
label_foo.pack(fill="both", expand=True)
label_bar.pack(fill="both", expand=True)
print_widget_under_mouse(root)
root.mainloop()