I am working on a roulette code in python with tkinter. I am pretty far with it. But the problem is that after a few Rolls it starts bugging out and crashes. (I know its not a too good code and there are quite a lot of unnecessary steps in it, I am still pretty new to programming).
from tkinter import *
import tkinter.messagebox
root = Tk()
import random
money2 = StringVar()
varblack = StringVar()
vargreen = StringVar()
varred = StringVar()
numlist = [7]
newnumlist = [1]
def num():
global numlist
number = random.randint(1,15)
if num.counter == 10:
numlist.append(number)
num.counter +=1
return numlist[len(numlist) - 1]
def newnumone():
global newnumlist
newnumber = random.randint(1, 4)
if newnumone.counter == 10:
newnumlist.append(newnumber)
newnumone.counter += 1
return newnumlist[len(newnumlist) - 1]
newnumone.counter = 0
num.counter = 0
RollList = ['red', 'black', 'red','black', 'red', 'black','red', 'green', 'black', 'red','black', 'red', 'black', 'red', 'black']
def colorsone():
newList = RollList[::-1]
if newList[0:9] == ['red', 'black', 'red','black', 'red', 'black','red', 'black', 'red']:
RollList.append('green')
if newList[0] == 'red':
RollList.append('black')
if newList[0] == 'black':
RollList.append('red')
def lol():
i = 0
global RollList
if lol.counter == 0:
num.counter = 10
newnumone.counter = 10
RollList = RollList[0:15]
number = int(num())
newnum = int(newnumone())
newRollsList = RollList[::-1]
if newRollsList[0] == 'red':
colorbgo1 = 'red'
i = i + 1
# colors('black')
if newRollsList[0] == 'green':
colorbgo1 = 'green'
i = i + 1
# colors('red')
if newRollsList[0] == 'black':
colorbgo1 = 'black'
i = i + 1
# colors('green')
if newRollsList[1] == 'red':
colorbgo2 = 'red'
i = i + 1
# colors('black')
if newRollsList[1] == 'green':
colorbgo2 = 'green'
i = i + 1
# colors('black')
if newRollsList[1] == 'black':
colorbgo2 = 'black'
i = i + 1
# colors('black')
if newRollsList[2] == 'red':
colorbgo3 = 'red'
i = i + 1
# colors('black')
if newRollsList[2] == 'green':
colorbgo3 = 'green'
i = i + 1
# colors('black')
if newRollsList[2] == 'black':
colorbgo3 = 'black'
i = i + 1
# colors('black')
if newRollsList[3] == 'red':
colorbgo4 = 'red'
i = i + 1
# colors('black')
if newRollsList[3] == 'green':
colorbgo4 = 'green'
i = i + 1
# colors('black')
if newRollsList[3] == 'black':
colorbgo4 = 'black'
i = i + 1
# colors('black')
if newRollsList[4] == 'red':
colorbgo5 = 'red'
i = i + 1
# colors('black')
if newRollsList[4] == 'green':
colorbgo5 = 'green'
i = i + 1
# colors('black')
if newRollsList[4] == 'black':
colorbgo5 = 'black'
i = i + 1
# colors('black')
if newRollsList[5] == 'red':
colorbgo6 = 'red'
i = i + 1
# colors('black')
if newRollsList[5] == 'green':
colorbgo6 = 'green'
i = i + 1
# colors('black')
if newRollsList[5] == 'black':
colorbgo6 = 'black'
i = i + 1
# colors('black')
if newRollsList[6] == 'red':
colorbgo7 = 'red'
i = i + 1
# colors('black')
if newRollsList[6] == 'green':
colorbgo7 = 'green'
i = i + 1
# colors('black')
if newRollsList[6] == 'black':
colorbgo7 = 'black'
i = i + 1
# colors('black')
if newRollsList[7] == 'red':
colorbgo8 = 'red'
i = i + 1
# colors('black')
if newRollsList[7] == 'green':
colorbgo8 = 'green'
i = i + 1
# colors('black')
if newRollsList[7] == 'black':
colorbgo8 = 'black'
i = i + 1
# colors('black')
if newRollsList[8] == 'red':
colorbgo9 = 'red'
i = i + 1
# colors('black')
if newRollsList[8] == 'green':
colorbgo9 = 'green'
i = i + 1
# colors('black')
if newRollsList[8] == 'black':
colorbgo9 = 'black'
i = i + 1
# colors('black')
if newRollsList[9] == 'red':
colorbgo10 = 'red'
i = i + 1
# colors('black')
if newRollsList[9] == 'green':
colorbgo10 = 'green'
i = i + 1
# colors('black')
if newRollsList[9] == 'black':
colorbgo10 = 'black'
i = i + 1
# colors('black')
lol.counter += 1
colorsone()
if lol.counter < 150:
countdownone(1, 10)
if lol.counter < 200 and lol.counter > 149:
countdownone(1, 40)
if lol.counter < 230 and lol.counter > 199:
countdownone(1, 80)
if lol.counter < 240 and lol.counter >229:
countdownone(1, 140)
if lol.counter < 250 and lol.counter > 239:
countdownone(1, 200)
if number == 8:
if lol.counter < 258 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 259 and lol.counter > 257:
countdownone(1, 500)
if lol.counter == 259:
play()
# lol.counter = 0
if number >= 9: #black
if newnum == 1:
if lol.counter < 254 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 257 and lol.counter > 253:
countdownone(1, 500)
if lol.counter == 257:
# print(1)
play()
# lol.counter = 0
if newnum == 2:
if lol.counter < 252 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 255 and lol.counter > 251:
countdownone(1, 500)
if lol.counter == 255:
# print(2)
play()
# lol.counter = 0
if newnum == 3:
if lol.counter < 259 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 262 and lol.counter > 258:
countdownone(1, 500)
if lol.counter == 262:
# print(3)
play()
# lol.counter = 0
if newnum == 4:
if lol.counter < 258 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 260 and lol.counter > 257:
countdownone(1, 500)
if lol.counter == 260:
# print(4)
play()
# lol.counter = 0
if number <= 7: #red
if newnum == 1:
if lol.counter < 254 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 256 and lol.counter > 253:
countdownone(1, 500)
if lol.counter == 256:
# print(5)
play()
# lol.counter = 0
if newnum == 2:
if lol.counter < 252 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 253 and lol.counter > 251:
countdownone(1, 500)
if lol.counter == 253:
play()
# print(6)
# lol.counter = 0
if newnum == 3:
if lol.counter < 256 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 258 and lol.counter > 255:
countdownone(1, 500)
if lol.counter == 258:
# print(7)
play()
# lol.counter = 0
if newnum == 4:
if lol.counter < 258 and lol.counter > 249:
countdownone(1, 300)
if lol.counter < 261 and lol.counter > 257:
countdownone(1, 500)
if lol.counter == 261:
# print(8)
play()
# lol.counter = 0
labelRoll1 = Label(root, bg = colorbgo1, height=4, width = 8).grid(row = 10, column = 4)
# labelRollsw1 = Label(root, text = ' ').grid(row = 15, column = 4)
labelRoll2 = Label(root, bg = colorbgo2, height=4, width = 8).grid(row = 10, column = 5)
# labelRollsw2 = Label(root, text = ' ').grid(row = 15, column = 5)
labelRoll3 = Label(root, bg = colorbgo3, height=4, width = 8).grid(row = 10, column = 6)
# labelRollsw3 = Label(root, text = ' ').grid(row = 15, column = 6)
labelRoll4 = Label(root, bg = colorbgo4, height=4, width = 8).grid(row = 10, column = 7)
# labelRollsw4 = Label(root, text = ' ').grid(row = 15, column = 7)
labelRoll5 = Label(root, bg = colorbgo5, height=4, width = 8).grid(row = 10, column = 8)
# labelRollsw5 = Label(root, text = ' ').grid(row = 15, column = 8)
labelRoll6 = Label(root, bg = colorbgo6, height=4, width = 8).grid(row = 10, column = 9)
# labelRollsw6 = Label(root, text = ' ').grid(row = 15, column = 9)
labelRoll7 = Label(root, bg = colorbgo7, height=4, width = 8).grid(row = 10, column = 10)
# labelRollsw7 = Label(root, text = ' ').grid(row = 15, column = 10)
labelRoll8 = Label(root, bg = colorbgo8, height=4, width = 8).grid(row = 10, column = 11)
# labelRollsw8 = Label(root, text = ' ').grid(row = 15, column = 11)
labelRoll9 = Label(root, bg = colorbgo9, height=4, width = 8).grid(row = 10, column = 12)
# labelRollsw9 = Label(root, text = ' ').grid(row = 15, column = 12)
labelRoll10 = Label(root, bg = colorbgo10, height=4, width = 8).grid(row = 10, column = 13)
labelRollsw1 = Label(root, height=4, width = 8).grid(row = 17, column = 4)
labelRollsw2 = Label(root, height=4, width = 8).grid(row = 17, column = 5)
labelRollsw3 = Label(root, height=4, width = 8).grid(row = 17, column = 6)
labelRollsw4 = Label(root, height=4, width = 8).grid(row = 17, column = 7)
labelRollsw5 = Label(root, height=4, width = 8).grid(row = 17, column = 8)
labelRollsw6 = Label(root, height=4, width = 8).grid(row = 17, column = 9)
labelRollsw7 = Label(root, height=4, width = 8).grid(row = 17, column = 10)
labelRollsw8 = Label(root, height=4, width = 8).grid(row = 17, column = 11)
labelRollsw9 = Label(root, height=4, width = 8).grid(row = 17, column = 12)
labelRollsw10 = Label(root, height=4, width = 8).grid(row = 17, column = 13)
labelRollsw11 = Label(root, height=4, width = 8).grid(row = 17, column = 14)
lol.counter = 0
def countdownone(count, i):
# timer['text'] = count
if count > 0:
root.after(i, countdownone, count-count, i)
if count == 0:
lol()
#timerone = Label(root)
#timerone.grid()
end = Label(root, text = '↓').grid(row = 8, column =9)
endone = Label(root, text = '↑').grid(row = 16, column =9)
#allin = Button(root, text = 'LOL', command = countdown(1, 100)).grid(row = 3, column = 3)
def countdown(count):
timer['text'] = count
if count > 0:
root.after(1000, countdown, count-1)
if count == 3:
countdownone(1, 10)
if count == 20:
entry_money.configure(state="normal")
greenB.configure(state="normal")
blackB.configure(state="normal")
redB.configure(state="normal")
if count == 0:
entry_money.configure(state="disabled")
greenB.configure(state="disabled")
blackB.configure(state="disabled")
redB.configure(state="disabled")
# if count == 0:
# play()
def play():
varblack1 = varblack.get()
vargreen1 = vargreen.get()
varred1 = varred.get()
if vargreen1 == 'off' and varblack1 == 'off' and varred1 == 'off':
nothing()
if varred1 == 'on':
# blackB.deselect()
# greenB.deselect()
red()
if varblack1 == 'on':
# greenB.deselect()
black()
if vargreen1 == 'on':
green()
redB.deselect()
blackB.deselect()
greenB.deselect()
countdown(20)
lol.counter = 0
entry_money.delete(0, 'end')
# newnumone.counter = 0
# num.counter = 0
def all():
total1=total.get()
money2.set(total1)
def red():
money1 = money2.get()
roulette3('red', money1)
def black():
money1 = money2.get()
roulette3('black', money1)
def green():
money1 = money2.get()
roulette3('green', money1)
def nothing():
roulette3('no', 1)
def colors(clr):
file = open('newfile.txt', 'a')
file.write(clr)
file.close()
file = open('newfile.txt', 'r')
file.close()
PrevRollsColor()
def PrevRollsColor():
lastRollsList = []
lastRolls = open("newfile.txt", "r")
Rolls = lastRolls.read().splitlines()
for line in Rolls:
lastRollsList.append(line)
lastRolls.close()
newRollsList = lastRollsList[::-1]
#labelRollsList = [labelRolls2, labelRolls3, labelRolls4, labelRolls5, labelRolls6, labelRolls7, labelRolls8, labelRolls9, labelRolls10]
if newRollsList[0] == 'red':
colorbg1 = 'red'
if newRollsList[0] == 'green':
colorbg1 = 'green'
if newRollsList[0] == 'black':
colorbg1 = 'black'
if newRollsList[1] == 'red':
colorbg2 = 'red'
if newRollsList[1] == 'green':
colorbg2 = 'green'
if newRollsList[1] == 'black':
colorbg2 = 'black'
if newRollsList[2] == 'red':
colorbg3 = 'red'
if newRollsList[2] == 'green':
colorbg3 = 'green'
if newRollsList[2] == 'black':
colorbg3 = 'black'
if newRollsList[3] == 'red':
colorbg4 = 'red'
if newRollsList[3] == 'green':
colorbg4 = 'green'
if newRollsList[3] == 'black':
colorbg4 = 'black'
if newRollsList[4] == 'red':
colorbg5 = 'red'
if newRollsList[4] == 'green':
colorbg5 = 'green'
if newRollsList[4] == 'black':
colorbg5 = 'black'
if newRollsList[5] == 'red':
colorbg6 = 'red'
if newRollsList[5] == 'green':
colorbg6 = 'green'
if newRollsList[5] == 'black':
colorbg6 = 'black'
if newRollsList[6] == 'red':
colorbg7 = 'red'
if newRollsList[6] == 'green':
colorbg7 = 'green'
if newRollsList[6] == 'black':
colorbg7 = 'black'
if newRollsList[7] == 'red':
colorbg8 = 'red'
if newRollsList[7] == 'green':
colorbg8 = 'green'
if newRollsList[7] == 'black':
colorbg8 = 'black'
if newRollsList[8] == 'red':
colorbg9 = 'red'
if newRollsList[8] == 'green':
colorbg9 = 'green'
if newRollsList[8] == 'black':
colorbg9 = 'black'
if newRollsList[9] == 'red':
colorbg10 = 'red'
if newRollsList[9] == 'green':
colorbg10 = 'green'
if newRollsList[9] == 'black':
colorbg10 = 'black'
labelRolls1 = Label(root, bg = colorbg1, height = 1, width = 2).grid(row = 18, column = 16)
labelRollsw1 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 17)
labelRolls2 = Label(root, bg = colorbg2, height = 1, width = 2).grid(row = 18, column = 18)
labelRollsw2 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 19)
labelRolls3 = Label(root, bg = colorbg3, height = 1, width = 2).grid(row = 18, column = 20)
labelRollsw3 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 21)
labelRolls4 = Label(root, bg = colorbg4, height = 1, width = 2).grid(row = 18, column = 22)
labelRollsw4 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 23)
labelRolls5 = Label(root, bg = colorbg5, height = 1, width = 2).grid(row = 18, column = 24)
labelRollsw5 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 25)
labelRolls6 = Label(root, bg = colorbg6, height = 1, width = 2).grid(row = 18, column = 26)
labelRollsw6 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 27)
labelRolls7 = Label(root, bg = colorbg7, height = 1, width = 2).grid(row = 18, column = 28)
labelRollsw7 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 29)
labelRolls8 = Label(root, bg = colorbg8, height = 1, width = 2).grid(row = 18, column = 30)
labelRollsw8 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 31)
labelRolls9 = Label(root, bg = colorbg9, height = 1, width = 2).grid(row = 18, column = 32)
labelRollsw9 = Label(root, bg = 'white', text = ' ').grid(row = 18, column = 33)
labelRolls10 = Label(root, bg = colorbg10, height = 1, width = 2).grid(row = 18, column = 34)
def roulette3(color, money):
yes = 'yes'
no = 'no'
on = 'yes'
total_money = total.get()
number = int(num())
try:
if color == no and money == 1:
if number == 8:
colors('green\n')
if number <= 7:
colors('red\n')
if number >= 9:
colors('black\n')
if int(money) <= int(total_money) and int(money) > 0:
if color == 'green' or color == 'red' or color == 'black':
if number == 8:
if color == 'green':
total.set(int(total_money) + int(money) * 14 - int(money))
a = ('It was green! You won!')
# tkinter.messagebox.showinfo('You won', a)
colors('green\n')
elif color != 'green':
total.set(int(total_money) - int(money))
b = ('It was green! You lost!')
# tkinter.messagebox.showinfo('You lost', b)
colors('green\n')
if number <= 7:
if color == 'red':
total.set(int(total_money) + int(money) * 2 - int(money))
c = ('It was red! You won!')
# tkinter.messagebox.showinfo('You won', c)
colors('red\n')
elif color != 'red':
total.set(int(total_money) - int(money))
d = ('It was red! You lost!')
# tkinter.messagebox.showinfo('You lost', d)
colors('red\n')
if number >= 9:
if color == 'black':
total.set(int(total_money) + int(money) * 2 - int(money))
e = ('It was black! You won!')
# tkinter.messagebox.showinfo('You won', e)
colors('black\n')
elif color != 'black':
total.set(int(total_money) - int(money))
f = ('It was black! You lost!')
# tkinter.messagebox.showinfo('You lost', f)
colors('black\n')
else:
g = ('you are unable to play with this amount')
# tkinter.messagebox.showinfo('Wrong Amount', g)
nothing()
except:
tkinter.messagebox.showinfo('Invalid Input', 'Invalid Input')
nothing()
total = StringVar()
total.set('1000')
yourMoney = Label(root, text = 'Your Money:')
yourMoney.grid(row = 1, column = 0)
all_money = Label(root, textvariable = total)
all_money.grid(row = 1, column = 1)
roulette = Label(root, text = 'Roulette', bg = 'red', fg = 'black')
roulette.grid(row = 0, column = 1, sticky = N)
moneyLabel = Label(root, text = 'How much:')
entry_money = Entry(root, textvariable = money2)
moneyLabel.grid(row = 2, column = 1)
entry_money.grid(row = 3, column = 1)
selectcolor = Label(root, text = 'Select your color:')
selectcolor.grid(row = 5, column = 0)
redB = Checkbutton(root, text = 'Red', variable = varred, onvalue = 'on', offvalue = 'off')
redB.grid(row = 4, column = 1)
blackB = Checkbutton(root, text = 'Black', variable = varblack, onvalue = 'on', offvalue = 'off')
blackB.grid(row = 5, column = 1)
greenB = Checkbutton(root, text = 'Green', variable = vargreen, onvalue = 'on', offvalue = 'off')
greenB.grid(row = 6, column = 1)
#playButton = Button(root, text = 'Play', command = play).grid(row = 4, column = 5)
#dontroll = Button(root, text = 'Wait for next Roll', command = nothing).grid(row = 3, column = 3)
lastrolls = Label(root, text = 'Last Rolls:')
lastrolls.grid(row = 18, column = 15)
zeit = Label(root, text = 'Time left until next roll:').grid(row = 1, column = 3)
timer = Label(root)
timer.grid(row = 1, column = 4)
allin = Button(root, text = 'All In', command = all).grid(row = 3, column = 3)
blackB.deselect()
greenB.deselect()
redB.deselect()
PrevRollsColor()
countdown(20)
#photo = PhotoImage(file = 'C:\\Users\\Louis\\Desktop\\roulette.png')
#label = Label(root, image=photo)
#label.grid(row = 7, column = 1)
root.geometry('1500x500+500+300')
root.title('roulette')
root.mainloop()
Related
This is a common arcade game, the goal is to hit all targets as many times as you can to earn the highest score. Every time the ball hits a "stone" you earn 1 point, and if it hits 2 you earn 2 points, respectively. If the player fails to catch the ball on the bar or "pole" then the game is over.
My assignment is to turn this game written in object-oriented programming into functional programming.
import time
class Ball:
def __init__(self, cvs, pole, stones, scre):
self.stones = stones
self.cvs = cvs
self.pole = pole
self.scre = scre
self.bottom_hit = False
self.hit = 0
self.id = canvas.create_oval(10, 10, 25, 25, fill="cadetblue", width=1)
self.cvs.move(self.id, 230, 461)
self.a = 3
self.b = -3
self.cvs.move(self.id, self.a, self.b)
self.cvs_height = canvas.winfo_height()
self.cvs_width = canvas.winfo_width()
def stone_strike(self, push):
for stone_line in self.stones:
for stone in stone_line:
stone_push = self.cvs.coords(stone.id)
try:
if push[2] >= stone_push[0] and push[0] <= stone_push[2]:
if push[3] >= stone_push[1] and push[1] <= stone_push[3]:
canvas.bell()
self.hit += 1
self.scre.configure(text="Score: " + str(self.hit))
self.cvs.delete(stone.id)
return True
except:
continue
return False
def pole_strike(self, push):
pole_push = self.cvs.coords(self.pole.id)
if push[2] >= pole_push[0] and push[0] <= pole_push[2]:
if push[3] >= pole_push[1] and push[1] <= pole_push[3]:
return True
return False
def draw(self):
self.cvs.move(self.id, self.a, self.b)
push = self.cvs.coords(self.id)
if self.stone_strike(push):
self.b = 3
if push[1] <= 0:
self.b = 3
if push[3] >= self.cvs_height:
self.bottom_hit = True
if push[0] <= 0:
self.a = 3
if push[2] >= self.cvs_width:
self.a = -3
if self.pole_strike(push):
self.b = -3
class Pole:
def __init__(self, cvs):
self.cvs = cvs
self.id = canvas.create_rectangle(0, 0, 100, 10, fill="darkgoldenrod")
self.cvs.move(self.id, 200, 485)
self.a = 0
self.cvs_width = canvas.winfo_width()
self.cvs.bind_all("<Left>", self.turn_left)
self.cvs.bind_all("<Right>", self.turn_right)
def draw(self):
push = self.cvs.coords(self.id)
if push[0] + self.a <= 0:
self.a = 0
if push[2] + self.a >= self.cvs_width:
self.a = 0
self.cvs.move(self.id, self.a, 0)
def turn_left(self, event):
self.a = -5
def turn_right(self, event):
self.a = 5
class Stone:
def __init__(self):
self.id = canvas.create_rectangle(5, 5, 25, 25, fill="firebrick")
def start_game(event):
score.configure(text="Score: 00")
canvas.delete("all")
pole = Pole(canvas)
stones = []
for i in range(0, 5):
b = []
for j in range(0, 19):
tmp = Stone()
b.append(tmp)
stones.append(b)
for i in range(0, 5):
for j in range(0, 19):
canvas.move(stones[i][j].id, 25 * j, 25 * i)
ball = Ball(canvas, pole, stones, score)
root.update()
time.sleep(1)
while 1:
if not ball.bottom_hit:
ball.draw()
pole.draw()
root.update()
time.sleep(0.01)
if ball.hit == 95:
canvas.create_text(250, 250, text="YOU WON!!", fill="darkolivegreen", font="Calibri 24")
break
else:
canvas.create_text(250, 250, text="GAME OVER!!", fill="darkolivegreen", font="Calibri 24")
break
root = Tk()
root.title("Bounce Ball Game")
root.geometry("500x570")
root.resizable(0, 0)
canvas = Canvas(root, width=500, height=500, bd=0, bg="black")
canvas.pack(padx=10, pady=10)
canvas.create_text(250, 250, text="Press Enter to start Game!!", fill="darkolivegreen", font="Calibri 18")
score = Label(height=50, width=80, text="Score: 00", font="Calibri 14 italic")
score.pack(side="left")
root.bind_all("<Return>", start_game)
root.mainloop()
Here is the code I have written.. There must be logical errors since it's not working. Any ideas??
import time
def startgame(event):
score.configure(text="score:00")
canvas.delete("all")
canvas_width = canvas.winfo_width()
canvas_height = canvas.winfo_height()
pole = canvas.create_rectangle(0, 0, 100, 10, fill="darkgoldenrod")
canvas.move(pole, 200, 425)
pa = 0
def turn_left(event):
pa = -5
def turn_right(event):
pa = 5
def stone_strike(push):
for stone_line in stones:
for stone in stone_line:
stone_push = canvas.coords(stone)
try:
if push[2] >= stone_push[0] and push[0] <= stone_push[2]:
if push[3] >= stone_push[1] and push[1] <= stone_push[3]:
canvas.bell()
hit += 1
score.configure(text="score:" + str(hit))
stonaki.delete()
return True
except:
continue
return False
def pole_strike(push_b):
pole_push = canvas.coords(pole)
if push_b[2] >= pole_push[0] and push_b[0] <= pole_push[2]:
if push_b[3] >= pole_push[1] and push_b[1] <= pole_push[3]:
return True
return False
canvas.bind_all("<Left>", turn_left)
canvas.bind_all("<Right>", turn_right)
push_p = canvas.coords(pole)
if push_p[0] + pa <= 0:
pa = 0
if push_p[2] + pa >= canvas_width:
pa = 0
stones = []
for i in range(0, 5):
lista = []
for j in range(0, 19):
stonaki = canvas.create_rectangle(5, 5, 25, 25, fill="firebrick")
lista.append(stonaki)
stones.append(lista)
for i in range(0, 5):
for j in range(0, 19):
canvas.move(stones[i][j], 25 * j, 25 * i)
root.update()
bottom_hit = False
hit = 0
ball = canvas.create_oval(10, 10, 25, 25, fill="cadetblue", width=1)
canvas.move(ball, 230, 461)
ba = 3
bb = -3
canvas.move(ball, ba, bb)
push_b = canvas.coords(ball)
if stone_strike(push_b):
bb = 3
if push_b[1] <= 0:
bb = 3
if push_b[3] >= canvas_height:
bottom_hit = True
if push_b[0] <= 0:
ba = 3
if push_b[2] >= canvas_width:
ba = -3
if pole_strike(push_b):
bb = -3
time.sleep(1)
while 1:
if not bottom_hit:
root.update()
time.sleep(0.01)
if hit == 95:
canvas.create_text(250, 250, text="YOU WON!!", fill="darkolivegreen", font="Calibri 24")
break
else:
canvas.create_text(250, 250, text="GAME OVER!!", fill="darkolivegreen", font="Calibri 24")
break
root = Tk()
root.title("Bounce Ball Game")
root.geometry("500x570")
root.resizable(0, 0)
canvas = Canvas(root, width=500, height=500, bd=0, bg="black")
canvas.pack(padx=10, pady=10)
canvas.create_text(250, 250, text="Press Enter to start Game!!", fill="darkolivegreen", font="Calibri 18")
score = Label(height=50, width=80, text="Score: 00", font="Calibri 14 italic")
score.pack(side="left")
root.bind_all("<Return>", startgame)
root.mainloop()
In the process of turning this game written in object-oriented programming into functional programming, we need to take care of variables/widgets which are being used by every function. If we are making changes to some variable in a local function and want to retain the changes made after the function call ends, so I will be making those variables/widgets global.
Also, in the OOP code, changes are being made every time in the canvas using functions draw() for both "ball" and "pole". Hence making two functions for the same drawB() and drawP():
from tkinter import *
import time
def startgame(event):
score.configure(text="score:00")
canvas.delete("all")
canvas_width = canvas.winfo_width()
canvas_height = canvas.winfo_height()
global pole,pa, ba,bb,bottom_hit, hit,ball
pole = canvas.create_rectangle(0, 0, 100, 10, fill="darkgoldenrod")
canvas.move(pole, 200, 425)
pa = 0
def turn_left(event):
global pa
pa = -5
def turn_right(event):
global pa
pa = 5
def stone_strike(push):
global stones, hit
for stone_line in stones:
for stone in stone_line:
stone_push = canvas.coords(stone)
try:
if push[2] >= stone_push[0] and push[0] <= stone_push[2]:
if push[3] >= stone_push[1] and push[1] <= stone_push[3]:
canvas.bell()
hit += 1
score.configure(text="score:" + str(hit))
canvas.delete(stone) #what to delete
return True
except:
continue
return False
def pole_strike(push_b):
global pole
pole_push = canvas.coords(pole)
if push_b[2] >= pole_push[0] and push_b[0] <= pole_push[2]:
if push_b[3] >= pole_push[1] and push_b[1] <= pole_push[3]:
return True
return False
canvas.bind_all("<Left>", turn_left)
canvas.bind_all("<Right>", turn_right)
def drawP():
global pa,pole
push_p = canvas.coords(pole)
if push_p[0] + pa <= 0:
pa = 0
if push_p[2] + pa >= canvas_width:
pa = 0
canvas.move(pole, pa, 0)
global stones
stones = []
for i in range(0, 5):
lista = []
for j in range(0, 19):
stonaki = canvas.create_rectangle(5, 5, 25, 25, fill="firebrick")
lista.append(stonaki)
stones.append(lista)
for i in range(0, 5):
for j in range(0, 19):
canvas.move(stones[i][j], 25 * j, 25 * i)
bottom_hit = False
hit = 0
ball = canvas.create_oval(10, 10, 25, 25, fill="cadetblue", width=1)
canvas.move(ball, 230, 461)
ba = 3
bb = -3
root.update()
def drawB():
global ba,bb,bottom_hit, hit,ball,pole
canvas.move(ball, ba, bb)
push_b = canvas.coords(ball)
if stone_strike(push_b):
bb = 3
if push_b[1] <= 0:
bb = 3
if push_b[3] >= canvas_height:
bottom_hit = True
if push_b[0] <= 0:
ba = 3
if push_b[2] >= canvas_width:
ba = -3
if pole_strike(push_b):
bb = -3
time.sleep(1)
while 1:
if not bottom_hit:
drawB()
drawP()
root.update()
time.sleep(0.01)
if hit == 95:
canvas.create_text(250, 250, text="YOU WON!!", fill="darkolivegreen", font="Calibri 24")
break
else:
canvas.create_text(250, 250, text="GAME OVER!!", fill="darkolivegreen", font="Calibri 24")
break
root = Tk()
root.title("Bounce Ball Game")
root.geometry("500x570")
root.resizable(0, 0)
canvas = Canvas(root, width=500, height=500, bd=0, bg="black")
canvas.pack(padx=10, pady=10)
canvas.create_text(250, 250, text="Press Enter to start Game!!", fill="darkolivegreen", font="Calibri 18")
score = Label(height=50, width=80, text="Score: 00", font="Calibri 14 italic")
score.pack(side="left")
root.bind_all("<Return>", startgame)
root.mainloop()
You may further optimize this code.
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.
Please give me advice.
Custom message box requirements include:
Be modal (Realized)
While the message box is displayed, the message box is on the front and other TK objects cannot be operated.
Wait for the return value of the message box
I want to wait for the message box input before moving on to the next action (display / hide widget etc.).
I want to continue processing the application(Realized)
The original Tk object wants to continue regular processing with the after method.
I want to adopt my own design(Realized)
In order to unify the design.
-Execution result-
If you close the message box, an error is displayed.
It will not proceed to the second line in the Btn_Messagebox_clicked method until self.MainWindow_obj is closed.
I don't know why I get an error. Also, if you close the message box, you won't know why it won't come back.
invalid command name "2291801753672dialog_mouse_release"
while executing
"2291801753672dialog_mouse_release 105 1 ?? ?? ?? 264 103442140 ?? 22 6 ?? 0 ?? ?? .!frame3.!button2 5 438 422 ??"
invoked from within
"if {"[2291801753672dialog_mouse_release 105 1 ?? ?? ?? 264 103442140 ?? 22 6 ?? 0 ?? ?? .!frame3.!button2 5 438 422 ??]" == "break"} break"
(command bound to event)
-code-
import tkinter as tk
from tkinter import ttk
from PIL import Image,ImageTk,ImageDraw,ImageFont
class CustomDialog(object):
def __init__(self):
self.title_bar_color = '#8FAADC'
self.item_ground_color = 'whitesmoke'
self.background_color = '#D9D9D9'
self.select_bar_color = '#BDD7EE'
self.isDrag_DlgMotion = False
self.drag_dx = 0
self.drag_dy = 0
def dialog_left_click(self,event):
dialog_x=self.dev_dialog.winfo_rootx()
dialog_y=self.dev_dialog.winfo_rooty()
point_x=self.dev_dialog.winfo_pointerx()
point_y=self.dev_dialog.winfo_pointery()
dx = point_x - dialog_x
dy = point_y - dialog_y
if (dx >= 0 and dx <= self.title_bar_width) and (dy >= 0 and dy <= self.title_bar_height):
self.drag_dx = dx
self.drag_dy = dy
self.isDrag_DlgMotion = True
return
def dialog_mouse_move_on(self,event):
if self.isDrag_DlgMotion:
X = event.x_root - self.drag_dx
Y = event.y_root - self.drag_dy
self.dev_dialog.geometry('+{0}+{1}'.format(X, Y))
pass
return
def dialog_mouse_release(self,event):
if self.isDrag_DlgMotion:
self.isDrag_DlgMotion = False
return
class CommonMessageBoxDialog(CustomDialog):
def __init__(self,title,message,state,parent = None):
self.return_state = None
if not isinstance(title,str) or not isinstance(message,str) or not isinstance(state,int):
return
if state < 1 or state > 3 :
return
root = ttk.tkinter.Tk()
#root = tk.Toplevel(parent)
#root.overrideredirect(True)
super().__init__()
self.box_state = state
self.box_message = message
self.box_title = title
W = 0
H = 1
self.dlg_size = [400,200]
self.title_bar_width = self.dlg_size[W]
self.title_bar_height = 40
self.btn_bar_height = 42
self.btn_32x32_size = 42
self.row_height = 28
self.btn_row_height = 32
self.frm_space = 10
self.parent = parent
self.CreateDialog(root)
root.wait_window(root)
#root.mainloop()
def CreateDialog(self,root):
W = 0
H = 1
if self.parent != None:
self.parent.update_idletasks()
ww=self.parent.winfo_screenwidth()
wh=self.parent.winfo_screenheight()
x=self.parent.winfo_rootx()
y=self.parent.winfo_rooty()
parent_w = self.parent.winfo_width()
parent_h = self.parent.winfo_height()
parent_x = self.parent.winfo_x()
parent_y = self.parent.winfo_y()
else:
root.update_idletasks()
ww=root.winfo_screenwidth()
wh=root.winfo_screenheight()
x=root.winfo_rootx()
y=root.winfo_rooty()
parent_w = root.winfo_width()
parent_h = root.winfo_height()
parent_x = root.winfo_x()
parent_y = root.winfo_y()
self.dev_dialog = root
dialog = self.dev_dialog
dialog.overrideredirect(True)
dlg_x = int((parent_x+parent_w) - (self.dlg_size[W]/2))
dlg_y = int((parent_y+parent_h) - (self.dlg_size[H]/2))
if dlg_x < 0 : dlg_x = 0
if dlg_y < 0 : dlg_y = 0
dialog.geometry('{}x{}+{}+{}'.format(self.dlg_size[W],self.dlg_size[H],dlg_x,dlg_y))
self.Title_Bar = tk.Frame(
dialog,
relief='flat',
bg = self.title_bar_color ,
)
self.Title_Label = tk.Label(
self.Title_Bar,
bg = self.title_bar_color ,
text = self.box_title,
)
dialog.bind('<Button-1>', self.dialog_left_click)
dialog.bind('<B1-Motion>', self.dialog_mouse_move_on)
dialog.bind('<ButtonRelease-1>',self.dialog_mouse_release)
self.MsgArea_frame = tk.Frame(
dialog,
relief='flat',
bg = self.select_bar_color,
)
self.message_frame = tk.Frame(
self.MsgArea_frame,
relief='flat',
bg = self.item_ground_color ,
)
self.label_message = tk.Label(
self.message_frame,
bg = self.item_ground_color ,
text = self.box_message,
)
self.BtnArea_frame = tk.Frame(
dialog,
relief='flat',
bg = self.item_ground_color,
)
self.btn_ok = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'OK',
command = lambda:self.btn_msgbox_clicked(1),
)
self.btn_yes = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'YES',
command = lambda:self.btn_msgbox_clicked(1),
)
self.btn_no = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'NO',
command = lambda:self.btn_msgbox_clicked(2),
)
self.btn_cancel = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'CANCEL',
command = lambda:self.btn_msgbox_clicked(3),
)
frm_space = self.frm_space
msg_frm_w = 4
btn_fram_h = 36
message_area_h = self.dlg_size[H] - self.title_bar_height - frm_space *2 - btn_fram_h
# Frame
self.Title_Bar.place(
x = 0, y = 0,
width = self.title_bar_width, height = self.title_bar_height
)
self.MsgArea_frame.place(
x = frm_space, y = self.title_bar_height + frm_space,
width = self.title_bar_width - frm_space*2, height = message_area_h
)
self.BtnArea_frame.place(
x = 0, y = self.title_bar_height + frm_space + message_area_h,
width = self.title_bar_width, height = btn_fram_h
)
self.Title_Label.grid(row = 0, column = 1,sticky = tk.W+tk.N+tk.S)
self.Title_Bar.columnconfigure(0,minsize = self.frm_space)
self.Title_Bar.rowconfigure(0,minsize = self.title_bar_height)
self.MsgArea_frame.columnconfigure(0,minsize = self.frm_space)
self.MsgArea_frame.rowconfigure(0,minsize = message_area_h)
self.BtnArea_frame.rowconfigure(0,minsize = btn_fram_h)
self.message_frame.place(
x = msg_frm_w, y = msg_frm_w,
width = self.title_bar_width - frm_space*2 - msg_frm_w*2, height = message_area_h - msg_frm_w*2,
)
# self.message_frame
self.label_message.grid(row = 0, column = 1,sticky = tk.W+tk.N+tk.S)
if self.box_state == 1:
self.btn_ok.place(
x = (self.title_bar_width/2) - 80/2 , y = btn_fram_h/2 - 24/2,
)
if self.box_state == 2:
self.btn_yes.place(
x = (self.title_bar_width/2) - (80 + frm_space) , y = btn_fram_h/2 - 24/2,
)
self.btn_no.place(
x = (self.title_bar_width/2) + frm_space , y = btn_fram_h/2 - 24/2,
)
if self.box_state == 3:
self.btn_yes.place(
x = (self.title_bar_width/2) - (80*1.5 + frm_space*2) , y = btn_fram_h/2 - 24/2,
)
self.btn_no.place(
x = (self.title_bar_width/2) - 80/2 , y = btn_fram_h/2 - 24/2,
)
self.btn_cancel.place(
x = (self.title_bar_width/2) + 80/2 + frm_space*2 , y = btn_fram_h/2 - 24/2,
)
#dialog.grab_set()
dialog.grab_set_global()
def btn_msgbox_clicked(self,state):
self.return_state = state
self.dev_dialog.grab_release()
self.dev_dialog.destroy()
def get_return_state(self):
return self.return_state
class CreateScreen(object):
def __init__(self):
self.cnt = 0
W = 0
H = 1
self.dlg_size = [400,200]
geo_string = '{}x{}'.format(self.dlg_size[W],self.dlg_size[H])
self.MainWindow_obj = ttk.tkinter.Tk()
self.MainWindow_obj.geometry(geo_string)
self.CntSting = tk.StringVar()
self.CntSting.set('...')
Label_Conter_text = tk.Label(
self.MainWindow_obj,
textvariable = self.CntSting,
)
self.MsgSting = tk.StringVar()
self.MsgSting.set(str(self.cnt))
Label_Message_text = tk.Label(
self.MainWindow_obj,
textvariable = self.MsgSting,
)
Btn_Messagebox = tk.Button(
self.MainWindow_obj,
text = 'Push',
command = self.Btn_Messagebox_clicked
)
Label_Conter_text.pack()
Label_Message_text.pack()
Btn_Messagebox.pack()
self.MainWindow_obj.after(1000,self.loop_msg)
self.MainWindow_obj.mainloop()
def Btn_Messagebox_clicked(self):
self.dlg = CommonMessageBoxDialog(title='Test',message='Do you remember ?',state=3,parent =self.MainWindow_obj)
ret = self.dlg.get_return_state()
if ret == 1:
self.MsgSting.set('Yes')
if ret == 2:
self.MsgSting.set('No')
if ret == 3:
self.MsgSting.set('Cancel')
return
def loop_msg(self):
self.cnt += 1
self.MsgSting.set(str(self.cnt))
self.MainWindow_obj.after(1000,self.loop_msg)
if __name__ == '__main__':
screen_obj = CreateScreen()
I solved it myself.
I'm binding mouse events for custom dialog navigation.
Therefore, after Destroy was called, the dialog with the mouse release event discarded was notified and an error occurred.
To solve this, I made self.isDestroy, and in the btn_msgbox_clicked method, changed self.isDestroy to True and connected the dialog_mouse_release method to the destroy method.
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from PIL import Image,ImageTk,ImageDraw,ImageFont
import datetime
class CustomDialog(object):
def __init__(self):
self.title_bar_color = '#8FAADC'
self.item_ground_color = 'whitesmoke'
self.background_color = '#D9D9D9'
self.select_bar_color = '#BDD7EE'
self.isDrag_DlgMotion = False
self.drag_dx = 0
self.drag_dy = 0
def dialog_left_click(self,event):
dialog_x=self.dev_dialog.winfo_rootx()
dialog_y=self.dev_dialog.winfo_rooty()
point_x=self.dev_dialog.winfo_pointerx()
point_y=self.dev_dialog.winfo_pointery()
dx = point_x - dialog_x
dy = point_y - dialog_y
if (dx >= 0 and dx <= self.title_bar_width) and (dy >= 0 and dy <= self.title_bar_height):
self.drag_dx = dx
self.drag_dy = dy
self.isDrag_DlgMotion = True
return
def dialog_mouse_move_on(self,event):
if self.isDrag_DlgMotion:
X = event.x_root - self.drag_dx
Y = event.y_root - self.drag_dy
self.dev_dialog.geometry('+{0}+{1}'.format(X, Y))
pass
return
def dialog_mouse_release(self,event):
if self.isDrag_DlgMotion:
self.isDrag_DlgMotion = False
return
class CommonMessageBoxDialog(CustomDialog):
def __init__(self,title,message,state,parent = None):
self.return_state = None
self.isDestroy = False
if not isinstance(title,str) or not isinstance(message,str) or not isinstance(state,int):
return
if state < 1 or state > 3 :
return
root = ttk.tkinter.Tk()
#root = tk.Toplevel(parent)
#root.overrideredirect(True)
super().__init__()
self.box_state = state
self.box_message = message
self.box_title = title
W = 0
H = 1
self.dlg_size = [400,200]
self.title_bar_width = self.dlg_size[W]
self.title_bar_height = 40
self.btn_bar_height = 42
self.btn_32x32_size = 42
self.row_height = 28
self.btn_row_height = 32
self.frm_space = 10
self.parent = parent
self.CreateDialog(root)
root.wait_window(root)
#root.mainloop()
def CreateDialog(self,root):
W = 0
H = 1
if self.parent != None:
self.parent.update_idletasks()
ww=self.parent.winfo_screenwidth()
wh=self.parent.winfo_screenheight()
x=self.parent.winfo_rootx()
y=self.parent.winfo_rooty()
parent_w = self.parent.winfo_width()
parent_h = self.parent.winfo_height()
parent_x = self.parent.winfo_x()
parent_y = self.parent.winfo_y()
else:
root.update_idletasks()
ww=root.winfo_screenwidth()
wh=root.winfo_screenheight()
x=root.winfo_rootx()
y=root.winfo_rooty()
parent_w = root.winfo_width()
parent_h = root.winfo_height()
parent_x = root.winfo_x()
parent_y = root.winfo_y()
self.dev_dialog = root
dialog = self.dev_dialog
dialog.overrideredirect(True)
dlg_x = int((parent_x+parent_w) - (self.dlg_size[W]/2))
dlg_y = int((parent_y+parent_h) - (self.dlg_size[H]/2))
if dlg_x < 0 : dlg_x = 0
if dlg_y < 0 : dlg_y = 0
dialog.geometry('{}x{}+{}+{}'.format(self.dlg_size[W],self.dlg_size[H],dlg_x,dlg_y))
self.Title_Bar = tk.Frame(
dialog,
relief='flat',
bg = self.title_bar_color ,
)
self.Title_Label = tk.Label(
self.Title_Bar,
bg = self.title_bar_color ,
text = self.box_title,
)
dialog.bind('<Button-1>', self.dialog_left_click)
dialog.bind('<B1-Motion>', self.dialog_mouse_move_on)
dialog.bind('<ButtonRelease-1>',self.dialog_mouse_release)
self.MsgArea_frame = tk.Frame(
dialog,
relief='flat',
bg = self.select_bar_color,
)
self.message_frame = tk.Frame(
self.MsgArea_frame,
relief='flat',
bg = self.item_ground_color ,
)
self.label_message = tk.Label(
self.message_frame,
bg = self.item_ground_color ,
text = self.box_message,
)
self.BtnArea_frame = tk.Frame(
dialog,
relief='flat',
bg = self.item_ground_color,
)
self.btn_ok = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'OK',
command = lambda:self.btn_msgbox_clicked(1),
)
self.btn_yes = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'YES',
command = lambda:self.btn_msgbox_clicked(1),
)
self.btn_no = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'NO',
command = lambda:self.btn_msgbox_clicked(2),
)
self.btn_cancel = tk.Button(
self.BtnArea_frame,
bg = self.item_ground_color,
text = 'CANCEL',
command = lambda:self.btn_msgbox_clicked(3),
)
frm_space = self.frm_space
msg_frm_w = 4
btn_fram_h = 36
message_area_h = self.dlg_size[H] - self.title_bar_height - frm_space *2 - btn_fram_h
# Frame
self.Title_Bar.place(
x = 0, y = 0,
width = self.title_bar_width, height = self.title_bar_height
)
self.MsgArea_frame.place(
x = frm_space, y = self.title_bar_height + frm_space,
width = self.title_bar_width - frm_space*2, height = message_area_h
)
self.BtnArea_frame.place(
x = 0, y = self.title_bar_height + frm_space + message_area_h,
width = self.title_bar_width, height = btn_fram_h
)
self.Title_Label.grid(row = 0, column = 1,sticky = tk.W+tk.N+tk.S)
self.Title_Bar.columnconfigure(0,minsize = self.frm_space)
self.Title_Bar.rowconfigure(0,minsize = self.title_bar_height)
self.MsgArea_frame.columnconfigure(0,minsize = self.frm_space)
self.MsgArea_frame.rowconfigure(0,minsize = message_area_h)
self.BtnArea_frame.rowconfigure(0,minsize = btn_fram_h)
self.message_frame.place(
x = msg_frm_w, y = msg_frm_w,
width = self.title_bar_width - frm_space*2 - msg_frm_w*2, height = message_area_h - msg_frm_w*2,
)
# self.message_frame
self.label_message.grid(row = 0, column = 1,sticky = tk.W+tk.N+tk.S)
if self.box_state == 1:
self.btn_ok.place(
x = (self.title_bar_width/2) - 80/2 , y = btn_fram_h/2 - 24/2,
)
if self.box_state == 2:
self.btn_yes.place(
x = (self.title_bar_width/2) - (80 + frm_space) , y = btn_fram_h/2 - 24/2,
)
self.btn_no.place(
x = (self.title_bar_width/2) + frm_space , y = btn_fram_h/2 - 24/2,
)
if self.box_state == 3:
self.btn_yes.place(
x = (self.title_bar_width/2) - (80*1.5 + frm_space*2) , y = btn_fram_h/2 - 24/2,
)
self.btn_no.place(
x = (self.title_bar_width/2) - 80/2 , y = btn_fram_h/2 - 24/2,
)
self.btn_cancel.place(
x = (self.title_bar_width/2) + 80/2 + frm_space*2 , y = btn_fram_h/2 - 24/2,
)
#dialog.grab_set()
dialog.grab_set_global()
def btn_msgbox_clicked(self,state):
self.return_state = state
self.isDestroy = True
def get_return_state(self):
return self.return_state
def dialog_mouse_release(self,event):
if self.isDrag_DlgMotion:
self.isDrag_DlgMotion = False
if self.isDestroy:
self._quit()
return
def _quit(self):
self.dev_dialog.grab_release()
self.dev_dialog.destroy()
class CreateScreen(object):
def __init__(self):
self.cnt = 0
W = 0
H = 1
self.dlg_size = [400,200]
geo_string = '{}x{}'.format(self.dlg_size[W],self.dlg_size[H])
self.MainWindow_obj = ttk.tkinter.Tk()
self.MainWindow_obj.geometry(geo_string)
self.CntSting = tk.StringVar()
self.CntSting.set(str(self.cnt))
Label_Conter_text = tk.Label(
self.MainWindow_obj,
textvariable = self.CntSting,
)
self.MsgSting = tk.StringVar()
self.MsgSting.set('...')
Label_Message_text = tk.Label(
self.MainWindow_obj,
textvariable = self.MsgSting,
)
Btn_Messagebox = tk.Button(
self.MainWindow_obj,
text = 'Push',
command = self.Btn_Messagebox_clicked
)
Label_Conter_text.pack()
Label_Message_text.pack()
Btn_Messagebox.pack()
self.MainWindow_obj.after(1000,self.loop_msg)
self.MainWindow_obj.mainloop()
def Btn_Messagebox_clicked(self):
self.dlg = CommonMessageBoxDialog(title='Test',message='Do you remember ?',state=3,parent =self.MainWindow_obj)
ret = self.dlg.get_return_state()
if ret == 1:
self.MsgSting.set('Yes')
if ret == 2:
self.MsgSting.set('No')
if ret == 3:
self.MsgSting.set('Cancel')
return
def loop_msg(self):
self.cnt += 1
self.CntSting.set(str(self.cnt))
self.MainWindow_obj.after(1000,self.loop_msg)
if __name__ == '__main__':
screen_obj = CreateScreen()
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.
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