Messagebox not working - python

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()

Related

How to solve the "bad window path name ".!labelframe.!canvas.!frame" error in tkinter python?

This is my code:
mycanvas = Canvas(self.search_result_frame)
mycanvas.pack(side=LEFT)
yscrollbar = ttk.Scrollbar(self.search_result_frame, orient="vertical", command=mycanvas.yview)
yscrollbar.pack(side=RIGHT, fill=Y)
mycanvas.configure(yscrollcommand=yscrollbar.set)
mycanvas.bind('<Configure>', lambda e: mycanvas.configure(scrollregion = mycanvas.bbox('all')))
self.sample_frame = Frame(mycanvas)
mycanvas.create_window((0,0), window=self.sample_frame, anchor=E)
for widget in self.search_result_frame.winfo_children():
widget.destroy()
if len(matching_bills) > 0:
for bill in matching_bills:
with open(f'{self.bill_folder}//{bill}//data//bill_details.json', 'r') as bill_json_file:
bill_details = json.loads(bill_json_file.read())
customer_name = bill_details["customer_details"][0]
payment_method = bill_details["payment_method"]
date_of_issue = bill_details["date_of_issue"]
date_of_issue = datetime.strptime(date_of_issue, "%d/%m/%Y")
date_of_issue = date_of_issue.strftime("%d %b %Y")
# # -------------------- Search Result Frame Contents
result_frame = Frame(self.sample_frame, bg=self.bg3, bd=5, relief=GROOVE)
result_frame.pack(fill=BOTH, pady=2)
result_billno_lbl = Label(result_frame, text=bill, bg=self.bg1, fg="#FFF", font=self.search_results_font1, padx=22, pady=3)
result_billno_lbl.grid(row=0, column=0, padx=50, pady=8, sticky=W)
billed_to_lbl = Label(result_frame, text=f"Billed To - {customer_name}", bg=self.bg1, fg="#FFF", font=self.search_results_font2, bd=2, relief=RAISED, padx=12, pady=3)
billed_to_lbl.grid(row=0, column=1, padx=80, sticky=W)
billed_type_lbl = Label(result_frame, text=f"Bill Type - {payment_method}", bg=self.bg1, fg="#FFF", font=self.search_results_font2, bd=2, relief=RAISED, padx=12, pady=3)
billed_type_lbl.grid(row=0, column=2, sticky=W)
issued_on_lbl = Label(result_frame, text=f"Issued On - {date_of_issue}", bg=self.bg1, fg="#FFF",
font=self.search_results_font2, bd=2, relief=RAISED, padx=12, pady=3)
issued_on_lbl.grid(row=0, column=3, padx=80, sticky=W)
view_btn = Button(result_frame, text="View", font="Comicsan 14", bd=2, relief=GROOVE, bg="#000", fg="#FFF", padx=1, command=lambda bill=bill: self.view_bill(bill))
view_btn.grid(row=0, column=4, padx=3, columnspan=2, sticky=W)
elif len(matching_bills) == 0:
for widgets in self.search_result_frame.winfo_children():
widgets.destroy()
no_result_lbl = Label(self.search_result_frame, text=f"No search result found for {bill_cat}", font=self.search_results_font1, bg=self.bg3, fg="#FFF")
no_result_lbl.pack(fill=X)
When I run it, it shows me the bad window path name ".!labelframe.!canvas.!frame error and when I try to do the same thing without object-oriented in tkinter then it works well !

Hangman turn into two player game Tkinter Python

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()

Link between two scripts on a button click in tkinter?

I have two files in my directory (first.py and second.py). The first.py has a button. So on clicking the button in first.py gui window, it should be directed to second.py gui window.
first.py window photo and second.py window photo. So on clicking the sign up button in the first.py, it should go to the sign up page in second.py.
How to do the connection or linking between the two scripts?
first.py
import tkinter as tk
root=tk.Tk()
root.title("My Bank")
root.geometry("500x500")
photo=tk.PhotoImage(file="image1.gif")
label = tk.Label(root, image=photo)
label.image = photo
label.pack()
label.place(x=0, y=0, relwidth=1, relheight=1)
tfm = tk.Frame(root, width=2000, height=50)
tfm.pack(side=tk.TOP)
w = tk.Label(tfm, text="MY bank", font=("Times", "24", "bold"), bg="yellow", anchor="e", fg="black", padx=350, pady=10)
w.pack(fill="both")
bfm = tk.Frame(root, width=2000, height=50, bg="gray")
bfm.pack(side=tk.BOTTOM)
w = tk.Label(root, text="Main Menu", font=("Times", "24", "bold"), bg="black", fg="white", padx=350, pady=10)
w.pack(padx=10, pady=30)
button1 = tk.Button(root, text="Sign Up", width=12, height=1, bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button1.pack(padx=10, pady=10)
button2 = tk.Button(root, text="Sign In", width=12, height=1,
bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button2.pack(padx=10, pady=10)
button3 = tk.Button(root, text="Admin Sign In", width=12, height=1, bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button3.pack(padx=10, pady=10)
button4 = tk.Button(root, text="Quit!", width=5, height=1, bg="black",fg="white", bd="10", font=("Helvetica", "12", "bold"))
button4.pack(padx=10, pady=10)
root.mainloop()
second.py
import tkinter as tk
root=tk.Tk()
root.title("My Bank")
root.geometry("500x500")
photo=tk.PhotoImage(file="image1.gif")
label = tk.Label(root, image=photo)
label.image = photo
label.pack()
label.place(x=0, y=0, relwidth=1, relheight=1)
tfm = tk.Frame(root, width=2000, height=50)
tfm.pack(side=tk.TOP)
w = tk.Label(tfm, text="MY bank", font=("Times", "24", "bold"), bg="yellow", anchor="e", fg="black", padx=350, pady=10)
w.pack(fill="both")
bfm = tk.Frame(root, width=2000, height=50, bg="gray")
bfm.pack(side=tk.BOTTOM)
w = tk.Label(root, text="Sign Up", font=("Times", "24", "bold"), bg="black", fg="white", padx=350, pady=10)
w.pack(padx=10, pady=30)
e1 = tk.Entry(root, width=20, font=("Times", "14", "bold"), bd=3, fg="blue")
e1.insert(0, 'Username')
e1.pack(padx=150, pady=10)
e2 = tk.Entry(root, width=20, font=("Times", "14", "bold"), bd=3, fg="blue")
e2.insert(0, 'Email')
e2.pack(padx=150, pady=10)
e3 = tk.Entry(root, width=20, font=("Times", "14", "bold"), bd=3, fg="blue")
e3.insert(0, 'Password')
e3.pack(padx=150, pady=10)
button1 = tk.Button(root, text="Sign Up", width=12, height=1, bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button1.pack(padx=100, pady=20)
root.mainloop()
I went through your problem and I guess you want to open another file when the button is clicked. To do this you need to import the file which you want to load on button click. And create another tkinter function in the external script. While running through your code i even came across the error which is tkinter.TclError: image "pyimage3" doesn't exist as of now I even fixed this for more information visit this link. Here is the code which i made all the changes.
"""
Spyder Editor
This is a temporary script file.
"""
import second
import tkinter as tk
root=tk.Toplevel()
root.title("My Bank")
root.geometry("500x500")
photo=tk.PhotoImage(file="image1.gif")
label = tk.Label(root, image=photo)
label.image = photo
label.pack()
label.place(x=0, y=0, relwidth=1, relheight=1)
tfm = tk.Frame(root, width=2000, height=50)
tfm.pack(side=tk.TOP)
w = tk.Label(tfm, text="MY bank", font=("Times", "24", "bold"), bg="yellow", anchor="e", fg="black", padx=350, pady=10)
w.pack(fill="both")
bfm = tk.Frame(root, width=2000, height=50, bg="gray")
bfm.pack(side=tk.BOTTOM)
w = tk.Label(root, text="Main Menu", font=("Times", "24", "bold"), bg="black", fg="white", padx=350, pady=10)
w.pack(padx=10, pady=30)
button1 = tk.Button(root, text="Sign Up", command=lambda : second.signup() , width=12, height=1, bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button1.pack(padx=10, pady=10)
button2 = tk.Button(root, text="Sign In", width=12, height=1,
bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button2.pack(padx=10, pady=10)
button3 = tk.Button(root, text="Admin Sign In", width=12, height=1, bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button3.pack(padx=10, pady=10)
button4 = tk.Button(root, text="Quit!", width=5, height=1, bg="black",fg="white", bd="10", font=("Helvetica", "12", "bold"))
button4.pack(padx=10, pady=10)
root.mainloop()
and the other one
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 7 11:09:28 2018
#author: kedar
"""
import tkinter as tk
def signup():
root=tk.Toplevel()
root.title("My Bank")
root.geometry("500x500")
photo=tk.PhotoImage(file="image1.gif")
label = tk.Label(root, image=photo)
label.image = photo
label.pack()
label.place(x=0, y=0, relwidth=1, relheight=1)
tfm = tk.Frame(root, width=2000, height=50)
tfm.pack(side=tk.TOP)
w = tk.Label(tfm, text="MY bank", font=("Times", "24", "bold"), bg="yellow", anchor="e", fg="black", padx=350, pady=10)
w.pack(fill="both")
bfm = tk.Frame(root, width=2000, height=50, bg="gray")
bfm.pack(side=tk.BOTTOM)
w = tk.Label(root, text="Sign Up", font=("Times", "24", "bold"), bg="black", fg="white", padx=350, pady=10)
w.pack(padx=10, pady=30)
e1 = tk.Entry(root, width=20, font=("Times", "14", "bold"), bd=3, fg="blue")
e1.insert(0, 'Username')
e1.pack(padx=150, pady=10)
e2 = tk.Entry(root, width=20, font=("Times", "14", "bold"), bd=3, fg="blue")
e2.insert(0, 'Email')
e2.pack(padx=150, pady=10)
e3 = tk.Entry(root, width=20, font=("Times", "14", "bold"), bd=3, fg="blue")
e3.insert(0, 'Password')
e3.pack(padx=150, pady=10)
button1 = tk.Button(root, text="Sign Up", width=12, height=1, bg="black",fg="white", bd="8", font=("Helvetica", "12", "bold"))
button1.pack(padx=100, pady=20)
root.mainloop()
For now you can just copy this and use it. I hope it helps.

How do I stop a button command when another button is clicked in python?

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.

How to make math work on my calculator created in Python with TKinter?

This is my code for my calculator. I can't figure out how to make the + - / * perform their functions... I was thinking something with If statements in my Equals function?
from Tkinter import*
calculator = Tk()
calculator.title('Calcualtor')
calculator.geometry('300x325')
screen = Frame(calculator, bd=2, width=250, height=25, relief=SUNKEN)
buttons = Frame(calculator, bd=2, width=250, height=200)
screen.grid(column=0, row=0, padx=25, pady=25)
buttons.grid(column=0, row=1, padx=25)
def appear(x):
return lambda: results.insert(END, x)
def Zero():
results.insert(END, "0")
return
def Math():
number= results.get()
results.delete(0, END)
number2=results.get()
return
def Equals():
numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
for index in range(9):
n=numbers[index]
Button(buttons, bg="White", text=n, width=5, height=2, command=appear(n)).grid(padx=5, pady=5, row=index%3, column=index/3)
zero= Button(buttons, bg="White", text="0", width=5, height=2, command=Zero)
zero.grid(padx=5, pady=5, column=1, row=3)
functions=["-", "+", "*", "/"]
for index in range(4):
f=functions[index]
Button(buttons, bg="White", text=f, width=5, height=2, command=Math).grid(padx=5, pady=5, row=index%4, column=3)
equals= Button(buttons, bg="White", text="=", width=5, height=2, command=Equals)
equals.grid(ipadx=10, pady=5, row=5, column=1)
numbers = StringVar()
results = Entry(screen, textvariable=numbers, width=30)
results.pack()
calculator.mainloop()
The easiest solution would be to use eval() and let python do all the work for you. Just add +-/* to the text entry as you do with the numbers and then use the equals button to evaluate the text in the text entry.
Make the following changes:
def Equals():
try:
result = eval(results.get())
except:
result = "Invalid sum"
results.delete(0, END)
results.insert(0, result)
....
Button(buttons, bg="White", text=f, width=5, height=2, command=appear(f)).grid(padx=5, pady=5, row=index%4, column=3)
You should also disable the text entry so a malicious user is unable to execute code.

Categories

Resources