I'm currently working on a hangman game in python using tkinter. My code is working but I would like to make it better. My question is how do I change the existing word list into a input from another player? I think I have to create a play button for the actual game to start how?
Thanks for your time!
from tkinter import messagebox
from tkinter import *
import random
#Setting up the window
window = Tk()
window.title("Välkommen till Rädda Gubbe")
window.geometry("350x250+525+200")
lblspel = Label(window, text="Rädda Gubbe", font=('Arial', '16', 'bold', 'italic'), justify='center', fg='Red'
).pack(side=TOP, anchor=CENTER,pady=7)
Namnlbl = Label(window, text="Skriv in det hemliga ordet: ", font=('Arial', '11', 'bold', 'italic'), justify='center'
).pack(side=TOP,pady=2)
e = Entry(window, font=('Arial', 12), justify='center')
e.pack(side=TOP)
startaspelet = Button(window, text="Starta Spelet", relief="solid", font=("arial", 12, "bold"), command=lambda: spelet).place(x=30, y=70)
def spelet():
window2 = Tk()
window2.title("Rädda Gubbe")
window2.resizable(0, 0)
#Words
word_list = ['FLAMBOYANT','AMBIGUOUS','AMBIVALENT','CHARISMA']
def newGame():
global the_word_withSpaces
global numberOfGuesses
numberOfGuesses=0
the_word=random.choice(word_list)
the_word_withSpaces=" ".join(the_word)
lblWord.set(" ".join("_"*len(the_word)))
def guess(letter):
global numberOfGuesses
if numberOfGuesses<11:
txt=list(the_word_withSpaces)
guessed=list(lblWord.get())
if the_word_withSpaces.count(letter)>0:
for c in range(len(txt)):
if txt[c]==letter:
guessed[c]=letter
lblWord.set("".join(guessed))
if lblWord.get()==the_word_withSpaces:
messagebox.showinfo("Hangman","You guessed it!")
newGame()
else:
numberOfGuesses+=1
if numberOfGuesses==11:
messagebox.showwarning("Hangman","Game over")
lblWord=StringVar()
Label(window, textvariable=lblWord, font=("Consolas 24 bold")).grid(row=0, column=3, columnspan=6, padx=10)
btn1 = Button(window2, text="A",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("A"))
btn1.grid(column=1, row=1)
btn2 = Button(window2, text="B",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("B"))
btn2.grid(column=2, row=1)
btn3 = Button(window2, text="C",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("C"))
btn3.grid(column=3, row=1)
btn4 = Button(window2, text="D",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("D"))
btn4.grid(column=4, row=1)
btn5 = Button(window2, text="E",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("E"))
btn5.grid(column=5, row=1)
btn6 = Button(window2, text="F",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("F"))
btn6.grid(column=6, row=1)
btn7 = Button(window2, text="G",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("G"))
btn7.grid(column=7, row=1)
btn9 = Button(window2, text="H",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("H"))
btn9.grid(column=1, row=2)
btn10 = Button(window2, text="I",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("I"))
btn10.grid(column=2, row=2)
btn11 = Button(window2, text="J",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("J"))
btn11.grid(column=3, row=2)
btn12 = Button(window2, text="K",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("K"))
btn12.grid(column=4, row=2)
btn13 = Button(window2, text="L",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("L"))
btn13.grid(column=5, row=2)
btn14 = Button(window2, text="M",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("M"))
btn14.grid(column=6, row=2)
btn15 = Button(window2, text="N",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("N"))
btn15.grid(column=7, row=2)
btn16 = Button(window2, text="O",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("O"))
btn16.grid(column=1, row=3)
btn17 = Button(window2, text="P",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("P"))
btn17.grid(column=2, row=3)
btn18 = Button(window2, text="Q",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("Q"))
btn18.grid(column=3, row=3)
btn19 = Button(window2, text="R",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("R"))
btn19.grid(column=4, row=3)
btn20 = Button(window2, text="S",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("S"))
btn20.grid(column=5, row=3)
btn21 = Button(window2, text="T",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("T"))
btn21.grid(column=6, row=3)
btn22 = Button(window2, text="U",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("U"))
btn22.grid(column=7, row=3)
btn23 = Button(window2, text="V",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("V"))
btn23.grid(column=1, row=4)
btn24 = Button(window2, text="W",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("W"))
btn24.grid(column=2, row=4)
btn25 = Button(window2, text="X",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("X"))
btn25.grid(column=3, row=4)
btn26 = Button(window2, text="Y",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("Z"))
btn26.grid(column=4, row=4)
btn27 = Button(window2, text="Å",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("Å"))
btn27.grid(column=5, row=4)
btn28 = Button(window2, text="Ä",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("Ä"))
btn28.grid(column=6, row=4)
btn29 = Button(window2, text="Ö",bg="skyBlue", fg="Black",width=3,height=1,font=('Helvetica','20'), command= lambda : guess("Ö"))
btn29.grid(column=7, row=4)
Button(window, text="New\nGame", command=lambda:newGame(), font=("Helvetica 10 bold")).grid(row=3, column=8, sticky="NSWE")
newGame()
window.mainloop()
The easiest way is to create file words.txt where second player can put his words:
File words.txt:
Strength
Perception
Endurance
Charisma
Intelligence
Agility
Luck
Code:
from tkinter import messagebox
from tkinter import *
import random
from string import ascii_uppercase
# Setting up the window
window = Tk()
window.title("Hangman")
window.resizable(0, 0)
def newGame():
global the_word_withSpaces
global numberOfGuesses
numberOfGuesses = 0
with open('words.txt', 'r', encoding='utf-8') as f:
words = [w.strip().upper() for w in f.readlines()]
the_word = random.choice(words)
the_word_withSpaces = " ".join(the_word)
lblWord.set(" ".join("_" * len(the_word)))
def guess(letter):
global numberOfGuesses
if numberOfGuesses < 11:
txt = list(the_word_withSpaces)
guessed = list(lblWord.get())
if the_word_withSpaces.count(letter) > 0:
for c in range(len(txt)):
if txt[c] == letter:
guessed[c] = letter
lblWord.set("".join(guessed))
if lblWord.get() == the_word_withSpaces:
messagebox.showinfo("Hangman", "You guessed it!")
newGame()
else:
numberOfGuesses += 1
if numberOfGuesses == 11:
messagebox.showwarning("Hangman", "Game over")
lblWord = StringVar()
Label(window, textvariable=lblWord, font=("Consolas 24 bold")).grid(row=0, column=3, columnspan=6, padx=10)
btn1 = Button(window, text="A", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("A"))
btn1.grid(column=1, row=1)
btn2 = Button(window, text="B", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("B"))
btn2.grid(column=2, row=1)
btn3 = Button(window, text="C", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("C"))
btn3.grid(column=3, row=1)
btn4 = Button(window, text="D", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("D"))
btn4.grid(column=4, row=1)
btn5 = Button(window, text="E", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("E"))
btn5.grid(column=5, row=1)
btn6 = Button(window, text="F", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("F"))
btn6.grid(column=6, row=1)
btn7 = Button(window, text="G", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("G"))
btn7.grid(column=7, row=1)
btn9 = Button(window, text="H", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("H"))
btn9.grid(column=1, row=2)
btn10 = Button(window, text="I", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("I"))
btn10.grid(column=2, row=2)
btn11 = Button(window, text="J", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("J"))
btn11.grid(column=3, row=2)
btn12 = Button(window, text="K", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("K"))
btn12.grid(column=4, row=2)
btn13 = Button(window, text="L", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("L"))
btn13.grid(column=5, row=2)
btn14 = Button(window, text="M", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("M"))
btn14.grid(column=6, row=2)
btn15 = Button(window, text="N", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("N"))
btn15.grid(column=7, row=2)
btn16 = Button(window, text="O", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("O"))
btn16.grid(column=1, row=3)
btn17 = Button(window, text="P", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("P"))
btn17.grid(column=2, row=3)
btn18 = Button(window, text="Q", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("Q"))
btn18.grid(column=3, row=3)
btn19 = Button(window, text="R", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("R"))
btn19.grid(column=4, row=3)
btn20 = Button(window, text="S", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("S"))
btn20.grid(column=5, row=3)
btn21 = Button(window, text="T", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("T"))
btn21.grid(column=6, row=3)
btn22 = Button(window, text="U", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("U"))
btn22.grid(column=7, row=3)
btn23 = Button(window, text="V", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("V"))
btn23.grid(column=1, row=4)
btn24 = Button(window, text="W", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("W"))
btn24.grid(column=2, row=4)
btn25 = Button(window, text="X", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("X"))
btn25.grid(column=3, row=4)
btn26 = Button(window, text="Y", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("Z"))
btn26.grid(column=4, row=4)
btn27 = Button(window, text="Å", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("Å"))
btn27.grid(column=5, row=4)
btn28 = Button(window, text="Ä", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("Ä"))
btn28.grid(column=6, row=4)
btn29 = Button(window, text="Ö", bg="skyBlue", fg="Black", width=3, height=1, font=('Helvetica', '20'),
command=lambda: guess("Ö"))
btn29.grid(column=7, row=4)
Button(window, text="New\nGame", command=lambda: newGame(), font=("Helvetica 10 bold")).grid(row=3, column=8,
sticky="NSWE")
newGame()
window.mainloop()
Output:
I have coded the basic idea. Add 2 frames one a game_frame and the other home_frame. Now just use .pack and .pack_forget to switch between frames
Here is the sample code (modify this to suit your need)
from tkinter import messagebox
from tkinter import *
from tkinter import ttk
import random
def assignWord(word):
global guess_word, the_word_withSpaces
guess_word = word.upper()
home_frame.pack_forget()
game_frame.pack()
print(guess_word)
guess_var.set(" ".join("_"*len(guess_word)))
the_word_withSpaces = " ".join(word.upper())
def createWord():
global currentPlayer
currentPlayer = playerChoose.get()
top = Toplevel(window)
ent = Entry(top, show='*')
ent.pack()
Button(top, text='Submit', command= lambda : [assignWord(ent.get()), top.destroy()]).pack()
def newGame():
global numberOfGuesses
numberOfGuesses = 0
game_frame.pack_forget()
home_frame.pack()
def guess(btn):
global numberOfGuesses
letter = btn['text']
if numberOfGuesses<11:
txt=list(the_word_withSpaces)
guessed=list(guess_var.get())
if the_word_withSpaces.count(letter)>0:
for c in range(len(txt)):
if txt[c]==letter:
guessed[c]=letter
guess_var.set("".join(guessed))
if guess_var.get()==the_word_withSpaces:
messagebox.showinfo("Hangman",f"{currentPlayer} guessed it!")
newGame()
return
else:
numberOfGuesses+=1
if numberOfGuesses==11:
messagebox.showwarning("Hangman","Game over")
newGame()
window = Tk()
window.title("Välkommen till Rädda Gubbe")
window.geometry("350x250+525+200")
numberOfGuesses = 0
players = ['Player1', 'Player2']
guess_word = "HELLO"
the_word_withSpaces = ''
currentPlayer = players[0]
alpha = [chr(x) for x in range(65,89)]
home_frame = Frame(window)
home_frame.pack()
Label(home_frame, text="Choose the player to enter a word: ").pack()
playerChoose = ttk.Combobox(home_frame, values=players, state='readonly')
playerChoose.set(players[0])
playerChoose.pack()
Button(home_frame, text='Enter word', command=createWord).pack()
game_frame = Frame(window)
guess_var = StringVar()
Label(game_frame, textvariable = guess_var).pack(side=TOP, anchor=CENTER,pady=7)
btn_frame = Frame(game_frame)
btn_frame.pack()
row, column = 0, 0
for x in alpha:
if column%7 == 0:
row += 1
column = 0
btn = Button(btn_frame, text=x)
btn.config(command = lambda b=btn: guess(b))
btn.grid(row=row, column=column)
column += 1
window.mainloop()
Related
from tkinter import *
import pywhatkit
import time
root = Tk()
root.title("whatsapp")
root.geometry('405x1000')
root.resizable(width=0, height=0)
label = Label(root, text="Whatsapp Automation", font='bold', width=40 , fg='white',
bg='black', padx=10, pady=13)
label.grid(row=0, columnspan=3, padx=10, pady=10)
label.place(x=10, y=10)
#form1
label=Label(root, text="whatsapp numbers", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=90)
number_str = StringVar()
entry1 = (Text(root,width=30, textvariable=number_str, bd=6, font=14, borderwidth=6))
entry1.insert(0,"+")
entry1.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry1.place(x=10, y=120)
#form2
label=Label(root, text="الرسالة", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=360)
message_str = StringVar()
entry2 = (Text(root, width=41, textvariable=message_str, bd=6, font=14, borderwidth=6))
entry2.insert(0, "write your message")
entry2.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry2.place(x=10, y=400)
#time
label=Label(root, text="وقت الانتظار24/الساعة", font=20 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=450)
labe4=Label(root, font=20 , fg="white", bg="black")
labe4.grid(row=1, padx=10, pady=10)
labe4.place(x = 220, y=450)
#time function
def localtime():
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
labe4.config(text="localtime:"+current_time)
labe4.after(200, localtime)
localtime()
entry3 = (Entry(root, width=20))
entry3.insert(0, "15")
entry3.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry3.place(x=15, y=490)
entry4 = (Entry(root, width=20))
entry4.insert(0, "20")
entry4.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry4.place(x=150, y=490)
#whatsapp send
def whatsapp():
number = entry1.get()
message = entry2.get()
time1 = int(entry3.get())
time2 = int(entry4.get())
pywhatkit.sendwhatmsg(number, message,time1,time2)
send = Button(root, font="30", width=40, text="ارسال" , fg="black",
bg="gold" , bd=10,
command=whatsapp)
send.grid(row=3, column=1, padx=10, pady=10)
send.place(x = 15 , y = 520)
root.mainloop()
I want to solve this problem without replacing Entry with Text in
#form1
entry1 = (Text(root,width=30, textvariable=number_str, bd=6, font=14, borderwidth=6))
and
entry2 = (Text(root, width=41, textvariable=message_str, bd=6, font=14, borderwidth=6))
I can't solve this problem. Code is not running.
The issue's in:
entry2 = (Text(root, width=41, textvariable=message_str, bd=6, font=14, borderwidth=6))
entry1 = (Text(root,width=30, textvariable=number_str, bd=6, font=14, borderwidth=6))
Try this.
from tkinter import *
import pywhatkit
import time
root = Tk()
root.title("whatsapp")
root.geometry('405x1000')
root.resizable(width=0, height=0)
label = Label(root, text="Whatsapp Automation", font='bold', width=40 , fg='white',
bg='black', padx=10, pady=13)
label.grid(row=0, columnspan=3, padx=10, pady=10)
label.place(x=10, y=10)
#form1
label=Label(root, text="whatsapp numbers", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=90)
number_str = StringVar()
entry1 = Text(root,width=30, bd=6, font=14, borderwidth=6)
entry1.insert('end',"+")
entry1.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry1.place(x=10, y=120)
#form2
label=Label(root, text="الرسالة", font=10 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=360)
message_str = StringVar()
entry2 = (Text(root, width=41, bd=6, font=14, borderwidth=6))
entry2.insert('end', "write your message")
entry2.grid(row=1, column=1, columnspan=1, padx=10, pady=13)
entry2.place(x=10, y=400)
#time
label=Label(root, text="وقت الانتظار24/الساعة", font=20 , fg="white", bg="black")
label.grid(row=1, padx=10, pady=10)
label.place(x = 10, y=450)
labe4=Label(root, font=20 , fg="white", bg="black")
labe4.grid(row=1, padx=10, pady=10)
labe4.place(x = 220, y=450)
#time function
def localtime():
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
labe4.config(text="localtime:"+current_time)
labe4.after(200, localtime)
localtime()
entry3 = (Entry(root, width=20))
entry3.insert(0, "15")
entry3.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry3.place(x=15, y=490)
entry4 = (Entry(root, width=20))
entry4.insert(0, "20")
entry4.grid(row=1, column=1, columnspan=1, padx=5, pady=13)
entry4.place(x=150, y=490)
#whatsapp send
def whatsapp():
number = number_str.get()
message = message_str.get()
time1 = int(entry3.get())
time2 = int(entry4.get())
pywhatkit.sendwhatmsg(number, message,time1,time2)
send = Button(root, font="30", width=40, text="ارسال" , fg="black",
bg="gold" , bd=10,
command=whatsapp)
send.grid(row=3, column=1, padx=10, pady=10)
send.place(x = 15 , y = 520)
root.mainloop()
Output:
]
So my intention is when the user clicks one of the buttons, for the rest of the other buttons not to perform anything even when clicked, so basically to stop the buttons from performing their commands when the user clicks them ONLY if they have clicked in another button previously, I don't know if I expressed myself well so I am sorry if I dind't but here's my code:
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
def test():
def test1():
if ticket == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
def test2():
if ticket == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
def test3():
if ticket == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
ticket = random.randint(1,3)
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=0, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=0, column=2, sticky="e")
button3 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
You can set the state of the other Buttons to DISABLED to grey them out and prevent clicks. This would be the ideal place to use a subclass that keeps track of its instances.
from tkinter import *
import random
screen = Tk()
class MykoButton(Button):
instances = []
def __init__(self, master=None, **kwargs):
super().__init__(master, command=self.run, **kwargs)
self.instances.append(self)
def run(self):
for button in self.instances:
if button is not self:
button.config(state=DISABLED)
if random.randint(1,3) == 1:
self.config(text="RIP", fg="white", bg="red") # update the button
else:
self.config(text="+1", fg="white", bg="green")
def test():
for i in range(3):
button = MykoButton(screen, text="1", fg="white", bg="blue", width=15, height=2)
button.grid(row=0, column=i)
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=1, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
Also, note that I changed your code to update the clicked button, rather than put a new button on top of it.
So I am trying to each time you click one of the buttons that doesn't have the bomb, for the variable "score" to update and immediately being displayed on the bottom. But when I click one of them, the displayed variable is not updated for some reason even though I explicitly said for the "Label" being displayed to have the "text=score". I know my code is quite long and not really efficient but I am a bit new to python and I'm still learning. What could I fix in my code to solve this issue? ANY help is appreciated!
from tkinter import *
import random
screen = Tk()
ticket = random.randint(1,3)
score = 0
def test():
ticket1 = random.randint(1,3)
ticket2 = random.randint(1,3)
def test1():
if ticket1 == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=1, column=0, sticky="w")
else:
button_2 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_2.grid(row=1, column=0, sticky="w")
global score
score += 1
def test2():
if ticket1 == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=1, column=1, sticky="w")
else:
button_4 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_4.grid(row=1, column=1, sticky="w")
global score
score += 1
def test3():
if ticket1 == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=1, column=2, sticky="w")
else:
button_6 = Button(screen, text="+1", fg="white", bg="green", width=15, height=2)
button_6.grid(row=1, column=2, sticky="w")
global score
score += 1
def test4():
if ticket2 == button1:
button_1 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_1.grid(row=0, column=0, sticky="w")
else:
button_2 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_2.grid(row=0, column=0, sticky="w")
global score
score += 2
def test5():
if ticket2 == button2:
button_3 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_3.grid(row=0, column=1, sticky="w")
else:
button_4 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_4.grid(row=0, column=1, sticky="w")
global score
score += 2
def test6():
if ticket2 == button3:
button_5 = Button(screen, text="RIP", fg="white", bg="red", width=15, height=2)
button_5.grid(row=0, column=2, sticky="w")
else:
button_6 = Button(screen, text="+2", fg="white", bg="green", width=15, height=2)
button_6.grid(row=0, column=2, sticky="w")
global score
score += 2
button1 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=1, column=0, sticky="w")
button1 = 1
button2 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=1, column=1, sticky="w"+"e"+"n"+"s")
button2 = 2
button3 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=1, column=2, sticky="e")
button3 = 3
button4 = Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test4)
button4.grid(row=0, column=0, sticky="w")
button4 = 1
button5 = Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test5)
button5.grid(row=0, column=1, sticky="w"+"e"+"n"+"s")
button5 = 2
button6 = Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test6)
button6.grid(row=0, column=2, sticky="e")
button6 = 3
button1 = Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button1.grid(row=8, columnspan=3, sticky="w"+"e"+"n"+"s")
scoreText = Label(screen, text="Score: " + str(score), width=25, height=2)
scoreText.grid(row=9, columnspan=3, sticky="w"+"e"+"n"+"s")
screen.mainloop()
After you change score you have to replace text in label
score += 1
scoreText['text'] = "Score: " + str(score)
Full code which replaces text in buttons instead of creating new ones.
import tkinter as tk
import random
def test():
def test1():
global score
if ticket1 == 1:
button1.config(text="RIP", bg="red")
else:
button1.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test2():
global score
if ticket1 == 2:
button2.config(text="RIP", bg="red")
else:
button2.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test3():
global score
if ticket1 == 3:
button3.config(text="RIP", bg="red")
else:
button3.config(text="+1", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test4():
global score
if ticket2 == 1:
button4.config(text="RIP", bg="red")
else:
button4.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test5():
global score
if ticket2 == 2:
button5.config(text="RIP", bg="red")
else:
button5.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
def test6():
global score
if ticket2 == 3:
button6.config(text="RIP", bg="red")
else:
button6.config(text="+2", bg="green")
score += 1
label_score['text'] = "Score: " + str(score)
ticket1 = random.randint(1, 3)
ticket2 = random.randint(1, 3)
button1 = tk.Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test1)
button1.grid(row=1, column=0, sticky="w")
button2 = tk.Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test2)
button2.grid(row=1, column=1, sticky="wens")
button3 = tk.Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test3)
button3.grid(row=1, column=2, sticky="e")
button4 = tk.Button(screen, text="1", fg="white", bg="blue", width=15, height=2, command=test4)
button4.grid(row=0, column=0, sticky="w")
button5 = tk.Button(screen, text="2", fg="white", bg="blue", width=15, height=2, command=test5)
button5.grid(row=0, column=1, sticky="wens")
button6 = tk.Button(screen, text="3", fg="white", bg="blue", width=15, height=2, command=test6)
button6.grid(row=0, column=2, sticky="e")
# --- main --
score = 0
screen = tk.Tk()
button_start = tk.Button(screen, text="START", fg="black", bg="orange", width=25, height=2, command=test)
button_start.grid(row=8, columnspan=3, sticky="wens")
label_score = tk.Label(screen, text="Score: 0", width=25, height=2)
label_score.grid(row=9, columnspan=3, sticky="wens")
screen.mainloop()
I have been doing a python app for a calculator with Tkinter. I want to know how access the buttons properties such as their size, height, width and color by the use of strings. So far I have been able to change the background of the lines behind the buttons to red by using style.configure("TButton", background='red',
font="Serif 15",
padding=10 ).
How do I change the buttons themselves? If anyone could help me I would greatly appreciate it.
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk
class Calculator:
calc_value = 0.0
div_trigger = False
mult_trigger = False
add_trigger = False
sub_trigger = False
def __init__(self,root):
self.entry_value = StringVar(root,value="")
root.title("Calculator")
root.geometry("600x500")
root.resizable(width=True, height=True)
style = ttk.Style()
style.configure(self, background='red')
style.configure("TButton", #background='red',
font="Serif 15",
padding=10 )
style.configure("TEntry",
font="Serif 15",
padding=10 )
self.number_entry = ttk.Entry(root,
textvariable=self.entry_value,width=50)
self.number_entry.grid(row=0, columnspan=4)
#-------1st row---------
self.button7 = ttk.Button(root, text="7",
command=lambda: self.button_press('7')).grid(row=1, column=0)
self.button8 = ttk.Button(root, text="8",
command=lambda: self.button_press('8')).grid(row=1, column=1)
self.button9 = ttk.Button(root, text="9",
command=lambda: self.button_press('9')).grid(row=1, column=2)
self.button_div = ttk.Button(root, text="/",
command=lambda: self.button_press('/')).grid(row=1, column=3)
#-------2nd row---------
self.button4 = ttk.Button(root, text="4",
command=lambda: self.button_press('4')).grid(row=2, column=0)
self.button5 = ttk.Button(root, text="5",
command=lambda: self.button_press('5')).grid(row=2, column=1)
self.button6 = ttk.Button(root, text="6",
command=lambda: self.button_press('6')).grid(row=2, column=2)
self.button_mult = ttk.Button(root, text="*",
command=lambda: self.button_press('*')).grid(row=2, column=3)
#-------3rd row---------
self.button1 = ttk.Button(root, text="1",
command=lambda: self.button_press('1')).grid(row=4, column=0)
self.button2 = ttk.Button(root, text="2",
command=lambda: self.button_press('2')).grid(row=4, column=1)
self.button3 = ttk.Button(root, text="3",
command=lambda: self.button_press('3')).grid(row=4, column=2)
self.button_add = ttk.Button(root, text="+",
command=lambda: self.button_press('+')).grid(row=4, column=3)
#-------4th row---------
self.button_clear = ttk.Button(root, text="AC",
command=lambda: self.button_press('AC')).grid(row=5, column=0)
self.button0 = ttk.Button(root, text="0",
command=lambda: self.button_press('0')).grid(row=5, column=1)
self.button_equal = ttk.Button(root, text="=",
command=lambda: self.button_press('=')).grid(row=5, column=2)
self.button_sub = ttk.Button(root, text="-",
command=lambda: self.button_press('-')).grid(row=5, column=3)
root = Tk()
calc = Calculator(root)
root.mainloop()
#button1 = Button(topframe,padx=16, pady=16, bd=8, text="1", fg="black", bg = random.choice(colors))
Here are documentatiopn about that.
http://effbot.org/tkinterbook/button.htm
If you want to change a botton size you can use.
button1.config(height = 100, width = 100)
My code for my messagebox won't work on my window. Everything else works but when I run it my "About" messagebox won't show up. I want my messagebox to pop out when "About" is clicked on my window. What can I do to make it work?
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("Calculator")
calculator.geometry("317x145")
menubar = Menu(calculator)
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
display = Frame(calculator, bd=0, width=1000, height=1000, relief=SUNKEN)
buttons = Frame(calculator, bd=0, width=7, height=1, relief=GROOVE)
display.grid(column=0, row=0, padx=0, pady=0)
buttons.grid(column=0, row=1, padx=1)
numbers = StringVar()
self.results = Entry(display, textvariable=numbers, width=31, fg="DarkOrchid4", bg="lavender blush", font="Verdana")
self.results.pack()
self.results.grid(column=0, row=0)
def showup(x):
return lambda: self.results.insert(END, x)
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for i in range(9):
n=numbers[i]
Button(buttons, bg="snow", text=n, width=7, height=1, command=showup(n), relief=RAISED).grid(row=i%3, column=i//3)
Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
Clear.grid(padx=2, pady=2, column=3, row=0)
Equals = Button(buttons, bg="snow", text="=", width=7, height=1, command=self.equals, relief=RAISED)
Equals.grid(padx=2, pady=2, column=4, row=3)
All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
All_clear.grid(padx=2, pady=2, column=4, row=0)
Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
Bracket_one.grid(padx=2, pady=2, column=2, row=3)
Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
Bracket_two.grid(padx=2, pady=2, column=3, row=3)
Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
Zero.grid(padx=2, pady=2, column=0, row=3)
Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
Decimal_point.grid(padx=2, pady=2, column=1, row=3)
Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
Multiplication.grid(padx=2, pady=2, column=3, row=1)
Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
Division.grid(padx=2, pady=2, column=4, row=1)
Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
Addition.grid(padx=2, pady=2, column=3, row=2)
Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
Subtraction.grid(padx=2, pady=2, column=4, row=2)
def equals(self):
try:
result = eval(self.results.get())
except:
result = "Invalid input"
self.all_clear()
self.results.insert(0, result)
def zero(self):
self.results.insert(END, "0")
def bracket_one(self):
self.results.insert(END, "(")
def bracket_two(self):
self.results.insert(END, ")")
def all_clear(self):
self.results.delete(0, END)
def clear(self):
self.results.delete(-1)
def multiplication(self):
self.results.insert(END, "*")
def division(self):
self.results.insert(END, "/")
def addition(self):
self.results.insert(END, "+")
def subtraction(self):
self.results.insert(END, "-")
def decimal_point(self):
self.results.insert(END, ".")
def about():
messagebox.showinfo(title = "About", message = "Author")
return
helpMenu = Menu(menubar)
menubar.add_command(label = "About", command=about)
if __name__ == '__main__':
Calculator().mainloop()
calculator.config(menu=menubar)
calculator.mainloop()
Your issue is that you are not associating the menubar with your root application. That is why it is never coming up. You need to configure the menu for your application to be the menubar you create. Example -
calculator.configure(menu=menubar)
Also, it would be better to move that code inside you frame as well. Example -
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("Calculator")
calculator.geometry("317x145")
menubar = Menu(calculator)
class Calculator(Frame):
def __init__(self):
Frame.__init__(self)
display = Frame(calculator, bd=0, width=1000, height=1000, relief=SUNKEN)
buttons = Frame(calculator, bd=0, width=7, height=1, relief=GROOVE)
display.grid(column=0, row=0, padx=0, pady=0)
buttons.grid(column=0, row=1, padx=1)
numbers = StringVar()
self.results = Entry(display, textvariable=numbers, width=31, fg="DarkOrchid4", bg="lavender blush", font="Verdana")
self.results.pack()
self.results.grid(column=0, row=0)
def showup(x):
return lambda: self.results.insert(END, x)
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for i in range(9):
n=numbers[i]
Button(buttons, bg="snow", text=n, width=7, height=1, command=showup(n), relief=RAISED).grid(row=i%3, column=i//3)
Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
Clear.grid(padx=2, pady=2, column=3, row=0)
Equals = Button(buttons, bg="snow", text="=", width=7, height=1, command=self.equals, relief=RAISED)
Equals.grid(padx=2, pady=2, column=4, row=3)
All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
All_clear.grid(padx=2, pady=2, column=4, row=0)
Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
Bracket_one.grid(padx=2, pady=2, column=2, row=3)
Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
Bracket_two.grid(padx=2, pady=2, column=3, row=3)
Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
Zero.grid(padx=2, pady=2, column=0, row=3)
Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
Decimal_point.grid(padx=2, pady=2, column=1, row=3)
Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
Multiplication.grid(padx=2, pady=2, column=3, row=1)
Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
Division.grid(padx=2, pady=2, column=4, row=1)
Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
Addition.grid(padx=2, pady=2, column=3, row=2)
Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
Subtraction.grid(padx=2, pady=2, column=4, row=2)
self.menubar = Menu(self)
def about():
messagebox.showinfo(title = "About", message = "Author")
return
self.helpMenu = Menu(self.menubar)
self.menubar.add_cascade(label="Help",menu=self.helpMenu)
self.helpMenu.add_command(label = "About", command=about)
calculator.config(menu=self.menubar)
def equals(self):
try:
result = eval(self.results.get())
except:
result = "Invalid input"
self.all_clear()
self.results.insert(0, result)
def zero(self):
self.results.insert(END, "0")
def bracket_one(self):
self.results.insert(END, "(")
def bracket_two(self):
self.results.insert(END, ")")
def all_clear(self):
self.results.delete(0, END)
def clear(self):
self.results.delete(-1)
def multiplication(self):
self.results.insert(END, "*")
def division(self):
self.results.insert(END, "/")
def addition(self):
self.results.insert(END, "+")
def subtraction(self):
self.results.insert(END, "-")
def decimal_point(self):
self.results.insert(END, ".")
if __name__ == '__main__':
Calculator().mainloop()
calculator.config(menu=menubar)
calculator.mainloop()