In this practice program, I have created a Color Game. In this I have created a Button called Start Game. Game should start only after I press Start Game button. This button also disappears when game starts. It works perfectly first time. But when countdown gets over or when the player lose, Start Game button should reappear in same place. Start Button is reappearing, but it is calling the function as it should be. please anyone help?
from tkinter import *
from random import *
doc = open("Highscore.txt", "r")
us = 0
hs = int(doc.read())
time_count = 5
colorlist = ["Red", "Yellow", "Blue", "Green", "Orange", "Purple"]
def add_uscore():
global us
us+= 1
score.config(text=(f"Score: {us}"))
def add_highscore():
global us
global hs
if us>hs:
hs = us
highscore.config(text=(f"Highscore: {hs}"))
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
def start_game():
global colorlist
global textcolor
rancolor = choice(colorlist)
textcolor = choice(colorlist)
start_btn.grid_forget()
color.config(text=rancolor, fg=textcolor)
btn1.config(state=ACTIVE, bg="Indian Red")
btn2.config(state=ACTIVE, bg="Gold")
btn3.config(state=ACTIVE, bg="DodgerBlue3")
btn4.config(state=ACTIVE, bg="Sea Green")
btn5.config(state=ACTIVE, bg="Dark Orange")
btn6.config(state=ACTIVE, bg="Purple3")
timer.grid(row=4, column=0, columnspan=3)
def countdown():
global time_count
if time_count > 0:
time_count -= 1
timer.config(text=(f"Countdown: {time_count}"))
timer.after(1000, countdown)
elif time_count==0:
result.config(text="Time Over", fg="Indian Red")
finish_game()
def finish_game():
timer.grid_forget()
start_btn.grid(row=4, column=0, columnspan=3)
btn1.config(state=DISABLED)
btn2.config(state=DISABLED)
btn3.config(state=DISABLED)
btn4.config(state=DISABLED)
btn5.config(state=DISABLED)
btn6.config(state=DISABLED)
def new_game():
global us
us = 0
score.config(text=(f"Score: {us}"))
finish_game()
def reset_game():
global hs
hs = 0
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
new_game()
def check(ucolor):
global textcolor
global time_count
if textcolor==ucolor:
result.config(text="Good", fg="Sea Green")
add_uscore()
add_highscore()
start_game()
time_count = 5
else:
result.config(text="You Lose", fg="Indian Red")
finish_game()
win = Tk()
win.title("Color Game")
#MENU
menu1 = Menu(win)
win.config(menu=menu1)
options = Menu(menu1)
menu1.add_cascade(label="Option", menu=options)
options.add_command(label="New Game", command=new_game)
options.add_command(label="Reset Game", command=reset_game)
options.add_command(label="Exit Game", command=quit)
#DISPLAY
color = Label(win, text="", font=("Comic Sans", 50), anchor=W)
color.grid(row=0, column=0, columnspan=4)
#BUTTON
btn1 = Button(win, text="Red", height=10, width=10, state=DISABLED, command=lambda:check("Red"))
btn1.grid(row=1, column=0)
btn2 = Button(win, text="Yellow", height=10, width=10,state=DISABLED, command=lambda:check("Yellow"))
btn2.grid(row=1, column=1)
btn3 = Button(win, text="Blue", height=10, width=10, state=DISABLED, command=lambda:check("Blue"))
btn3.grid(row=1, column=2)
btn4 = Button(win, text="Green", height=10, width=10, state=DISABLED, command=lambda:check("Green"))
btn4.grid(row=2, column=0)
btn5 = Button(win, text="Orange", height=10, width=10, state=DISABLED, command=lambda:check("Orange"))
btn5.grid(row=2, column=1)
btn6 = Button(win, text="Purple", height=10, width=10, state=DISABLED, command=lambda:check("Purple"))
btn6.grid(row=2, column=2)
#RESULT
result = Label(win, text="", font=("Ariel", 25))
result.grid(row=3, column=0, columnspan=3)
#COUNTDOWN
timer = Label(win, text="", fg="Dark Orange", font=("Ariel", 15))
#START BUTTON
start_btn = Button(win, text="START GAME", bg="Green", command= lambda: [start_game(), countdown()])
start_btn.grid(row=4, column=0, columnspan=3)
#SCORE
score = Label(win, text=(f"Score: {us}"), fg="Sea Green", font=("Ariel", 10))
score.grid(row=5, column=0, columnspan=3)
#HIGHSCORE
highscore = Label(win, text=(f"Highscore: {hs}"), font=("Ariel", 10), fg="firebrick4")
highscore.grid(row=6, column=0, columnspan=3)
win.mainloop()
In your code there is a variable time_count
It is set as 5 in the beginning of the code
...
hs = int(doc.read())
time_count = 5 # <-----------
colorlist = ["Red", "Yellow", "Blue", "Green", "Orange", "Purple"]
...
When you run out of time, time_count has a value of 0. When you call the start_game function again, it sees that time_count is 0 and so the game must be over. To fix this, you'd have to reset time_count after each time the game ends. Something like this worked for me:
def finish_game():
global time_sleep
time_sleep = 5
timer.grid_forget()
start_btn.grid(row=4, column=0, columnspan=3)
btn1.config(state=DISABLED)
btn2.config(state=DISABLED)
btn3.config(state=DISABLED)
btn4.config(state=DISABLED)
btn5.config(state=DISABLED)
btn6.config(state=DISABLED)
Edit:
I managed to fix the countdown function executing on its own in the background by adding a gameover variable. When the game ends, it is set to 1, when the game starts it is again set to 0. The countdown function checks gameover and only executes when it is set to 0.
I also made the result label only appear when the game is over.
The full code:
from tkinter import *
from random import *
doc = open("Highscore.txt", "r")
us = 0
hs = int(doc.read())
time_count = 5
colorlist = ["Red", "Yellow", "Blue", "Green", "Orange", "Purple"]
def add_uscore():
global us
us+= 1
score.config(text=(f"Score: {us}"))
def add_highscore():
global us
global hs
if us>hs:
hs = us
highscore.config(text=(f"Highscore: {hs}"))
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
def start_game():
global gameover
global colorlist
global textcolor
gameover = 0
rancolor = choice(colorlist)
textcolor = choice(colorlist)
start_btn.grid_forget()
result.grid_forget()
color.config(text=rancolor, fg=textcolor)
btn1.config(state=ACTIVE, bg="Indian Red")
btn2.config(state=ACTIVE, bg="Gold")
btn3.config(state=ACTIVE, bg="DodgerBlue3")
btn4.config(state=ACTIVE, bg="Sea Green")
btn5.config(state=ACTIVE, bg="Dark Orange")
btn6.config(state=ACTIVE, bg="Purple3")
timer.grid(row=4, column=0, columnspan=3)
def countdown():
global time_count
if time_count > 0 and gameover != 1:
time_count -= 1
timer.config(text=(f"Countdown: {time_count}"))
timer.after(1000, countdown)
elif time_count==0:
result.config(text="Time Over", fg="Indian Red")
finish_game()
def finish_game():
global time_count
time_count = 5
timer.grid_forget()
result.grid(row=3, column=0, columnspan=3)
start_btn.grid(row=4, column=0, columnspan=3)
btn1.config(state=DISABLED)
btn2.config(state=DISABLED)
btn3.config(state=DISABLED)
btn4.config(state=DISABLED)
btn5.config(state=DISABLED)
btn6.config(state=DISABLED)
def new_game():
global us
us = 0
score.config(text=(f"Score: {us}"))
finish_game()
def reset_game():
global hs
hs = 0
doc2 = open("Highscore.txt","w")
doc2.write(str(hs))
doc2.close()
new_game()
def check(ucolor):
global textcolor
global time_count
global gameover
if textcolor==ucolor:
result.config(text="Good", fg="Sea Green")
add_uscore()
add_highscore()
start_game()
time_count = 5
else:
result.config(text="You Lose", fg="Indian Red")
gameover = 1
finish_game()
win = Tk()
win.title("Color Game")
#MENU
menu1 = Menu(win)
win.config(menu=menu1)
options = Menu(menu1)
menu1.add_cascade(label="Option", menu=options)
options.add_command(label="New Game", command=new_game)
options.add_command(label="Reset Game", command=reset_game)
options.add_command(label="Exit Game", command=quit)
#DISPLAY
color = Label(win, text="", font=("Comic Sans", 50), anchor=W)
color.grid(row=0, column=0, columnspan=4)
#BUTTON
btn1 = Button(win, text="Red", height=10, width=10, state=DISABLED, command=lambda:check("Red"))
btn1.grid(row=1, column=0)
btn2 = Button(win, text="Yellow", height=10, width=10,state=DISABLED, command=lambda:check("Yellow"))
btn2.grid(row=1, column=1)
btn3 = Button(win, text="Blue", height=10, width=10, state=DISABLED, command=lambda:check("Blue"))
btn3.grid(row=1, column=2)
btn4 = Button(win, text="Green", height=10, width=10, state=DISABLED, command=lambda:check("Green"))
btn4.grid(row=2, column=0)
btn5 = Button(win, text="Orange", height=10, width=10, state=DISABLED, command=lambda:check("Orange"))
btn5.grid(row=2, column=1)
btn6 = Button(win, text="Purple", height=10, width=10, state=DISABLED, command=lambda:check("Purple"))
btn6.grid(row=2, column=2)
#RESULT
result = Label(win, text="", font=("Ariel", 25))
#COUNTDOWN
timer = Label(win, text="", fg="Dark Orange", font=("Ariel", 15))
#START BUTTON
start_btn = Button(win, text="START GAME", bg="Green", command= lambda: [start_game(), countdown()])
start_btn.grid(row=4, column=0, columnspan=3)
#SCORE
score = Label(win, text=(f"Score: {us}"), fg="Sea Green", font=("Ariel", 10))
score.grid(row=5, column=0, columnspan=3)
#HIGHSCORE
highscore = Label(win, text=(f"Highscore: {hs}"), font=("Ariel", 10), fg="firebrick4")
highscore.grid(row=6, column=0, columnspan=3)
win.mainloop()
Notice how the result label is only placed with the grid manager when the game ends and it is removed once the game starts again:
Placing the result label with .grid when the game ends
def finish_game():
...
result.grid(row=3, column=0, columnspan=3)
...
Removing the result label with .grid_forget when the game starts
def start_game():
...
result.grid_forget()
...
Related
I'm making a wrong-word corrector so I use replace method, but it doesn't work
because it is not all same word.
For example:
string = i like icecream
I want to change the word = icecream
It only works for "i like icecream" if it is all the same
This is my whole code:
# coding: utf-8
from tkinter import *
import tkinter.messagebox
root=Tk()
root.title("words corrector")
root.resizable(0, 0)
root.geometry("+{}+{}".format(600, 400))
mainFrame = Frame(root, width=600, height=400)
mainFrame.pack()
textFrame = Frame(mainFrame, width=100, height=100)
textFrame.pack()
textFrame_1 = Frame(mainFrame, width=100, height=100)
textFrame_1.pack()
textFrame_2 = Frame(mainFrame,width=100, height=100)
textFrame_2.pack()
scrollbar = Scrollbar(textFrame)
scrollbar.pack(side=RIGHT, fill="y")
#textField == sentance
textField = Text(textFrame, width=50, height=10, bd=5, relief="groove")
textField.insert(CURRENT,"enter the text\n")
textField.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField["yscrollcommand"] = scrollbar.set
#textField_2 == wrong word
textField_2= Text(textFrame_1, width=15, height=3, bd=5, relief="groove")
textField_2.insert(CURRENT,"wrong words\n")
textField_2.pack(side=LEFT, padx=(5,0), pady=(5,5))
#textField_3 == correct word
textField_3= Text(textFrame_1,width=15, height=3, bd=5, relief="groove")
textField_3.insert(CURRENT, "correct words\n")
textField_3.pack(side=LEFT, padx=(5,0), pady=(5,5))
def chg():
sentance = textField.get("1.0",END)
wrong_word = textField_2.get("1.0",END)
correct_word = textField_3.get("1.0",END)
result = sentance.replace(wrong_word,correct_word)
textField_4.insert("1.0",result)
def msg():
tkinter.messagebox.showerror("error","there's no words")
def ok():
if textField_2.get("1.0",END) in textField.get("1.0",END):
chg()
else:
msg()
okButton = Button(textFrame_1, text="OK", command=ok)
okButton.pack(padx=40, pady=(20,5))
scrollbar_2 = Scrollbar(textFrame_2)
scrollbar_2.pack(side=RIGHT, fill="y")
textField_4 = Text(textFrame_2, width=50, height=10, bd=5, relief="groove")
textField_4.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField_4["yscrollcommand"] = scrollbar.set
root.mainloop()
Try the following code. You have to convert unicode characters to a string and use str.replace.
from tkinter import *
import tkinter.messagebox
root=Tk()
root.title("words corrector")
root.resizable(0, 0)
root.geometry("+{}+{}".format(600, 400))
mainFrame = Frame(root, width=600, height=400)
mainFrame.pack()
textFrame = Frame(mainFrame, width=100, height=100)
textFrame.pack()
textFrame_1 = Frame(mainFrame, width=100, height=100)
textFrame_1.pack()
textFrame_2 = Frame(mainFrame,width=100, height=100)
textFrame_2.pack()
scrollbar = Scrollbar(textFrame)
scrollbar.pack(side=RIGHT, fill="y")
#textField == sentance
textField = Text(textFrame, width=50, height=10, bd=5,
relief="groove")
textField.insert(CURRENT,"enter the text\n")
textField.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField["yscrollcommand"] = scrollbar.set
#textField_2 == wrong word
textField_2= Text(textFrame_1, width=15, height=3, bd=5,
relief="groove")
textField_2.insert(CURRENT,"wrong words\n")
textField_2.pack(side=LEFT, padx=(5,0), pady=(5,5))
#textField_3 == correct word
textField_3= Text(textFrame_1,width=15, height=3, bd=5,
relief="groove")
textField_3.insert(CURRENT, "correct words\n")
textField_3.pack(side=LEFT, padx=(5,0), pady=(5,5))
scrollbar_2 = Scrollbar(textFrame_2)
scrollbar_2.pack(side=RIGHT, fill="y")
textField_4 = Text(textFrame_2, width=50, height=10, bd=5,
relief="groove")
textField_4.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField_4["yscrollcommand"] = scrollbar.set
def chg():
sentance = textField.get("1.0",END)
wrong_word = textField_2.get("1.0",END)
correct_word = textField_3.get("1.0",END)
# result = sentance.replace(wrong_word,correct_word)
result = str.replace(str(sentance), wrong_word, correct_word)
textField_4.insert("1.0",result)
def msg():
tkinter.messagebox.showerror("error","there's no words")
def ok():
# if textField_2.get("1.0",END) in textField.get("1.0",END):
chg()
# else:
# msg()
okButton = Button(textFrame_1, text="OK", command=ok)
okButton.pack(padx=40, pady=(20,5))
root.mainloop()
OUTPUT:
EDIT
If you want want to keep that "enter the text part" and type your sentence below, without replacing it, you should do the following in the relevant line for the code to work.
result = str.replace(str(sentance).replace('enter the text\n',''), wrong_word.replace('wrong words\n',''), correct_word.replace('correct words\n',''))
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 found some code to create a menu bar in TkInter, but I can't put in my code without it bugging.
Here is the code I'm using:
from Tkinter import *
import subprocess
import os
master = Tk()
master.geometry("1000x668")
master.title("Menu")
master.configure(background='pale green')
master.iconbitmap(r"C:\Users\André\Desktop\python\menu.ico")
master = Tk()
def NewFile():
print "New File!"
def OpenFile():
name = askopenfilename()
print name
def About():
print "This is a simple example of a menu"
menu = Menu(master)
master.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=NewFile)
filemenu.add_command(label="Open...", command=OpenFile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=master.quit)
w = Label(master, text="Abrir", bg="pale green", fg="steel blue", font=("Algerian", 20, "bold"))
w.pack()
w.place(x=100, y=0)
def notepad():
subprocess.Popen("notepad.exe")
buttonote = Button(master, text="Bloco de notas", wraplength=50, justify=CENTER, padx=2, bg="light sea green", height=2, width=7, command=notepad)
buttonote.pack()
buttonote.place(x=0, y=50)
def regedit():
subprocess.Popen("regedit.exe")
buttonreg = Button(master, text="Editor de Registo", wraplength=50, justify=CENTER, padx=2, bg="light sea green", height=2, width=7, command=regedit)
buttonreg.pack()
buttonreg.place(x=60, y=50)
def skype():
subprocess.Popen("skype.exe")
buttonskype = Button(master, text="Skype", bg="light sea green", height=2, width=7, command=skype)
buttonskype.pack()
buttonskype.place(x=120, y=50)
def steam():
os.startfile("D:\Steam\Steam.exe")
buttonsteam = Button(master, text="Steam", bg="light sea green", height=2, width=7, command=steam)
buttonsteam.pack()
buttonsteam.place(x=178, y=50)
e1 = Entry(master, width=15)
e1.pack(padx=100,pady=4, ipadx=2)
def save():
text = e1.get()
SaveFile = open('information.txt','w')
SaveFile.write(text)
SaveFile.close()
nome = Label(master, text="Nome?", bg="pale green", fg="steel blue", font=("Arial Black", 12))
nome.pack()
nome.place(x=380, y=0)
buttonsave = Button(master, text="Guardar", bg="light sea green", height=1, width=6, command=save)
buttonsave.pack()
buttonsave.place(x=550, y=0)
f = open('information.txt','r')
line = f.readline()
show = Label(master, text=line, bg="pale green", fg="steel blue", font=("Arial Black", 12))
show.pack()
show.place(x=32, y=640)
hi = Label(master, text='Hi, ', bg="pale green", fg="steel blue", font=("Arial Black", 12))
hi.pack()
hi.place(x=0, y=640)
master.mainloop()
Can anyone work out what's wrong with my code? Thanks!
You have master = Tk() on line 4 and repeated on line 9. Delete line 9.
This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
Closed 6 months ago.
I'm writing a Connect Four game in Python using Tkinter. I'm now making a board. I want circles to change color when I click them.
Only the last column of the last row is changed wherever I click on the board. How can I make it so that whenever I click a specific circle, only that circle changes color?
from tkinter import *
import random
def conx_create_window():
mw = Tk()
mw.title("Connect Four Game")
mw.geometry("650x600")
mw.configure(bg="#3C3C3C", padx=50, pady=50)
return mw
def main():
m_window = conx_create_window()
return m_window
m_window = main()
mframe = Frame(m_window, bg="#3C3C3C", padx=50, pady=150)
mframe.pack()
newframe = Frame(m_window, bg="#3C3C3C", padx=50, pady=50)
board = {}
buttons = {}
frames = {}
gameBoard = Frame(m_window)
#----------------------------------
def newgame_click():
print("New game")
mframe.pack_forget()
boardOption()
def boardOption():
newframe.pack()
def board7x6():
gameBoard.pack()
newframe.pack_forget()
print("7x6 Board Size")
for row in range(6):
board[row] = {}
frames[row] = Frame(gameBoard)
frames[row].pack()
for col in range(7):
board[row][col] = 0
frame = Frame(frames[row])
frame.pack(side = LEFT)
c = Canvas(frame, bg="#666", width=50, height=50)
c.pack()
r = c.create_rectangle((0, 0, 50, 50), fill="#3C3C3C")
circle = c.create_oval(3, 3, 49, 49, fill="#3D3D3D")
c.tag_bind(r, "<Button-1>", lambda event: print('works'))
c.tag_bind(circle, "<Button-1>", lambda event: c.itemconfig(circle, fill="green"))
print(" ", board[row][col], " ", end="")
print()
def board8x7():
gameBoard.pack()
newframe.pack_forget()
print("8x7 Board Size")
for row in range(7): # 7 rows
board[row] = {}
buttons[row] = {}
frames[row] = Frame(gameBoard)
frames[row].pack()
for col in range(8): # 8 columns
board[row][col] = 0
buttons[row][col] = Button(frames[row], text="", width=8, height=4, bg="#1EC811", bd=0, highlightthickness=0)
print(" ", board[row][col], " ", end="")
buttons[row][col].pack(side=LEFT)
print()
board7x6_btn = Button(newframe, text="7X6", bg="#64E545", command=board7x6, bd=0, highlightthickness=0)
board8x7_btn = Button(newframe, text="8X7", bg="#64E545", command=board8x7, bd=0, highlightthickness=0)
board7x6_btn.grid(row=0, column=0, padx=20, pady=10, ipadx=20, ipady=20)
board8x7_btn.grid(row=0, column=1, padx=20, pady=10, ipadx=20, ipady=20)
newgame_btn = Button(mframe, text="NEW GAME", bg="#64E545", command=newgame_click, bd=0, highlightthickness=0)
load_btn = Button(mframe, text="LOAD", bg="#64E545", padx=25, bd=0, highlightthickness=0)
ins_btn = Button(mframe, text="INSTRUCTIONS", bg="#64E545", bd=0, highlightthickness=0)
exit_btn = Button(mframe, text="EXIT", bg="#64E545", padx=10, bd=0, highlightthickness=0)#, command = exit_click)
newgame_btn.grid(row=0, column=0, padx=10, pady=10, ipadx=10, ipady=20)
load_btn.grid(row=0, column=1, padx=10, pady=10, ipady=20)
ins_btn.grid(row=1, column=0, padx=10, pady=10, ipady=20)
exit_btn.grid(row=1, column=1, padx=10, pady=10, ipadx=20, ipady=20)
#----------------------------------
m_window.mainloop()
The problem is the lambda construction: c is always the same (last one) and is therefore not evaluated at execution:
c.tag_bind(circle, '<Button-1>', lambda event: c.itemconfig(circle, fill = "green"))
Use a default argument instead::
c.tag_bind(circle, '<Button-1>', lambda event, c=c: c.itemconfig(circle, fill = "green"))
So c is now a default argument and now you have different lamdas. See here for a far better explanation than mine.
I have 2 functions, MakeGUI:
def makeGUI():
#Define the global variables of the function.
global root,f1,f2,f3,r,y,b,g,patColor
#Initialize Gui Items.
root = Tk()
root.wm_title("Buttons")
f3 = Frame(root)
f1 = Frame(root)
f2 = Frame(root)
r = Button(f1, text= "Red", fg="Black", bg="Red", width=25, font="TimesNewRoman", bd=1)
y = Button(f1, text= "Yellow", fg="Black", bg="Yellow", width=25, font="TimesNewRoman", bd=1)
b = Button(f2, text= "Blue", fg="Black", bg="Blue", width=25, font="TimesNewRoman", bd=1, command=showPattern)
g = Button(f2, text= "Green", fg="Black", bg="Green", width=25, font="TimesNewRoman", bd=1)
patColor = Label(f3, bg="White", width=66)
#Pack the GUI items so they will show.
f3.pack()
f1.pack()
f2.pack()
r.pack(side=LEFT)
y.pack(side=RIGHT)
b.pack(side=LEFT)
g.pack(side=RIGHT)
patColor.pack()
#Show the GUI.
root.mainloop()
And showPattern:
def showPattern():
patColor.bg = "Blue"
Is there any way to update only the patColor bg property without refreshing the whole GUI? I am making a simon says type game with python 2.7 and i need it to cycle through a pattern array.
I've discovered after looking into more that the proper notation is:
patColor["bg"] = "Color"