I'm using tkinter to create a window with a button, the button's command is to destroy the window and create a similar new one on click, but the moment you run the program it automatically executes the button command which leads to a spam of windows creation and destruction
from tkinter import *
import random
import tkinter as tk
j=0
def func(j):
f=Tk()
f.title("game")
f.geometry("400x350")
f["bg"]="black"
#message
Label(f,bg="black",fg="white",height=2,width=20,text=" ").pack()
Label(f,bg="black",fg="white",height=3,width=20,text="click continue to proceed\n to main menu",font=("Arial",13)).pack()
#frame
global d
d=Frame(f,bg="white",bd=1)
d.pack(fill="both",expand=True,side="bottom")
print(d.__format__)
#cancel button
def canccel():
f.destroy()
c=Canvas(d,bg="white")
b1=Button(c,bg="white",text="cancel",command=canccel)
b1.pack()
c.pack(padx=90, pady=22,side=tk.LEFT)
#play button
if j==0:
k=Canvas(d,bg="white")
b2=Button(k,bg="red",text="continue!",command= [print("hehe"),func(-1)])
b2.pack()
k.pack(padx=15,pady=0,side=LEFT)
else:
j=random.randrange(0,400)
i=random.randrange(0,300)
k=Canvas(d,bg="white")
b2=Button(k,bg="white",text="continue!",command= [print("hehe"),func(j)])
b2.pack()
k.pack(padx=i,pady=j,side=LEFT)
f.mainloop()
func(j)
Related
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed last year.
I wanted to make button in tkinter, but when I started program, the command always calls when code just starts.
Here is example code:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.title("Why this don't works???")
window.wm_geometry("100x100")
def message():
messagebox.showinfo("Hi there")
button = tk.Button(text="Hello", command=message())
button.grid(column=0, row=0)
while True:
window.update()
And then, button didn't worked. (When you press it, it don't works.)
I don't know what I'm doing wrong, so I need help.
The command should be a pointer to a function
In the code you wrote, the command gets the return value from the function.
command=message()
The correct way is
command = message
The problem is you are requesting a return value from the fucnction. Try using this.
from tkinter import *
# import messagebox from tkinter module
import tkinter.messagebox
# create a tkinter root window
root = tkinter.Tk()
# root window title and dimension
root.title("When you press a button the message will pop up")
root.geometry('75x50')
# Create a messagebox showinfo
def onClick():
tkinter.messagebox.showinfo("Hello World!.", "Hi I'm your message")
# Create a Button
button = Button(root, text="Click Me", command=onClick, height=5, width=10)
# Set the position of button on the top of window.
button.pack(side='top')
root.mainloop()
You have 2 errors:
first:
It must be command=message
second:
You must give a message argument too, you entered a title only.
Or, what you can do is.
Add another variable.
command = message()
Before this line,
button = tk.Button(text="Hello", command=message())
And chande this line to,
button = tk.Button(text="Hello", command=command)
I want run python file which opens camera preview by Tkinter button that placed on the main window.But it runs automatically camera window without opening the main window when executing the code.
from tkinter import *
import tkinter as tk
import os
window = tk.Tk()
window.title("Camera")
window.geometry("640x480")
lbl=Label(window,text="Start", font=("Arial Bold",10))
lbl.grid(column=0,row=0)
btn = Button(window, text="Start",command=os.system('capture.py'))
btn.grid(column=1, row=0)
window.mainloop()
It should be command=lambda: os.system('capture.py'):
btn = Button(window, text="Start",command=lambda: os.system('capture.py'))
btn.grid(column=1, row=0)
If you use () near a function name, it will call the function immediately. Which is not what you want, you want it to be called upon press, so just pass the function name(with lambda if it has arguments) and tkinter will handle the rest.
I have a simple program with start and exit buttons. The start button makes a notification using win10toast, but the button remains visibly pressed down and the window becomes unresponsive. The exit button works fine before the start button is pressed. Here's my code:
from tkinter import *
from win10toast import ToastNotifier
root = Tk()
def exit_p():
exit()
def new():
hr.show_toast("New", "Alert")
return
#creates a label widget
myLabel1 = Label(root, text="Full Moon Notification!")
myLabel2 = Label(root, text="Here you can start and exit the program")
button1 = Button(root, text="Start",padx=50,command=new).grid(row=3,column=0)
button2 = Button(root, text="Exit", padx=50,command=exit_p).grid(row=4,column=0)
#puts the widget on the screen
myLabel1.grid(row=0,column=0)
myLabel2.grid(row=1,column=0)
#loop to keep program running
root.mainloop()
The issue is likely because hr.show_toast("New", "Alert") blocks.
The win10toast library conveniently provides an option threaded=True, so just change that code to
hr.show_toast("New", "Alert", threaded=True)
should make it work.
How can I spawn a window, and halt the execution of the GUI until this window is closed by the user?
That's exactly what functions from the tkinter.messagebox submodule will do.
These will spawn a dialog, and halt the execution until closed.
For instance, the showinfo function will spawn a window with the first parameter as title and the second as message.
Until the window is closed, the remaining of the GUI will not be interactable.
Here is an example demonstrating this.
import tkinter as tk
import tkinter.messagebox as tkmb
root = tk.Tk()
button = tk.Button(
root,
text="Spawn a dialog",
command=lambda: tkmb.showinfo(
"Information",
"Please close this window or press OK to continue"))
button.pack()
root.mainloop()
When the button is clicked, a window spawns.
As long as this window is open, the button will not be clickable once again.
I created a tkinter Toplevel window for my application and later in the program destroyed it but after destroying the window the program doesnt get executed further and get struck there itself doing nothing . Here is the code that I used :-
#login.py
from tkinter import *
class gui:
def __init__(self):
#does something
def login(self):
self.winLogin.destroy()
def guilogin(self):
self.winLogin = Toplevel()
btn = Button(self.winLogin,command=self.login,text='asd')
btn.pack()
self.winLogin.mainloop()
#main.py
import login
from tkinter import *
main = Tk()
a = login.gui()
a.guilogin()
if True:
#some code and this part doesnot get executed
main.mainloop()
else:
main.destroy()
I run main.py file and the code get struck and do nothing before the if part . I tottaly have no idea whats wrong . Pls. Help!
As furas said in the comments, you should not call mainloop on the toplevel, instead use grab_set to disable the main window and wait_window to wait for the toplevel to be closed:
from tkinter import Tk, Toplevel, Button
def login():
top = Toplevel(root)
Button(top, text="Quit", command=top.destroy).pack()
top.grab_set() # deactivate the main GUI while top is opened
root.wait_window(top) # wait for top to be closed before doing the rest
print("logged in")
root = Tk()
Button(root, text="login", command=login).pack()
root.mainloop()