Move tkinter button randomly on mouse hover - python

I'm trying to make a button move randomly to coordinates in lists.
It moves the first time I hover on it each time I run the programme and never after and I can't figure it out, I'm a total noob, though and frankly I'm amazed it works at all.
I hate asking questions but I've been trying to solve this for weeks so I appreciate anyone's help..
import tkinter as tk
from tkinter import *
import random
root = tk.Tk()
root.title('Press me')
root.geometry('1280x800')
img=PhotoImage(file='red_button_crop.png')
my_label=Label(root, text="",font='helvetica,12')
my_label.pack(pady=50)
but_loc_x=[200,600,1000]
but_loc_y=[200,350,600]
but_pos_x=random.choice(but_loc_x)
but_pos_y=random.choice(but_loc_y)
def press():
my_label.config(text="You pressed me.\n Well done\nYou are as clever as a monkey.\n Not one of the good ones tho")
root.after(1500,root.destroy)
def button_hover(e):
root.after(250)
button.place_configure(x=but_pos_x,y=but_pos_y)
#def unhover(e):
# root.after(500)
#button.place_configure(x=600,y=350)
button =tk.Button(root,image=img,borderwidth=0,command=press)
button.place(x=600,y=350,anchor=CENTER)
button.bind("<Enter>",button_hover)
#button.bind("<Leave>",unhover)
root.mainloop()
I've tried implementing various bit of code I searched up on the net but I don't know enough to work it out

Importantly, as one of the comments suggests, the button is moving every time you hover over it, so your code was in fact correct.
However, because the coordinates are set outside of the function it always hovers to the same place (so it appears like it was not moving).
The changes that correct to code to the desired output are below.
removed from tkinter import * and used the tk alias as it should be.
moved the random button positions into the function (see comment with arrow).
This is the corrected version of the code:
import tkinter as tk
# from tkinter import *
import random
root = tk.Tk()
root.title('Press me')
root.geometry('1280x800')
img=tk.PhotoImage(file='red_button_crop.png')
my_label=tk.Label(root, text="",font='helvetica,12')
my_label.pack(pady=50)
but_loc_x=[200,600,1000]
but_loc_y=[200,350,600]
def press():
my_label.config(text="You pressed me.\n Well done\nYou are as clever as a monkey.\n Not one of the good ones tho")
root.after(1500,root.destroy)
def button_hover(e):
root.after(250)
but_pos_x=random.choice(but_loc_x) # <----- moved into the function
but_pos_y=random.choice(but_loc_y) # <----- moved into the function
button.place_configure(x=but_pos_x,y=but_pos_y)
#def unhover(e):
# root.after(500)
#button.place_configure(x=600,y=350)
button =tk.Button(root,image=img,borderwidth=0,command=press)
button.place(x=600,y=350,anchor=tk.CENTER)
button.bind("<Enter>",button_hover)
#button.bind("<Leave>",unhover)
root.mainloop()
Result:
the image red_button_crop.png now moves randomly when hovered over.

Related

How to deselect an entry in Tkinter

A friend of mine was making a basic program using tkinter when he realized that even when you deselect an entry, the cursor still remains in that entry until you select another one. My question is, is this a technical issue? Also, is there any way for me to fix this?
use widget.focus_set() to change focus when mouse button is pressed
from tkinter import *
def change_focus(event):
event.widget.focus_set()
root = Tk()
Entry(root).pack()
Entry(root).pack()
root.bind_all('<Button>', change_focus)
root.mainloop()

Importing and using mp3s on button press

So I have coded a "copy" of the game 2048 after following a Kite youtube tutorial. I want to add a small mp3 to play anytime you click an arrow key(to move stuff around in the game) but I'm not entirely sure what i'm doing right or wrong here. How do I do this?
I've snipped the important stuff out(import music is a folder for my mp3s)
import tkinter as tk
import mp3play
import music
The two errors I'm getting are down below, the Tk in Tk() is underlined and the root in left(root...)
when i attempt to run the code like this, it highlights "import mp3play" and says there is a Syntax error. Not sure why, I have in fact installed mp3play via pip installer as well
root = Tk()
f = mp3play.load('beep.mp3'); play = lambda: f.play()
button = left(root, text = "Play", command = play)
button.pack()
root.mainloop()
in between the 2 middle sections is the def for up, down, left, and right but that would just clutter this question
Here is the stackoverflow I've referenced for it, to be honest I dont understand half of it. How can I play a sound when a tkinter button is pushed?
Take a look at this simple example using winsound which is easier to handle for small beeps.
from tkinter import *
import winsound
root = Tk()
def play():
winsound.Beep(1000, 100)
b = Button(root,text='Play',command=play)
b.pack()
root.mainloop()
winsound.Beep(1000, 100) takes two positional arguemnts, 1000 is the frequency and 100 is the duration in milliseconds.
Do let me know if any errors or doubts.
Cheers

How to put image in another window in tkinter?

I want to put an image in the second window using tkinter, in the first window the code works good, but the second window shows nothing.
In this part I import necessary modules:
from tkinter import filedialog, Tk, Frame, Label, PhotoImage, Button
from PIL import Image
from tkinter import*
import tkinter as tk
Then create the principal window:
raiz = Tk()
raiz.title("ventana")
Then I create the frame and put the image in the frame:
miFrame = Frame()
miFrame.pack()
miFrame.config(width="1400", heigh=("1200"))
fondo=tk.PhotoImage(file="fondoF.png")
fondo=fondo.subsample(1,1)
label=tk.Label(miFrame,image=fondo)
label.place(x=0,y=0,relwidth=1.0,relheight=1.0)
Then a button that will call the second window function:
btn3 = Button(raiz, text="boton")
btn3.place(x=500, y=500)
btn3.config(command=abrirventana2)
Here we have the function which opens the second window and here (I guess) is where I want to put the image.
This part also has two buttons named mih which does nothing in the meantime and ok which calls the function to close the second window:
def abrirventana2():
raiz.deiconify()
ventana2=tk.Toplevel()
ventana2.geometry('500x500')
ventana2.title("ventana2")
ventana2.configure(background="white")
fondov=tk.PhotoImage(file="xxx.gif")
label1=tk.Label(ventana2,image=fondov)
label1.place(x=50,y=50,relwidth=5.0,relheight=5.0)
mensaje=tk.Label(ventana2,text="funciona")
mensaje.pack(padx=5,pady=5,ipadx=5,ipady=5,fill=tk.X)
boton1=tk.Button(ventana2,text='mih')
boton1.pack(side=tk.TOP)
boton2=tk.Button(ventana2,text='ok',command=ventana2.destroy)
boton2.pack(side=tk.TOP)
Function to close the second window:
def cerrarventana2():
ventana.destroy()
I use the mainloop to keep the window open
raiz.mainloop()
Note: I had already tried creating a frame in the second window, but it didn't work.
Apologies for my previously incorrect answer.
The reason the image is not showing is due to the fact that you did not create a reference to it. If you don't create a reference, the image is garbage collected, which doesn't remove it, but in a sense just renders a blank placeholder on the GUI.
In order to display the image correctly you need to add a reference to the image within the code that displays the image.
You therefore now have:
fondov=tk.PhotoImage(file="giphy.gif")
label1=tk.Label(ventana2,image=fondov)
label1.image = fondov
label1.pack()
(label1.image = fondov is the reference)
Sorry for the confusion there. This should work.

Python Tk() Button command not completely working

I'm quite new to python programming and have quite a basic question which I can't seem to resolve myself - I hope someone might be able to shed some light on this!
I created a .py file which runs a basic Rock, Paper, Scissors game between a user and the (random) computer. This uses a GUI via a tk() and works absolutely fine.
Then, I created another .py file, this time to create an overall menu GUI, from which I could choose to run my Rock, Paper, Scissors game. I can create this tk() fine, the button to select the RPS game, the game loads up, but this time it doesn't work at all! I can press the buttons, but they don't progress the game.
Here's my code for the game.py:
from tkinter import *
from tkinter.ttk import *
import random
def gui():
<game code goes in here, including other functions>
root=Tk()
root.title("Rock, Paper, Scissors")
# more code to define what this looks like
# including a Frame, buttons, labels, etc>
if __name__=='__main__':
gui()
And then I created the overall game menu, menu.py:
from tkinter import *
from tkinter.ttk import *
import random
import game
main=Tk()
main.title("J's games")
mainframe=Frame(main,height=200,width=500)
mainframe.pack_propagate(0)
mainframe.pack(padx=5,pady=5)
intro=Label(mainframe,
text="""Welcome to J's Games. Please make your (RPS) choice.""")
intro.pack(side=TOP)
rps_button=Button(mainframe, text="Rock,Paper,Scissors", command=game.gui)
rps_button.pack()
test_button=Button(mainframe,text="Test Button")
test_button.pack()
exit_button=Button(mainframe,text="Quit", command=main.destroy)
exit_button.pack(side=BOTTOM)
main.mainloop()
If anyone can see something obvious, please let me know. I'm confused as to why it works on its own, but not when I incorporate it into another function (the button command). I've tried the IDLE debugging but it seems to freeze on me!
I presume you want the main window to remain when one selects a particular game. That means that the game should be in a separate frame, initially in a separate Toplevel. Modify your rps file something like the following,
from tkinter import *
from tkinter.ttk import *
import random
class RPS(Toplevel):
def __init__(self, parent, title):
Toplevel.__init__(parent)
self.title(title)
#game code goes in here, including other functions
# more code to define what this looks like
# including a Frame, buttons, labels, etc>
if __name__=='__main__':
root=Tk()
root.withdraw()
RPS(title = "Rock, Paper, Scissors")
root.mainloop()
This way, importing the file does not create a second root and mainloop.
If you want only one game running at a time, you could instead use a paned window with two panes. Turtledemo does this. The code is in turtledemo.main. You would then derive RPS from Frame and pack it into the second pane.

How to bring Tkinter window in front of other windows?

I'm working with some Tkinter Python code (Python 3.4), and I've come across a problem. When I create my Tkinter window it doesn't show up in front. I do it currently with the following code:
from tkinter import *
win = Tk()
win.minsize(width=1440, height=828)
win.maxsize(width=1440, height=828)
The minsize() and maxsize() make the window cover my entire screen, but the original python running window (The one that wouldprint("Hello, World!")) ends up on top. Is there a way to fix this? I'm running OS X 10.10.1.
Set it as the topmost (but it will always stay in front of the others):
win.attributes('-topmost', True) # note - before topmost
To not make it always in front of the others, insert this code before the mainloop:
win.lift()
win.attributes('-topmost', True)
win.attributes('-topmost', False)
Don't forget win.mainloop() at the end of your code (even if in some cases it's not explicitly required)
Other discussions on the same problem:
How to put a Tkinter window on top of the others
How to make a Tkinter window jump to the front?

Categories