Python Tkinter Entry not placing - python

In Croatia we have competitions where you make apps. I'm making an app to help 1st and 2nd graders learn and revise math. I just started recently so it doesn't have almost anything.
The problem is that when variable: mode = "number" , entries aren't placed.
Btw when opening the app you will be presented with 4 options.
They are addition, subtraction, multiplication and division.
I translated it from Croatian to English so you can understand.
When you run the program press the Addition button.
Then you will see the task but entries missing.
If you change the value of the variable mode to mode = "result", entries are placed.
I tried everything but couldn't get it to work.
Here's the code:
import tkinter as tk
import random
wn = tk.Tk()
wn.config(width = 550, height = 500)
wn.resizable(False, False)
wn.title("Learn and Revise")
number1_1 = 0
number1_2 = 0
number2_1 = 0
number2_2 = 0
number3_1 = 0
number3_2 = 0
number4_1 = 0
number4_2 = 0
number5_1 = 0
number5_2 = 0
def makeRandomNumbers():
global number1_1, number1_2
global number2_1, number2_2
global number3_1, number3_2
global number4_1, number4_2
global number5_1, number5_2
if mode == "number":
while True:
number1_1 = random.randint(0, 10)
number1_2 = random.randint(0, 10)
if number1_1 > number1_2:
pass
else:
break
while True:
number2_1 = random.randint(0, 10)
number2_2 = random.randint(0, 10)
if number2_1 > number2_2:
pass
else:
break
while True:
number3_1 = random.randint(0, 10)
number3_2 = random.randint(0, 10)
if number3_1 > number3_2:
pass
else:
break
while True:
number4_1 = random.randint(0, 10)
number4_2 = random.randint(0, 10)
if number4_1 > number4_2:
pass
else:
break
while True:
number5_1 = random.randint(0, 10)
number5_2 = random.randint(0, 10)
if number5_1 > number5_2:
pass
else:
break
elif mode == "result":
number1_1 = random.randint(0, 10)
number1_2 = random.randint(0, 10)
number2_1 = random.randint(0, 10)
number2_2 = random.randint(0, 10)
number3_1 = random.randint(0, 10)
number3_2 = random.randint(0, 10)
number4_1 = random.randint(0, 10)
number4_2 = random.randint(0, 10)
number5_1 = random.randint(0, 10)
number6_2 = random.randint(0, 10)
def placeTasks(oper):
global operation
operation = oper
makeTasks()
wipeMenu()
button_check.place(x = 310, y = 225)
label1.place(x = 150, y = 125)
label2.place(x = 150, y = 175)
label3.place(x = 150, y = 225)
label4.place(x = 150, y = 275)
label5.place(x = 150, y = 325)
if mode == "number":
entry1.place(x = 240, y = 130)
entry2.place(x = 240, y = 180)
entry3.place(x = 240, y = 230)
entry4.place(x = 240, y = 280)
entry5.place(x = 240, y = 330)
elif mode == "result":
entry1.place(x = 240, y = 130)
entry2.place(x = 240, y = 180)
entry3.place(x = 240, y = 230)
entry4.place(x = 240, y = 280)
entry5.place(x = 240, y = 330)
task1 = 0
task2 = 0
task3 = 0
task4 = 0
task5 = 0
def makeTasks():
global task1, task2, task3, task4, task5
global label1, label2, label3, label4, label5
makeRandomNumbers()
operation_sign = ""
if operation == "addition":
operation_sign = '+'
elif operation == "subtraction":
operation_sign = '-'
elif operation == "multiplication":
operation_sign = '•'
elif operation == "division":
operation_sign = '÷'
if mode == "result":
task1 = "{} {} {} =".format(number1_1, operation_sign, number1_2)
task2 = "{} {} {} =".format(number2_1, operation_sign, number2_2)
task3 = "{} {} {} =".format(number3_1, operation_sign, number3_2)
task4 = "{} {} {} =".format(number4_1, operation_sign, number4_2)
task5 = "{} {} {} =".format(number5_1, operation_sign, number5_2)
elif mode == "number":
task1 = "{} {} = {}".format(number1_1, operation_sign, number1_2)
task2 = "{} {} = {}".format(number2_1, operation_sign, number2_2)
task3 = "{} {} = {}".format(number3_1, operation_sign, number3_2)
task4 = "{} {} = {}".format(number4_1, operation_sign, number4_2)
task5 = "{} {} = {}".format(number5_1, operation_sign, number5_2)
label1 = tk.Label(wn, text = task1, font = ("Arial", 15))
label2 = tk.Label(wn, text = task2, font = ("Arial", 15))
label3 = tk.Label(wn, text = task3, font = ("Arial", 15))
label4 = tk.Label(wn, text = task4, font = ("Arial", 15))
label5 = tk.Label(wn, text = task5, font = ("Arial", 15))
operation = ""
mode = "number"
button_check = tk.Button(wn, width = 20, text = "Check")
label1 = tk.Label(wn, text = task1, font = ("Arial", 15))
entry1 = tk.Entry(wn, width = 7)
label2 = tk.Label(wn, text = task2, font = ("Arial", 15))
entry2 = tk.Entry(wn, width = 7)
label3 = tk.Label(wn, text = task3, font = ("Arial", 15))
entry3 = tk.Entry(wn, width = 7)
label4 = tk.Label(wn, text = task4, font = ("Arial", 15))
entry4 = tk.Entry(wn, width = 7)
label5 = tk.Label(wn, text = task5, font = ("Arial", 15))
entry5 = tk.Entry(wn, width = 7)
def placeMenu():
menu_label1.place(x = 175, y = 75)
button1.place(x = 200, y = 150)
button2.place(x = 200, y = 200)
button3.place(x = 200, y = 250)
button4.place(x = 200, y = 300)
def wipeMenu():
menu_label1.destroy()
button1.destroy()
button2.destroy()
button3.destroy()
button4.destroy()
menu_label1 = tk.Label(wn, text = "Revise", font = ("Arial", 35))
button1 = tk.Button(wn, width = 20, text = "Addition", command = lambda: placeTasks("addition"))
button2 = tk.Button(wn, width = 20, text = "Subtraction")
button3 = tk.Button(wn, width = 20, text = "Multiplication")
button4 = tk.Button(wn, width = 20, text = "Division")
placeMenu()
wn.mainloop()

TL;DR
Postavi font prilikom inicijalizacije entrya, preimenuj if statement i ukloni globalnu varijablu te koristi lokalnu (oper)
Prvo što vidim je mnoštvo ponavljanja. Napravi funkciju s više parametara na kojima ćeš izvršavati for loopove - kod će biti kraći i čitljiviji 20 puta. Tkinter je jednostavan, ali nije praktičan ukoliko nije objektno orijentiran (preporučujem tk.Toplevel klase za prebacivanje prozora, onda samo switchaš screenove i nema potrebe za brisanjem i postavljanjem, što dodatno ubrzava izvrašavanje). Idealno bi bilo kreirati class za svaku aritmetičku operaciju i uz to ne koristiti (spore) lambda anonimne funkcije samo za pozivanje s atributima.
Dakle, kod bi izgledao otprilike ovako:
for (akcija, klasa) in zip(["Addition", "Substraction", ...], lista_klasi):
button = tk.Button(wn, width=20, text=akcija, command=klasa);
...
button.pack() # Izbjegavaj .place(), uvijek samo pack() ili grid()
...
class Solution(tk.Toplevel):
def __init__(self, atributi):
super().__init__()
self.attributes("-topmost", False)
self.solution = tk.Canvas(self, bg="white" ...)
self.solution.pack()
...
# Za najbolji izgled postavljaj widgete na canvas...
self.solution.create_window(w, h, window=atribut[neki])
# Također, ako želiš ostati u istom prozoru, spremi widgete i koristi:
self.canvas.delete("all")
Osobno koristim pack jer je najjednostavniji, u početku nezgodan jer ne dobivaš izgledom točno kako zamišljaš ali kad pohvataš sve ne bi se nikad vratio na place(), osim ako nije nužno :)
Zasad prvo prouči sve pojašnjene primjere ovdje.
Tek kad savladaš tkinter kreni na kivy ako misliš stvarno rasturit na natjecanju.

Related

Switching between frames in tkinter, clock app

Good day, guys. I've got a problem with switching between frames in tkinter. I'm trying to make a clock app with time, stopwatch, timer and alarm. If I click on the first frame it's working, but if I select the second frame it's breaks. The previous frame just don't open because the second frame refreshing too fast (lbl.after). Can you help me with switching between frames?
from tkinter import *
from tkmacosx import *
from time import strftime
root = Tk()
root.title('Time')
root.geometry('500x500')
root.resizable(False, False)
counter = -1
running = False
def time_frame():
string = strftime("%H:%M:%S %A %d %Y")
frame_time = Frame(root, width = 480, height = 410, bg = 'gray70')
frame_time.place(x = 10, y = 80)
lbl1 = Label(frame_time, text = list, width = 32, height = 10, font = ('Arial', 25))
lbl1.place(x = 10, y = 80)
lbl1.config(text=string)
lbl1.after(1000, time_frame)
def stopwatch_frame():
frame_stopwatch = Frame(root, width = 480, height = 410, bg = 'gray70')
frame_stopwatch.place(x = 10, y = 80)
lbl2 = Label(frame_stopwatch, text = '0', width = 25, height = 5, font = ('Arial', 25))
lbl2.place(x = 10, y = 80)
start_button = Button(frame_stopwatch, width = 80, height = 40, text = 'Start')
start_button.place(x = 10, y = 240)
stop_button = Button(frame_stopwatch, width = 80, height = 40, text = 'Stop')
stop_button.place(x = 100, y = 240)
reset_button = Button(frame_stopwatch, width = 80, height = 40, text = 'Reset')
reset_button.place(x = 190, y = 240)
lbl2.after(1, stopwatch_frame)
frame_top = Frame(root, width = 500, height = 70, bg = 'gray64')
frame_top.place(x = 0, y = 0)
time_btn = Button(frame_top, text = 'Time', width = 50, height = 50, command = time_frame)
time_btn.place(x = 10, y = 10)
stopwatch_btn = Button(frame_top, text = 'Stopwatch', width = 50, height = 50, font = ('Arial', 9), command = stopwatch_frame)
stopwatch_btn.place(x = 80, y = 10)
timer_btn = Button(frame_top, text = 'Timer', width = 50, height = 50)
timer_btn.place(x = 150, y = 10)
alarm_btn = Button(frame_top, text = 'Alarm', width = 50, height = 50)
alarm_btn.place(x = 220, y = 10)
root.mainloop()
Here is a simplified example of a clock and stop watch class.
import tkinter as tk
from tkmacosx import *
from time import strftime, process_time
class timer:
delaya = None
delayb = None
def __init__( self ):
self.root = tk.Tk()
self.root.title('Time')
self.buttona = tk.Button( self.root, text = 'clock', width = 40, command = self.setclock )
self.buttonb = tk.Button( self.root, text = 'watch', width = 40, command = self.setwatch )
self.buttona.grid( row=0, column=0, sticky='ew' )
self.buttonb.grid( row=0, column=1, sticky='ew' )
self.root.update_idletasks()
self.root.resizable( False, False )
def clock( self ):
self.root.after_cancel( self.delaya )
self.delaya = None
self.buttona[ 'text' ] = strftime("%H:%M:%S %A %d %Y")
self.delaya = self.root.after( 1000, self.clock )
def watch( self ):
self.root.after_cancel( self.delayb )
self.delayb = None
self.buttonb[ 'text' ] = f'{process_time():0.5f}'
self.delayb = self.root.after( 1, self.watch )
def setclock( self ):
if self.delaya == None:
self.delaya = self.root.after( 1000, self.clock )
else:
self.root.after_cancel( self.delaya )
self.delaya = None
self.buttona[ 'text' ] = 'clock'
def setwatch( self ):
if self.delayb == None:
self.delayb = self.root.after( 1, self.watch )
else:
self.root.after_cancel( self.delayb )
self.delayb = None
self.buttonb[ 'text' ] = 'watch'
if __name__ == '__main__':
device = timer( )
tk.mainloop()

time.sleep skips multiple lines in my script

def fctCountdown():
t = 3
countdown = Label(Pong, text = "3", font = ("Fixedsys", 30), bg = "#CB997E", fg = 'black')
countdown.place(x = 387, y = 300)
while t >= 0:
if t == 2:
countdown.config(text = "2")
if t == 1:
countdown.config(text = "1")
if t == 0:
countdown.config(text = "Start !")
sleep(1)
t -= 1
countdown.place_forget()
def fctGoDown():
global x1, y1
def fctGameMenu():
background_image = PhotoImage(master = Pong, file = "fondpong0.png")
background_label = Label(Pong, image = background_image)
background_label.place(x = 0, y = 0)
background_label.image = background_image
def fctStartGame(evt):
global state
if state == 0:
state = 1
fctGameMenu()
sleep(1)
fctCountdown()
Hi guys ! I'm asking you for help because the sleep(1) line in fctStartGame is executed before the fctGameMenu() and i don't understand why. Because of it my countdown doesn't work.

How to move Tkinter widget precisely. Place method not working

Here's the code so far:
# -*- coding: utf-8 -*-
from Tkinter import *
#Creates game window
master = Tk()
master.geometry("640x480")
master.resizable(width = False, height = False)
master.title("YeeHaw Poker")
#Divides window into subsections
menuFrame = Frame(master, bg = "black", height = 60)
menuFrame.pack(fill = X, side = TOP)
tableFrame = Frame(master, highlightbackground = "black", highlightthickness = 4)
tableFrame.pack(fill = BOTH, expand = True)
optionsFrame = Frame(master, bg = "black", height = 100)
optionsFrame.pack(fill = X, side = BOTTOM)
#Draws poker table decorations
tableDecorations = Canvas(tableFrame, bg = "#771427", highlightthickness = 0)
tableDecorations.pack(fill = BOTH, expand = True)
#Renders window thus far so that dimensions can be found
master.update()
tWidth = tableDecorations.winfo_width()
tHeight = tableDecorations.winfo_height()
#Main edge
gap = 10
tableDecorations.create_rectangle(gap, gap, tWidth - gap, tHeight - gap, fill ="#277714", width = 4)
#Table outline
gap = 30
tableDecorations.create_rectangle(gap, gap, tWidth - gap, tHeight - gap, outline = "#35a31b", width = 2)
#Card outline coordinates
cardNum = 5
cardSize = 20
cardHeight = cardSize * 3.5
cardWidth = cardSize * 2.5
cardSpace = 10
cardTop = tHeight / 4
cardLeft = (tWidth - (cardNum * (cardWidth + cardSpace))) / 2
cardY1 = cardTop + cardHeight
cardY2 = cardTop
cardX1 = [0 for i in range(0, cardNum)]
cardX2 = [0 for i in range(0, cardNum)]
suit = [0 for i in range(0, cardNum)]
for i in range(0, cardNum):
cardX1[i] = cardLeft + (i * (cardWidth + cardSpace))
cardX2[i] = cardX1[i] + cardWidth
suit[i] = Label(tableDecorations, text = "", bg = "white", font = (None, 50))
suit[i].place(x = 5000, y = 5000)
#Draws specified card in specified place
def drawCard(pos, type, pip):
if type == "empty":
tableDecorations.create_rectangle(cardX1[pos], cardY1, cardX2[pos], cardY2, outline = "#35a31b", width = 2)
suit[pos].pack_forget()
else:
tableDecorations.create_rectangle(cardX1[pos], cardY1, cardX2[pos], cardY2, fill = "white", outline = "grey", width = 1)
if type == "diamond":
suit[pos].config(text = "♦", fg = "red")
elif type == "heart":
suit[pos].config(text = "♥", fg = "red")
elif type == "spade":
suit[pos].config(text = "♠", fg = "black")
elif type == "club":
suit[pos].config(text = "♣", fg = "black")
suit[pos].pack()
#Creates new table
def newTable():
for i in range(0, cardNum):
drawCard(i, "diamond", 0)
newTable()
master.mainloop()
However this doesn't move the labels with the diamonds in at all, as shown here:
It's infuriating...
I'm wanting the diamond to appear on each individual card, but clearly that's not happening here...
Any ideas?

python 3 tkinter class variables and Spinboxes with Labels not updating

Can't figure out why my labels aren't updating from clicks on my Spinboxes
from tkinter import *
mainBackground = "#0047BF"
mainForeground = "#C2F2E6"
inputBackground = "#230E38"
window = Tk()
window.title("Gurps Game Manager")
window.geometry("700x600")
window.wm_iconbitmap('pyramid.ico')
window.configure(background = mainBackground)
# Creating Variable Classes and setting to base stat
strength = IntVar(window)
strength.set(10)
dexterity = IntVar(window)
dexterity.set(10)
intelligence = IntVar(window)
intelligence.set(10)
health = IntVar(window)
health.set(10)
hpMod = IntVar(window)
hpMod.set(0)
willMod = IntVar(window)
willMod.set(0)
perMod = IntVar(window)
perMod.set(0)
fpMod = IntVar(window)
fpMod.set(0)
bSpeedMod = IntVar(window)
bSpeedMod.set(0)
bMoveMod = IntVar(window)
bMoveMod.set(0)
hpTotal = IntVar(window)
hpTotal.set(10)
willTotal = IntVar(window)
willTotal.set(10)
perTotal = IntVar(window)
perTotal.set(10)
fpTotal = IntVar(window)
fpTotal.set(10)
bSpeedTotal = IntVar(window)
bSpeedTotal.set(5)
bMoveTotal = IntVar(window)
bMoveTotal.set(5)
bLift = IntVar(window)
bLift.set(20)
bThrust = StringVar(window)
bThrust.set('1d-2')
bSwing = StringVar(window)
bSwing.set('1d')
charPointTotal = IntVar(window)
charPointTotal.set(0)
charPointLimit = IntVar(window)
charPointLimit.set(250)
charPointDiff = IntVar(window)
charPointDiff.set(250)
# Functions to create widgets
def mainLabel(text):
label = Label(window, text = text, bg = mainBackground, fg = mainForeground,
font = ('Lucida Console', 14))
return label
def calcLabel(textVariable):
label = Label(window, textvariable = textVariable, bg = mainBackground, fg = mainForeground, font = ('Lucida Console', 14))
return label
def mainEntry(callback = None):
entry = Entry(window, bg = inputBackground, fg = mainForeground, insertbackground = mainForeground,
command = callback)
return entry
def mainSpinbox(callback, textVar, floor, ceiling, increment = 1):
spinbox = Spinbox(window, fg = mainForeground, state = 'readonly', readonlybackground = mainBackground,
from_ = floor, to = ceiling, increment = increment, textvariable = textVar, command = callback,
justify = 'center', border = '0', width = '5')
return spinbox
# Command function to set values on change
def charPointsCallback():
st = int(strength.get())
dx = int(dexterity.get())
iq = int(intelligence.get())
ht = int(health.get())
hp = int(hpMod.get())
will = int(willMod.get())
per = int(perMod.get())
fp = int(fpMod.get())
bSpeed = int(bSpeedMod.get())
bMove = int(bMoveMod.get())
hpTotal.set(st + hp)
willTotal.set(iq + will)
perTotal.set(iq + per)
fpTotal.set(ht + fp)
bSpeedTotal.set((ht + dx) / 4 + bSpeed)
bMoveTotal.set((ht + dx) // 4 + bMove)
bLift.set((st * st) / 5)
cpTotal = ((st - 10) * 10) + ((dx - 10) * 20) + ((iq - 10) * 20) + ((ht - 10) * 10) + (hp * 2) + (will * 5) + (
per * 5) + (fp * 5) + (bSpeed * 20) + (bMove * 5)
cpLimit = charPointLimit.get()
charPointTotal.set(cpTotal)
charPointDiff.set(cpLimit - cpTotal)
# Lists of strings and variables for loop to create widgets
coreStatLabels = ['ST', 'DX', 'IQ', 'HT']
coreStatVar = [strength, dexterity, intelligence, health]
modStatLabels = ['HP', 'Will', 'Per', 'FP', 'Basic Speed', 'Basic Move']
modStatVar = [hpMod, willMod, perMod, fpMod, bSpeedMod, bMoveMod]
totalStatVar = [hpTotal, willTotal, perTotal, fpTotal, bSpeedTotal, bMoveTotal]
derivedStatLabels = ['Basic Lift', 'Basic Thrust', 'Basic Swing', 'Character Point Total:']
derivedStatVar = [bLift, bThrust, bSwing, charPointTotal]
# Widgets
characterNameLbl = mainLabel('Character Name:')
characterNameLbl.grid(row = 0, column = 0, columnspan = 2)
characterNameEntry = mainEntry(charPointsCallback())
characterNameEntry.grid(row = 0, column = 2)
charPointLimitLbl = mainLabel('Character Point Limit:')
charPointLimitLbl.grid(row = 1, column = 0, columnspan = 2)
charPointLimitSpin = mainSpinbox(charPointsCallback(),charPointLimit, 100, 500, 10)
charPointLimitSpin.grid(row = 1, column = 2)
# Loops that create the widgets
for i in range(4):
row = range(2, 6)
coreStatLbl = mainLabel(coreStatLabels[i])
coreStatLbl.grid(row = row[i], column = 0)
coreStatSpin = mainSpinbox(charPointsCallback(), coreStatVar[i], 5, 15)
coreStatSpin.grid(row = row[i], column = 2)
for i in range(5):
row = range(6, 12)
modStatLbl = mainLabel(modStatLabels[i])
modStatLbl.grid(row = row[i], column = 0)
modStatSpin = mainSpinbox(charPointsCallback(), modStatVar[i], -5, 5)
modStatSpin.grid(row = row[i], column = 1)
totalStatLabel = calcLabel(totalStatVar[i])
totalStatLabel.grid(row = row[i], column = 2)
for i in range(4):
row = range(12,16)
derivedStatLbl = mainLabel(derivedStatLabels[i])
derivedStatLbl.grid(row = row[i], column = 0)
derivedStatCalc = calcLabel(derivedStatVar[i])
derivedStatCalc.grid(row = row[i], column = 2)
window.mainloop()
My understanding of variable classes is that any widget with a variable class set to it will update with the variable when it changes. I click on the up/down spinner, and nothing changes.
When you do this:
modStatSpin = mainSpinbox(charPointsCallback(), ...)
It is exactly the same as if you did this:
something = charPointsCallback()
modStatSpin = mainSpinbox(something, ...)
If you are passing in a callback toa function, you must pass in a reference to the function (ie: remove the trailing ())

A loop within tkinter - HELP!

this is my first time using this forum, hopefully, i can get a quick response with a detailed explanation.
Running:
Python 3.2
Tkinter 8.5 & Windows7 x64
My code:
from tkinter import *
import tkinter.messagebox
class Application(Frame):
def __init__(self, master):
super(Application, self).__init__(master)
self.grid()
self.lvl_one_att = 4
self.bttn_clicks = 2
self.bttn_clicks2 = 2
self.bttn_clicks3 = 1
self.bttn_clicks4 = 2
self.bttn_clicks5 = 1
self.bttn_clicks6 = 2
self.bttn_clicks7 = 1
self.bttn_clicks8 = 2
self.bttn_clicks9 = 2
self.level_one()
def level_one(self):
self.lbl1 = Label(self, text = "You must flip all the boxes to show the same colour!")
self.lbl1.grid(row = 0, column = 0, columnspan = 3)
self.levellbl = Label(self, text = "Level 1")
self.levellbl.grid(row = 4, column = 1, sticky = W, columnspan = 2)
self.rulesbttn = Button(self, text = "Instructions", command = self.rules)
self.rulesbttn.grid(row = 4, column = 0, sticky = W, columnspan = 1)
self.tlbttn = Button(self, bg = "red", width = 20, height = 10, command = self.callback1)
self.tlbttn.grid(row = 1, column = 0, columnspan = 1)
self.tmbttn = Button(self, bg = "red", width = 20, height = 10, command = self.callback2)
self.tmbttn.grid(row = 1, column = 1, columnspan = 1)
self.trbttn = Button(self, bg = "blue", width = 20, height = 10, command = self.callback3)
self.trbttn.grid(row = 1, column = 2, columnspan = 1)
self.mlbttn = Button(self, bg = "red", width = 20, height = 10, command = self.callback4)
self.mlbttn.grid(row = 2, column = 0, columnspan = 1)
self.mmbttn = Button(self, bg = "blue", width = 20, height = 10, command = self.callback5)
self.mmbttn.grid(row = 2, column = 1, columnspan = 1)
self.mrbttn = Button(self, bg = "red", width = 20, height = 10, command = self.callback6)
self.mrbttn.grid(row = 2, column = 2, columnspan = 1)
self.blbttn = Button(self, bg = "blue", width = 20, height = 10, command = self.callback7)
self.blbttn.grid(row = 3, column = 0, columnspan = 1)
self.bmbttn = Button(self, bg = "red",width = 20, height = 10, command = self.callback8)
self.bmbttn.grid(row = 3, column = 1, columnspan = 1)
self.brbttn = Button(self, bg = "red", width = 20, height = 10, command = self.callback9)
self.brbttn.grid(row = 3, column = 2, columnspan = 1)
def callback1(self):
self.lvl_one_att -= 1
self.color_change1()
self.color_change2()
self.color_change4()
self.color_change5()
def callback2(self):
self.lvl_one_att -= 1
self.color_change1()
self.color_change2()
self.color_change3()
self.color_change5()
self.color_change4()
self.color_change6()
def callback3(self):
self.lvl_one_att -= 1
self.color_change2()
self.color_change3()
self.color_change6()
self.color_change5()
def callback4(self):
self.lvl_one_att -= 1
self.color_change1()
self.color_change2()
self.color_change4()
self.color_change5()
self.color_change7()
self.color_change8()
def callback5(self):
self.lvl_one_att -= 1
self.color_change1()
self.color_change2()
self.color_change3()
self.color_change6()
self.color_change9()
self.color_change4()
self.color_change5()
self.color_change7()
self.color_change8()
def callback6(self):
self.lvl_one_att -= 1
self.color_change3()
self.color_change2()
self.color_change6()
self.color_change5()
self.color_change9()
self.color_change8()
def callback7(self):
self.lvl_one_att -= 1
self.color_change4()
self.color_change5()
self.color_change7()
self.color_change8()
def callback8(self):
self.lvl_one_att -= 1
self.color_change4()
self.color_change5()
self.color_change6()
self.color_change7()
self.color_change8()
self.color_change9()
def callback9(self):
self.lvl_one_att -= 1
self.color_change5()
self.color_change6()
self.color_change9()
self.color_change8()
def color_change1(self):
self.bttn_clicks += 1
if self.bttn_clicks == 3:
self.bttn_clicks = 1
if self.bttn_clicks == 1:
self.tlbttn.configure(bg = "blue")
else:
self.tlbttn.configure(bg = "red")
def color_change2(self):
self.bttn_clicks2 += 1
if self.bttn_clicks2 == 3:
self.bttn_clicks2 = 1
if self.bttn_clicks2 == 1:
self.tmbttn.configure(bg = "blue")
else:
self.tmbttn.configure(bg = "red")
def color_change3(self):
self.bttn_clicks3 += 1
if self.bttn_clicks3 == 3:
self.bttn_clicks3 = 1
if self.bttn_clicks3 == 1:
self.trbttn.configure(bg = "blue")
else:
self.trbttn.configure(bg = "red")
def color_change4(self):
self.bttn_clicks4 += 1
if self.bttn_clicks4 == 3:
self.bttn_clicks4 = 1
if self.bttn_clicks4 == 1:
self.mlbttn.configure(bg = "blue")
else:
self.mlbttn.configure(bg = "red")
def color_change5(self):
self.bttn_clicks5 += 1
if self.bttn_clicks5 == 3:
self.bttn_clicks5 = 1
if self.bttn_clicks5 == 1:
self.mmbttn.configure(bg = "blue")
else:
self.mmbttn.configure(bg = "red")
def color_change6(self):
self.bttn_clicks6 += 1
if self.bttn_clicks6 == 3:
self.bttn_clicks6 = 1
if self.bttn_clicks6 == 1:
self.mrbttn.configure(bg = "blue")
else:
self.mrbttn.configure(bg = "red")
def color_change7(self):
self.bttn_clicks7 += 1
if self.bttn_clicks7 == 3:
self.bttn_clicks7 = 1
if self.bttn_clicks7 == 1:
self.blbttn.configure(bg = "blue")
else:
self.blbttn.configure(bg = "red")
def color_change8(self):
self.bttn_clicks8 += 1
if self.bttn_clicks8 == 3:
self.bttn_clicks8 = 1
if self.bttn_clicks8 == 1:
self.bmbttn.configure(bg = "blue")
else:
self.bmbttn.configure(bg = "red")
def color_change9(self):
self.bttn_clicks9 += 1
if self.bttn_clicks9 == 3:
self.bttn_clicks9 = 1
if self.bttn_clicks9 == 1:
self.brbttn.configure(bg = "blue")
else:
self.brbttn.configure(bg = "red")
def rules(self):
tkinter.messagebox.showinfo("Instructions", "The idea of the game, is to make sure all the boxes on the screen are the same colour. By pressing a button it will flip, all colours touching it, including diagonally. ")
def round_win(self):
self.lbl1.grid_forget()
self.rulesbttn.grid_forget()
self.tlbttn.grid_forget()
self.tmbttn.grid_forget()
self.trbttn.grid_forget()
self.mlbttn.grid_forget()
self.mmbttn.grid_forget()
self.mrbttn.grid_forget()
self.blbttn.grid_forget()
self.bmbttn.grid_forget()
self.brbttn.grid_forget()
self.win()
def win(self):
self.lbl2 = Label(self, text = "CONGRATULATIONS!", font=("Helvetica", 40))
self.lbl2.grid(row = 0, column = 0)
root = Tk()
root.title("Program")
app = Application(root)
root.mainloop()
What i can work out how to do, is somehow use a loop so that when all 9 squares are the Red that it runs the round_win() function.
im unsure where to put the loop, and how to write it (for loop, while loop, if, but, else, etc)
Thanks heaps guys for any help you may be able to provide :)
You can put the original buttons into a list:
def level_one(self):
...
self.game_buttons = []
for btn_index in range(9):
bg = "red" # change this to something based on the index
next_button = Button(self, bg = bg, width = 20, height = 10)
next_button['command'] = (lambda index=btn_index: self.callback(index))
row = index/3 + 1
column = index % 3
next_button.grid(row = row, column = column, columnspan = 1)
self.game_buttons.append(next_button)
def callback1(self, index):
button = self.game_buttons[index]
# add the appropriate code here
def color_change(self, index):
# add the appropriate code here
Also, you can change the following code:
self.bttn_clicks2 += 1
if self.bttn_clicks2 == 3:
self.bttn_clicks2 = 1
to
self.bttn_clicks2 = self.bttn_clicks2 % 3 + 1

Categories