My button doesn't apear after the initial popup - Python Message Box - python

I'm trying to make a little pop-up interface before my game to choose difficulties. The problem I'm having is that after I click yes on the first messagebox.askyesno() the whole pop up disappears and I have no idea on how to know which button was pressed to return an output. This is my first time using tkinter and messagebox so any help is greatly appreciated.
This is my code:
import tkinter as tk
from tkinter import messagebox
def start_game():
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
if messagebox.askyesno("Welcome to Snake!", "Would you like to play?") == True:
mainLabel = tk.Label(root, text='Choose a dificulty:')
easy_ask = tk.Button(root, text='Easy')
medium_ask = tk.Button(root, text='Medium')
hard_ask = tk.Button(root, text='Hard')
mainLabel.pack(side=tk.LEFT)
easy_ask.pack(side=tk.LEFT)
medium_ask.pack(side=tk.LEFT)
hard_ask.pack(side=tk.LEFT)
root.deiconify()
root.destroy()
root.quit()
root.mainloop()
start_game()

What about an else statement ;-)? Consider what your code is doing: if you click 'Yes', it creates some Button on a main window that you have withdrawn. Then, immediately after you deiconify it, you destroy it. Reshuffle your code like follows:
import tkinter as tk
from tkinter import messagebox
def start_game():
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
if messagebox.askyesno("Welcome to Snake!", "Would you like to play?") == True:
root.deiconify() # <--- deiconify under the True condition
mainLabel = tk.Label(root, text='Choose a dificulty:')
easy_ask = tk.Button(root, text='Easy')
medium_ask = tk.Button(root, text='Medium')
hard_ask = tk.Button(root, text='Hard')
mainLabel.pack(side=tk.LEFT)
easy_ask.pack(side=tk.LEFT)
medium_ask.pack(side=tk.LEFT)
hard_ask.pack(side=tk.LEFT)
else:
root.destroy() # <--- destroy and quit under the False condition
root.quit()
root.mainloop()
start_game()
Note that you can also assign the outcome of messagebox.askyesno to a variable:
answer = messagebox.askyesno("Welcome to Snake!", "Would you like to play?")

Related

Python Tkinter simple value process

I just new for the GUI and need little help.
a=int(input())
if a==0:
print("hi")
else:
print("hello")
I want to change input process to click button, like a switch.
left button -> a=0
right button -> a=1
window=tkinter.Tk()
window.title("")
window.geometry("640x640+100+100")
window.resizable(True, True)
a=tkinter.Button(window, text="left")
a.pack()
b=tkinter.Button(window, text="right")
b.pack()
window.mainloop()
I can see left, right button but I don't know how to put values.
Is there any example I can use?
Thanks
Does this example help You:
from tkinter import Tk, Button
def switch(btn1, btn2):
btn1.config(state='disabled')
btn2.config(state='normal')
print(btn1['text'])
window = Tk()
window.title("")
on = Button(window, text="On", command=lambda: switch(on, off))
on.pack(side='left', expand=True, fill='x')
off = Button(window, text="Off", command=lambda: switch(off, on))
off.pack(side='left', expand=True, fill='x')
off.config(state='disabled')
window.mainloop()
If You have questions ask but here is pretty good site to look up tkinter widgets and what they do, their attributes.
Also I suggest You follow PEP 8
You need to add a function to each one that will be executed when the buttons are clicked like this:
import tkinter as tk
def left_clicked():
print("Left button clicked")
right_button.config(state="normal") # Reset the button as normal
left_button.config(state="disabled") # Disable the button
def right_clicked():
print("Right button clicked")
right_button.config(state="disabled")
left_button.config(state="normal")
window = tk.Tk()
window.title("")
window.geometry("640x640+100+100")
# window.resizable(True, True) # Unneeded as it is already the default
left_button = tk.Button(window, text="left", command=left_clicked)
left_button.pack(side="left")
right_button = tk.Button(window, text="right", command=right_clicked,
state="disabled")
right_button.pack(side="right")
window.mainloop()

How can I delete a Label?

When I click a button, it should write text under it and the text should disappear after few seconds.
I don't know how to code that. What I have tried so far:
from tkinter import *
import time
window = Tk()
window.title("Button")
window.geometry("500x300")
def buttonclick():
tex = Label(text="You clicked the button")
tex.pack()
time.sleep(5)
tex.destroy()
but = Button(text="Click me!", command=buttonclick)
but.pack()
window.mainloop()
You can use .after() method to destroy the label after fixed period of time.
The following example will delete the label after 3 seconds:
from tkinter import *
import time
window = Tk()
window.title("Button")
window.geometry("500x300")
def buttonclick():
tex = Label(text="You clicked the button")
tex.pack()
tex.after(3000, tex.destroy)
but = Button(text="Click me!", command=buttonclick)
but.pack()
window.mainloop()
Output:
Your code looks correct for the most part. The reason why it doesn't appear to be working is that there is nothing telling the window to update after adding the text. A simple fix would be to add window.update() when you create the label.
The Code should look like:
from tkinter import *
import time
window = Tk()
window.title("Button")
window.geometry("500x300")
def buttonclick():
tex = Label(text="You clicked the button")
tex.pack()
window.update()
time.sleep(5)
tex.destroy()
window.update()
but = Button(text="Click me!", command=buttonclick)
but.pack()
window.mainloop()

Tkinter (Python) output random numbers to GUI

Noob Alert!!!
Hello, I just started my journey with through python a couple of days ago, so my question will most likely be extremely simple to answer. Basically I have a random number gen. from 1 to 10, this is activated when the "test button is pressed on the windows that pops up. As you can see from the image below the random number appears in the output console on the bottom of the screen, in this case it was a 9. So here's the question, How can I make the random number on the GUI? so when the button is pressed a random number appears on the same window as the button.
https://i.stack.imgur.com/hWd3i.png
Any help is appreciated!
from tkinter import *
root = Tk()
root.geometry("300x300")
root.title("test it is")
root.grid()
def randnum(event):
import random
value =random.randint(1,10)
print(value)
button_1 = Button(root, text="test")
button_1.bind("<Button-1>",randnum)
button_1.pack()
root.mainloop()
from tkinter import *
root = Tk()
root.geometry("300x300")
root.title("test it is")
root.grid()
def randnum(event):
import random
value =random.randint(1,10)
print(value)
updateDisplay(value)
def updateDisplay(myString):
displayVariable.set(myString)
button_1 = Button(root, text="test")
button_1.bind("<Button-1>",randnum)
button_1.pack()
displayVariable = StringVar()
displayLabel = Label(root, textvariable=displayVariable)
displayLabel.pack()
root.mainloop()
Here is what it looks like.You have to create a Label with a Button, whose value will get updated when you click on button.
import tkinter as tk
from random import randint
win = tk.Tk()
def test_button_click():
label_val.set(randint(1, 10))
my_button = tk.Button(win, text='Test Button',
command=test_button_click)
my_button.grid(column=0, row=0)
label_val = tk.IntVar()
my_Label = tk.Label(win, textvariable=label_val)
my_Label.grid(column=1, row=0)
win.mainloop()
This will achieve what you are requesting -- create a tk window, add a button and label, use the callback test_button_click to set the labels int var when the button is clicked.

How to destroy widgets?

I want in my if statement for it to destroy the buttons on my tkinter. I have tried a couple of methods and looked up a few and some i don't understand/too complicated. I have tried making the function create a new window but it isn't displaying.
def greenwin():
global tkinter
global Tk
root = Tk()
root.title("GAME OVER")
root.geometry('387x387')
gamelabel=Label(root,text="GAME OVER!GREENS
WIN!",width=33,height=15).place(x=150,y=150)
root.mainloop
return
I want a clear method of destroying widgets.I would like a function that destroys all these buttons for my tic tac toe.
but1=Button(root,text="",bg="white",width=11,height=5,command=colour1).place(x=0,y=0)
but2=Button(root,text="",bg="white",width=11,height=5,command=colour2).place(x=0,y=150)
but3=Button(root,text="",bg="white",width=11,height=5,command=colour3).place(x=0,y=300)
but4=Button(root,text="",bg="white",width=11,height=5,command=colour4).place(x=150,y=0)
but5=Button(root,text="",bg="white",width=11,height=5,command=colour5).place(x=150,y=150)
but6=Button(root,text="",bg="white",width=11,height=5,command=colour6).place(x=150,y=300)
but7=Button(root,text="",bg="white",width=11,height=5,command=colour7).place(x=300,y=0)
but8=Button(root,text="",bg="white",width=11,height=5,command=colour8).place(x=300,y=150)
but9=Button(root,text="",bg="white",width=11,height=5,command=colour9).place(x=300,y=300)
root.mainloop
import tkinter as tk
root = tk.Tk()
any_widget = tk.Button(root, text="Press to destroy!")
any_widget['command'] = any_widget.destroy # pay special attention to the lack of ()
# call any_widget.destroy(), button widget's command option specifically needs a
# reference to the method instead of an actual call
any_widget.pack()
root.mainloop()
Try this:
import tkinter as tk
root = tk.Tk()
root.geometry("500x300+10+13")
root.title("Test")
b = tk.Button(root, text="click me")
def onclick(evt):
w = evt.widget
w.destroy()
b.bind("<Button-1>", onclick)
b.pack()
root.mainloop()

How to compulsory close message box for Toplevel window

image for that
I have few lines of code here which is login system which works fine but i can click on the Toplevel button multiple times when i provide the wrong password without closing the messagebox.How can i make it so that it has to be closed messagebox before i can make attempt again.
from tkinter import *
from tkinter import messagebox
def top():
if entry1.get() == "333":
log.destroy()
root.deiconify()
else:
messagebox.showerror("error", "try again")
root = Tk()
root.geometry("300x300")
log = Toplevel(root)
log.geometry("200x200")
label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)
label1.pack()
entry1.pack()
button1.pack(side="bottom")
lab = Label(root, text="welcome bro").pack()
root.withdraw()
root.mainloop()
You need to make the log window the parent of the dialog:
messagebox.showerror("error", "try again", parent=log)
By default it will use the root window (the Tk instance) as the parent which in this case is not what you want.
With hint from #furas this how to implement this:
create another function to the call it when the entry doesn't match and use grab_set method for the Toplevel window tp.grab_set().You can add your customarised image to the Toplevel window as well as message to display in the box(here: i use label to depict that)
from tkinter import *
from tkinter import messagebox
def dialog(): # this function to call when entry doesn't match
tp = Toplevel(log)
tp.geometry("300x100")
tp.title('error')
tp.grab_set() # to bring the focus to the window for you to close it
tp.resizable(width=False, height=False)
l = Label(tp, text="try again\n\n\n\n add your customarize image to the window")
l.pack()
def top():
if entry1.get() == "333":
log.destroy()
root.deiconify()
else:
dialog() # being called here
root = Tk()
root.geometry("300x300")
log = Toplevel(root)
log.geometry("200x200")
label1 = Label(log, text="password")
entry1 = Entry(log)
button1 = Button(log, text="login", command=top)
label1.pack()
entry1.pack()
button1.pack(side="bottom")
lab = Label(root, text="welcome bro").pack()
root.withdraw()
root.mainloop()

Categories