Tkinter Pressing Buttons to produce a list - python

I'm trying to make a system where buttons are generated from a list, then as each one is pressed that button disappears and updates a value in a list it has created of equal length in the order the buttons were pressed i.e. [1,3,2,4] would mean that the first button was pressed first, then the 3rd, 2nd etc.
I've currently have it at the stage where the buttons will disappear but I can't yet have it increment its order or produce a list.
def buttonSelected(k, buttonNames, order, itemButton, buttonOrder):
order = order + 1
itemButton[k].destroy()
buttonOrder[k] = order
orderText = ["first, second, third"]
if order <= 2:
lbl.configure(text="Which button do you want to click first?")
else:
lbl.configure(text="Which button do you want to click %sth?" % order)
return order
def chooseOrder(buttonNames, order, buttonOrder):
orderText = ["first, second, third"]
itemButton = []
for i in range(len(buttonNames)):
print i
itemButton.append('')
itemButton[i] = tkinter.Button(window, text=buttonNames[i], command=lambda c=i: buttonSelected(c, buttonNames, order, itemButton, buttonOrder), font=("Helvetica", 10))
itemButton[i].pack()
if order <= 2:
lbl.configure(text="Which button do you want to click first?")
else:
lbl.configure(text="Which button do you want to click %sth?" % order)
buttonOrder = []
for i in range(len(buttonNames)):
buttonOrder.append(0)
chooseOrder(buttonNames, 0, buttonOrder)
My order doesn't iterate because I haven't returned it and I don't know how to return a list either.
This is my complete code:
# import and rename the 'tkinter' module for < Python 3.3
import Tkinter as tkinter
import os
class Checkbar(tkinter.Frame):
def __init__(self, parent=None, picks=[], side=tkinter.TOP, anchor=tkinter.W):
tkinter.Frame.__init__(self, parent)
self.vars = []
for pick in picks:
var = tkinter.IntVar()
chk = tkinter.Checkbutton(self, text=pick, variable=var, font=("Helvetica", 10))
chk.pack(side=side, anchor=anchor, expand=tkinter.YES)
self.vars.append(var)
def state(self):
return map((lambda var: var.get()), self.vars)
def moduleSelected(k, wantedModules, order, itemButton, moduleOrder):
order = order + 1
#for j in range(len(itemButton)):
itemButton[k].destroy()
moduleOrder[k] = order
#chooseOrder(wantedModules, order)
orderText = ["first, second, third"]
if order <= 2:
lbl.configure(text="Which item do you want appearing first?")
else:
lbl.configure(text="Which item do you want appearing %sth?" % order)
if order == len(moduleOrder):
moduleOrder1Finished = 1
return order
def chooseOrder(wantedModules, order, moduleOrder):
orderText = ["first, second, third"]
itemButton = []
for i in range(len(wantedModules)):
print i
itemButton.append('')
itemButton[i] = tkinter.Button(window, text=wantedModules[i], command=lambda c=i: moduleSelected(c, wantedModules, order, itemButton, moduleOrder), font=("Helvetica", 10))
itemButton[i].pack()
print wantedModules
if order <= 2:
lbl.configure(text="Which button do you want appearing first?")
else:
lbl.configure(text="Which button do you want appearing %sth?" % order)
def chooseOrders(moduleList, moduleSelectColumn, order):
wantedModules = []
moduleOrder = []
for i in range(len(moduleList)):
if moduleList[i] == 1:
wantedModules.append(moduleSelectColumn[i])
moduleOrder.append(0)
chooseOrder(wantedModules, order, moduleOrder)
def modulesSelected(modules1, moduleSelectColumn1, modules2, moduleSelectColumn2, moduleSelectButton):
moduleList1 = modules1.state()
moduleList2 = modules2.state()
modules1.destroy()
modules2.destroy()
moduleSelectButton.destroy()
moduleOrder1 = chooseOrders(moduleList1, moduleSelectColumn1, 0)
moduleOrder2 = chooseOrders(moduleList2, moduleSelectColumn2, 0)
def produceSurvey():
moduleSelectColumn = []
for i in range(4):
moduleSelectColumn.append([])
moduleSelectColumn[1] = ['cheese', 'wine', 'bread', 'cereal']
moduleSelectButton = tkinter.Button(window, text="Finish Selecting", bg="#ffffff", font=("Helvetica", 16), command=lambda: modulesSelected(modules1, moduleSelectColumn[1], modules2,moduleSelectColumn[2], moduleSelectButton))
moduleSelectButton.pack(side=tkinter.TOP)
modules1 = Checkbar(window, moduleSelectColumn[1])
modules2 = Checkbar(window, moduleSelectColumn[2])
modules1.pack(side=tkinter.LEFT)
modules2.pack(side=tkinter.RIGHT)
lbl.configure(text="Select which buttons you want to Select?")
window.geometry("720x720")
def analSurvey():
print "analysing survey!"
def optionButton(option, option1, option2):
option1.destroy()
option2.destroy()
if option == 1:
produceSurvey()
elif option == 2:
analSurvey()
def callback_and_hide(button):
callback()
button.destroy()
def callback():
lbl.configure(text="What would you like to do?")
option1 = tkinter.Button(window, text="Help JameswDemps on stackexchange", bg="#ffffff", font=("Helvetica", 16), command=lambda: optionButton(1, option1, option2))
option1.pack()
option2 = tkinter.Button(window, text="go to a blank page", bg="#ffffff", font=("Helvetica", 16), command=lambda: optionButton(2, option1, option2))
option2.pack()
# create a new window
window = tkinter.Tk()
# set window title
window.title("Button Presser")
# Gets the requested values of the height and widht.
windowWidth = window.winfo_reqwidth()
windowHeight = window.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(window.winfo_screenwidth()/2 - windowWidth/2)
positionDown = int(window.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
window.geometry("+{}+{}".format(positionRight-250, positionDown-150))
window.geometry("720x480")
# set the window background to hex code ...
window.configure(background="#ffffff")
# create a label widget call 'lbl'
lbl = tkinter.Label(window, text="Welcome to the Button presser!", bg="#ffffff", font=("Helvetica", 24))
# creat a text entry widget called 'ent'
#ent = tkinter.Entry(window)
# create a button widget called btn
startBtn = tkinter.Button(window, text="Start", command=lambda: callback_and_hide(startBtn), font=("Helvetica", 16))
# pack (add) the widget into the window
lbl.pack()
#ent.pack()
startBtn.pack()
# draw the window, and start the 'application'
window.mainloop()

RESULT = []
def moduleSelected(k, wantedModules, order, itemButton, moduleOrder):
order = order + 1
#for j in range(len(itemButton)):
itemButton[k].destroy()
moduleOrder[k] = order
print k
RESULT.append(k+1)
print RESULT # -> This will print the output you want.
#chooseOrder(wantedModules, order)
orderText = ["first, second, third"]
if order <= 2:
lbl.configure(text="Which item do you want appearing first?")
else:
lbl.configure(text="Which item do you want appearing %sth?" % order)
if order == len(moduleOrder):
moduleOrder1Finished = 1
return order
I have added a RESULT list to store the order of buttons in which they are clicked.

Related

Run functions from list

trying to get the selected values from a list of checkbutton without having to create 10 or more checbutton and var.
i got this to test the idea
from tkinter import Tk, StringVar, Checkbutton, Button, BooleanVar
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
def def1():
print("1")
def def2():
print("2")
def def3():
print("3")
def def4():
print("4")
def def5():
print("5")
def def6():
print("6")
def letssee():
print(addlist)
nomtestes = ["def1", "def2", "def3", "def4", "def5", "def6"]
clltes = 0
rwwtes = 0
addlist=[]
username_cbs = dict()
for name in nomtestes:
if clltes == 5:
rwwtes += 1
clltes = 0
username_cbs[name] = Checkbutton(root, text=name, onvalue=True, offvalue=False)
username_cbs[name].var = BooleanVar()
username_cbs[name]['variable'] = username_cbs[name].var
username_cbs[name]['command'] = lambda w=username_cbs[name]: upon_select(w)
username_cbs[name].grid(row=rwwtes, column=clltes, pady=2)
clltes += 1
Button(root, text="OK",command=letssee).grid(column=0, row=5, padx=1, pady=15)
def upon_select(widget):
if widget.var.get() == True:
addlist.append(widget['text'])
else:
addlist.remove(widget['text'])
root.mainloop()
In this example im trying to print all the checkbuttons i selected, but, to run the funcions added to the addlist
Any ideia how to do this?
thanks
You can create a dictionary, mapping string values to respective functions, and then add or remove them to a list. You can add a function map and change the letssee() like this to check.
func_map = {"def1": def1, "def2": def2, "def3": def3, "def4": def4, "def5": def5, "def6": def6}
nomtestes = ["def1", "def2", "def3", "def4", "def5", "def6"]
def letssee():
print(addlist)
for i in addlist:
func_map[i]()
Out:['def2', 'def1']
2
1

How can I make a re-grading button from tkinter entry?

I was making a vocab test program and I was making a grading button. But I faced a problem that when I press the grading twice, grade, entries, right, wrong keeps appends and I can't find the way to reset these lists. So, when I press the grade button again after I correct the answer, the grading overlaps and makes an error.
import tkinter
from tkinter import *
window = tkinter.Tk()
container = tkinter.Frame(window)
canvas = tkinter.Canvas(container)
window.title('Rescue word test')
window.geometry('640x480')
window.resizable(True, True)
scrollbar = tkinter.Scrollbar(container, orient="vertical", command=canvas.yview)
#scroll
main_frame = Frame(window)
main_frame.pack(fill=BOTH, expand=1)
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)
my_scrollbar = tkinter.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_canvas.configure(yscrollcommand=my_scrollbar.set)
my_scrollbar.bind('<Configure>', lambda e: my_canvas.configure(scrollregion= my_canvas.bbox("all")))
second_frame = Frame(my_canvas)
my_canvas.create_window((0,0), window= second_frame, anchor="nw")
def mouse_scroll(event):
my_canvas.yview_scroll(-1 * int((event.delta / 120)), "units")
my_canvas.bind_all("<MouseWheel>", mouse_scroll)
def getEntry( i ):
return list( second_frame.children.values() )[ i ]
Day21_eng = ['exquisite', 'acquisition', 'regulate', 'transportation', 'insight', 'straightforward', 'cultivate', 'innovation', 'preserve', 'odor', 'exception', 'munch', 'proclaim', 'slap', 'variability', 'investigate', 'flare', 'outpace', 'genuine', 'plead', 'fossilize', 'toil', 'drastic', 'withhold', 'inanimate', 'clockwise', 'amnesia', 'revive', 'theorize', 'culprit', 'limp', 'worn-out', 'indignity', 'span', 'bribe']
Day21_kor = [['우아한', '정교한', '절묘한'], ['취득', '획득', '습득'], ['규제하다', '통제하다'], ['운송', '운임', '추방'], ['통찰', '통찰력'], ['명확한', '솔직한'], ['경작하다', '기르다', '장려하다', '육성하다'], ['혁신'], ['보전', '보호지', '보호하다', '보존하다'], ['냄새', '악취', '기미', '낌새'], ['예외'], ['우적우적 먹다'], ['선언하다'], ['찰싹 때리다'], ['변화성', '가변성', '변용성'], ['조사하다'], ['불끈 성나게 하다', '이글거리다', '불꽃', '타오름'], ['앞지르다', '속도가 더 빠르다'], ['진짜의', '진품의'], ['탄원하다', '변호하다', '애원하다'], ['고착화하다', '화석화하다'], ['수고', '노고', '힘들게 일하다'], ['급격한', '극단적인'], ['보류하다', '유보하다'], ['생명 없는', '무생물의'], ['시계방향으로'], ['기억상실'], ['부활시키다', '되살아나게 하다'], ['이론화하다'], ['죄인', '범죄자', '장본인'], ['절뚝거리다', '느릿느릿 가다', '기운이 없는','축 처진'], ['닳아빠진', '진부한', '지친'], ['모욕', '무례', '치욕'], ['기간', '폭', '범위', '걸치다', '이르다'], ['뇌물을 주다', '뇌물']]
entries = []
grade =[]
def check():
for i, e in enumerate(entries):
value = e.get()
grade.append(str(value in Day21_kor[i]))
right = [i for i, value in enumerate(grade) if value == 'True']
wrong = [k for k, value in enumerate(grade) if value == 'False']
print(right) # I can check that these lists keep appends
print(wrong)
print(entries)
print(grade)
r = 0
for i in range(0, len(right)):
label_right = Label(second_frame, text='O', fg='Blue')
label_right.grid(column=3, row= right[r])
r += 1
w = 0
for i in range(0, len(wrong)):
label_wrong = Label(second_frame, text='X', fg= 'red')
label_wrong.grid(column=3, row= wrong[w])
w += 1
b = 0
for row, item in enumerate(Day21_eng):
global label_word
label_word = tkinter.Label(second_frame, text= item)
label_word.grid(column=0, row=row)
b += 1
#입력 값 35개
entry = tkinter.Entry(second_frame, width=30)
entry.grid(row=row, column=1, sticky='nsew')
# important to bind each one for access
entry.bind('<Return>', getEntry)
entries.append(entry) # save 'entry' into list
b_check = tkinter.Button(second_frame, text='grade', command=check)
b_check.grid(columnspan=2, row=36)
window.mainloop()
How can I reset these lists so I can re-grade the answers? I've tried adding right=[] wrong=[] entries=[] grade=[] and also used another list to get rid of the overlapped values in the list,
def check():
for i in range(0,35):
test_try_list[test_try].append(entry) # save 'entry' into list
for i, e in enumerate(test_try_list[test_try]):
value = e.get()
i_list.append(i)
print(i_list)
if len(i_list) > 35:
for i in range(0, len(i_list)):
new_i_list.append(i_list[i] % 35)
for v in new_i_list:
if v not in new_i_list2:
new_i_list2.append(v)
print(new_i_list2)
but it still doesn't work. How can I make button to re-grade?
You can use grade.clear() to clear list
def check():
grade.clear()
or you have to use global to inform function that it has to assign new list to external/global variable
def check():
global grade
grade = []
But I would run it without all these lists
def check():
correct = 0
wrong = 0
for i, (e, expected) in enumerate(zip(entries, Day21_kor)):
value = e.get()
if value in expected:
correct += 1
label = Label(second_frame, text='O', fg='Blue')
else:
wrong += 1
label = Label(second_frame, text='X', fg= 'red')
label.grid(column=3, row=i)
percent = correct/(correct+wrong)
print('Correct:', correct, '| Wrong:', wrong, '| Percent: {:.1%}'.format(percent))
Result:
Correct: 0 | Wrong: 35 | Percent: 0.0%
Correct: 1 | Wrong: 34 | Percent: 2.9%

change button text, using button name

I have an issue, I created a table of buttons using a loop, and I saved the button's names in a list, now I want to change the text of the buttons when one button is clicked.
I don't konw how.
this is the loop where i create the table
def grid(n):
i = n*n
for widget in LeftFrame.winfo_children():
widget.destroy()
for i in range(n):
for row in range(n):
for col in range(n):
button = Button(LeftFrame, text=' ', width=12, height=6, command=lambda: checker(button, i))
button.grid(row=row, column=col)
button_identities.append(button)
and this is the function on click of the button
def checker(buttons, i):
print(i)
global click, button_identities
print(button_identities)
bname = (button_identities[i])
print(bname)
if buttons["text"] == ' ' and click == True:
buttons["text"] = 'X'
click = False
# scorekeeper()
elif buttons['text'] == ' ' and click == False:
buttons['text'] = 'O'
click = True
# scorekeeper()
there is a method to check the text from the button name in the last function
Try this:
from functools import partial
def grid(n):
for widget in LeftFrame.winfo_children():
widget.destroy()
for i in range(n):
for row in range(n):
for col in range(n):
button = Button(LeftFrame, text=' ', width=12, height=6)
# Assign the button a command
command = partial(checker, button)
button.config(command=command)
button.grid(row=row, column=col)
button_identities.append(button)
def checker(button):
# The argument is a button
global click
# If the cell is empty
if button.cget("text") == " ":
# If Xs are you play
if click:
# Change the text of the button
button.config(text="X")
click = False
# If Os are to play
else:
# Change the text of the button
button.config(text="O")
click = True
I usually use <widget>.cget("<parameter>") to get the parameter out of a widget and <widget>.config(parameter=<new value>) to assign it a new value. Also you can use functools.partial to pass in arguments for the button command.
so this is my take on this issue:
from tkinter import Tk, Button
root = Tk()
class EditableButton(Button):
def __init__(self, parent, row, col):
Button.__init__(self, parent)
self.parent = parent
self.row = row
self.col = col
self.tracker = 0
self.name_list = ['apple', 'pear']
print(len(self.name_list))
self.button = Button(self.parent, text=self.name_list[self.tracker], command=self.change_text)
self.button.grid(row=self.row, column=self.col)
def change_text(self):
if self.tracker < len(self.name_list) - 1:
self.tracker += 1
else:
self.tracker = 0
self.button.config(text=self.name_list[self.tracker])
n = 3
for row in range(n):
for col in range(n):
button = EditableButton(root, row, col)
root.mainloop()
basically what happens is You make a class that is like a template for buttons and each class object created by the loop is independent, each of them has their own spot in memory, so whenever You press the button it only calls the function in its own class

Python Tkinter Multiple buttons are getting created on clicking on radio buttons

These are few lines from my actual code - I am aware this is not the best way of writing a code, but as I am new and getting familiarize with Tkinter (py2) consider this as my scratch work.
I am listing a question and multiple options. When the user selects an option, a SUBMIT button is created and when clicks on SUBMIT button it will accordingly change the color of Option to green or red. If green then another NEXT button will be available to clean and move to next question.
The issue that I am facing is if a user selects option A but then without clicking the SUBMIT button selects another option the submit button multiplies. I want to destroy the unwanted buttons or even do not want to create multiple SUBMIT buttons.
Please do help in achieving the same.
import Tkinter
from Tkinter import *
import yaml
import random
grey = "#808080"
offwhite = "#e3e3e3"
filepath = "chapter-2.yaml"
tk = Tkinter.Tk()
tk.title("iCodet Learnings")
tk.geometry("800x600")
x = ''
tk.config(background=offwhite)
tk.resizable(0,0)
q_count = 0
def yaml_loader(filepath):
with open (filepath, "r") as fileread:
data = yaml.load(fileread)
return data
def cleaner(hint):
global rbutton
global q_count
global quest_label
global radio1
global button_game
quest_label.destroy()
radio1.destroy()
# destroys the radio buttons
for b in rbutton:
b.destroy()
# destroys the SUBMIT button
button_game.destroy()
# go to ext question
if hint == 'next':
q_count += 1
game_loop()
# This is display the first element from the yaml i.e the question
def display_question(questions, qc):
global quest_label
q = questions.keys()[qc]
a = questions[q]
v = a.keys()
quest_label = Label(tk, text = q, font = ("Consolas", 16), width = 500, justify = "center", wraplength = 400)
quest_label.pack(pady = (50,0))
return v
# This is for selecting the radio buttons
def selected():
global radio_default, button_next,radio1, val
global x, data,q_count, vali, rbutton, select_val
x = radio_default.get()
select_val = rbutton[x]
if q_count <= len(data):
q = data.keys()[q_count]
a = data[q] #second dictionary
v = a.keys() #second dictionary keys
# True or False from Yaml
val = a[v[x]][0]
press_button(val)
else:
print ("Mid way")
# This will list all the options under question
def display_answer(ans):
global radio1, rbutton
global x, q_count
global radio_default
radio_default = IntVar()
rbutton = []
rad_select = []
val_count = 0
for i in ans:
radio1 = Radiobutton(tk, text = i, font = ("times", 14, "bold"), value = val_count, variable = radio_default, command = selected, background = 'NavajoWhite3')
rbutton.append(radio1)
val_count += 1
radio1.pack(pady = (30,0))
radio_default.set(-1)
# This displays the SUBMIT buuton
def press_button(val):
global button_game
# true
if val:
button_game = Button(tk, text = 'SUBMIT', font = ("default", 15, "bold"), bg='orange', fg = 'white', border=2, height = 2, width = 8, command = lambda: cleaner('next'))
button_game.pack(pady = (30,0))
# false
elif not val:
print "Do nothing"
button_game = Button(tk, text = 'SUBMIT', font = ("default", 15, "bold"), bg='orange', fg = 'white', border=2, height = 2, width = 8, command = lambda: cleaner('stay'))
button_game.pack(pady = (30,0))
return True
def game_loop():
global q_count
global x, data
global quest_label, button_game
action = True
data = yaml_loader(filepath)
if q_count <= len(data)-1:
l_ans = display_question(data, q_count)
display_answer(l_ans)
else:
txt_label = Label(tk, text = "CONGRATULATIONS ON COMPLETING CHAPTER", font = ("Comicsans", 24, "bold"), background = offwhite, wraplength = 700)
txt_label.pack(pady = (100,0))
button_end = Button(tk, text = 'THANK YOU !', font = ("default", 15, "bold"), bg='saddle brown', fg = 'white', border=2, height = 3, width = 10, command = tk.destroy)
button_end.pack(pady = (50,0))
game_loop()
tk.mainloop()
chapter-1.yaml
> "What’s the complete name of Sachin Tendulkar ?":
> "Sachin Ramya Tendulkar":
> - False
> "Sachin Ramesh Tendulkar":
> - True
> "Sachin Tendehar":
> - False
> " Sachin 10dulkar":
> - False
> "Hint":
> - "biscuit & cookies"
As things are, each time press_button() is run, a new Button object is generated, and placed in the button_game variable. This does not remove or hide the previous button, which still exists in the packed UI.
A simple solution that would save the machine some work is to initialize the button only once, earlier in the code, but omit placing/displaying/packing it until that block within press_button() is run.
I was able to achieve what I was looking for with the help of config.
I created the SUBMIT button once at the beginning and then instead of calling the whole function again and again; I just replaced press_button with button_game.config(command = lambda: right(chapter, num_ques, topic, val))
Now I should write this code using class in python.

How to see which button is activated / determine right buttons are activated on python tkinter

I'm making a game that finding seven right buttons(It has a fixed answer) among 12 buttons by using tkinter. There are a total of 12 buttons, and only if all seven of them are clicked will win the game.
I'm curious about how to make the window to see which button is activated or inactivated, and how to make a function to determine whether one wins or loses. (when seven specific buttons are activated, it wins.)
++
game1=tkinter.Tk()
game1.title("Test")
game1.geometry("600x450")
button1 = Button(game1, text=' 1 ', fg='black', bg='red',
height=3, width=10)
button1.place(x=0,y=300)
button2 = Button(game1, text=' 2 ', fg='black', bg='red',
height=3, width=10)
button2.place(x=100,y=300)
game1.mainloop()
This is the first time using tkinter on python so actually I stopped after writing this really basic code.
The player can choose seven buttons until player itself clicks the "finish" button. (after click that button, player cannot modify anything.)
At first, I thought if I declare "num" and +=1 on that when the right buttons are clicked, but this trial failed because the player can choose whether one activates or inactivates until until player itself clicks the "finish" button. So I thought that this code needs the way to check the final statements of the buttons.
Is there any ways to use something like "if" statements on tkinter? (if players choose right seven buttons, so it is found that they're activated --> then player wins.)
EDIT - I've updated the code:
import tkinter as tk
import tkinter.ttk as ttk
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
from random import sample
tk.Tk.__init__(self, *args, **kwargs)
self.title("Buttons")
self.resizable(width=False, height=False)
row_count = 3
column_count = 4
self.winning_buttons_count = 7
assert 0 < self.winning_buttons_count <= row_count * column_count
winning_buttons_numbers = sample(range(0, row_count * column_count), k=self.winning_buttons_count)
self.selected_buttons_count = 0
self.selected_button_color = "gray"
self.correct_button_color = "green"
self.incorrect_button_color = "red"
self.missed_button_color = "orange"
self.default_button_color = tk.Button().cget("bg")
def on_press(button):
color = button.cget("bg")
if color == self.default_button_color and self.selected_buttons_count < self.winning_buttons_count:
button.configure(bg=self.selected_button_color)
button.configure(relief=tk.SUNKEN)
self.selected_buttons_count += 1
elif color == self.selected_button_color:
button.configure(bg=self.default_button_color)
button.configure(relief=tk.RAISED)
self.selected_buttons_count -= 1
def check_win():
selected_winning_count = 0
for button in self.buttons:
is_selected = button.cget("bg") == self.selected_button_color and \
button.cget("relief") == tk.SUNKEN
is_winning = button.number in winning_buttons_numbers
if is_selected:
if is_winning:
button.configure(bg=self.correct_button_color)
selected_winning_count += 1
else:
button.configure(bg=self.incorrect_button_color)
else:
if is_winning:
button.configure(bg=self.missed_button_color)
if selected_winning_count == self.winning_buttons_count:
self.finish_button.configure(text="You won!")
else:
self.finish_button.configure(text="Incorrect.")
self.buttons = []
for row in range(row_count):
for column in range(column_count):
button = tk.Button(self, text=" " * 8)
button.grid(row=row, column=column)
button.number = (row * column_count) + column
button.configure(command=lambda b=button: on_press(b))
self.buttons.append(button)
vertical_line = ttk.Separator(self, orient=tk.VERTICAL)
vertical_line.grid(row=0, column=column_count+1, rowspan=row_count, sticky="ns", padx=(8, 8))
self.finish_button = tk.Button(self, text="Did I win?", command=check_win)
self.finish_button.grid(row=row_count//2, column=column_count+2)
def main():
application = Application()
application.mainloop()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())

Categories

Resources