How to save docx file based on values chosen from tkinter? - python

Here is my code:
from tkinter import *
from docx import Document
root = Tk()
info = ["Option 1", "Option 2", "Option 3"]
vars = []
for idx,i in enumerate(info):
var = IntVar(value=0)
vars.append(var)
lblOption = Label(root,text=i)
btnYes = Radiobutton(root, text="Yes", variable=var, value=2)
btnNo = Radiobutton(root, text="No", variable=var, value=1)
btnNa = Radiobutton(root, text="N/A", variable=var,value=0)
lblOption.grid(column=4,row=idx, sticky = W)
btnYes.grid(column=1,row=idx)
btnNo.grid(column=2,row=idx)
btnNa.grid(column=3,row=idx)
def save():
document = Document()
#add table
table = document.add_table(1, 4)
#style table
table.style = 'Table Grid'
#populate header row
heading_cells = table.rows[0].cells
heading_cells[0].text = "Options"
heading_cells[1].text = "Yes"
heading_cells[2].text = "No"
heading_cells[3].text = "N/a"
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "*"
elif val == 1: # checks if no
cells[2].text = "*"
elif val == 0: # checks if N/A
cells[3].text = "*"
for x in cells[2].text:
if "*" in x:
print("Failed.docx")
elif "*" not in x:
print("Test.docx")
savebtn = Button(root, text = "Save", command = save).grid()
root.mainloop()
This is my previous question: Link
I have used one of the answers to combine it with my question.
What I am trying to achieve:
If no has been selected for any of the options via the radio buttons, then save the document as failed.docx if every option has been selected without any no's then save the file as Test.docx.
My problem is:
Why is my last for loop and if statement is not working.
When I select a no option it returns me Failed.docx. But if none of the no' is selected, it does nothing? does not run the elif statement at all.

In your code, you are writing to docx row by row by creating cells on each iteration.
cells is a row that contains three radiobutton values for a single option. Let's say if you choose Yes for option3, cells would contain [* '' ''] for its iteration.
cells[0] = *
cells[1] = ''
cells[2] = ''
Also when you try to iterate over cells[1].text, you are trying to iterate on an empty item. That's why it never gets into if-elif statements because it never gets into for loop.
(not sure if I managed to explain this clearly but if you use a value for non-selected radiobuttons or debugger, you can see quite clearly what's going on)
For a solution, since you want to check all values for a single column, you can use table.column.
for idx, item in enumerate(vars):
cells = table.add_row().cells
cells[0].text = info[idx] # gets the option name
val = item.get() #radiobutton value
if val == 2: # checks if yes
cells[1].text = "*"
cells[2].text = "not-selected"
cells[3].text = "not-selected"
elif val == 1: # checks if no
cells[2].text = "*"
cells[1].text = "not-selected"
cells[3].text = "not-selected"
elif val == 0: # checks if N/A
cells[3].text = "*"
cells[1].text = "not-selected"
cells[2].text = "not-selected"
fn = 'Test.docx'
for cell in table.columns[2].cells[1:4]: #column2 is No column, 1:4 excludes header cell
if cell.text == '*':
fn = 'Failed.docx'
break
print(fn)

Related

Python (docx) excel and word

how to remove internal borders of tables that are written to a Word file?
I create tables in a Word file, and write information from an excel file into them, and I want the tables in the Word to have no internal borders, I don’t know how to do it
reviewed everything that was possible, but still did not find it, they wrote a lot that table.style = 'Table Grid this removes internal borders, but this does not work
import tkinter as tk
from tkinter import filedialog
import openpyxl
import docx
from docx import Document
from docx.shared import Cm
# Create the main window
root = tk.Tk()
root.withdraw()
# Open a file dialog to select the Excel file
file_path = filedialog.askopenfilename(title="Select Excel file", filetypes=(("Excel files", "*.xlsx"), ("All files", "*.*")))
# Open the Excel file and select the worksheet
wb = openpyxl.load_workbook(file_path)
sheet = wb['Sheet1']
doc = Document()
section = doc.sections[0]
margin = docx.shared.Inches(0.1)
margin2 = docx.shared.Inches(0.5)
margin3 = docx.shared.Inches(0.3)
section.left_margin = margin3
section.right_margin = margin
section.top_margin = margin
section.bottom_margin = margin2
table_count = 0
row = None
for i in range(2, sheet.max_row + 1):
if sheet[f'B{i}'].value:
for j in range(int(sheet[f'F{i}'].value)):
# Check if we need to start a new row
if table_count % 2 == 0:
row = doc.add_table(rows=1, cols=2).rows[0]
row.height = Cm(3)
row.cells[0].width = Cm(25)
row.cells[1].width = Cm(25)
# Add a table to the current row
table = row.cells[table_count % 2].add_table(rows=7, cols=2)
table.style = 'Table Grid'
table.autofit = False
# Remove internal borders from the table
# Merge the first row
table.cell(0, 0).merge(table.cell(0, 1))
table.cell(6, 0).merge(table.cell(6, 1))
# Modify the width of the first column
for cell in table.columns[0].cells:
cell.width = Cm(2.5)
# Modify the width of the second column
for cell in table.columns[1].cells:
cell.width = Cm(5.5)
nos = sheet[f"B{i}"].value if sheet[f"B{i}"].value else "N/A"
nom_nr = sheet[f"J{i}"].value if sheet[f"J{i}"].value else "N/A"
kods = sheet[f"D{i}"].value if sheet[f"D{i}"].value else "N/A"
pas_nr = sheet[f"K{i}"].value if sheet[f"K{i}"].value else "N/A"
table.cell(0, 0).text = "Nos.: "
table.cell(0, 0).paragraphs[0].add_run(f"{nos}").bold = True
table.cell(1, 0).text = "Nom. Nr.: "
table.cell(1, 1).text = str(nom_nr)
table.cell(1, 1).paragraphs[0].runs[0].bold = True # make the variable bold
table.cell(2, 0).text = "Kods: "
table.cell(2, 1).text = str(kods)
table.cell(2, 1).paragraphs[0].runs[0].bold = True # make the variable bold
table.cell(3, 0).text = "Pas. Nr.: "
table.cell(3, 1).text = str(pas_nr)
table.cell(3, 1).paragraphs[0].runs[0].bold = True # make the variable bold
table.cell(4, 0).text = "Daudzums: "
table.cell(4, 1).text = "1000"
table.cell(4, 1).paragraphs[0].runs[0].bold = True # make the variable bold
table.cell(5, 0).text = " "
table.cell(5, 1).text = " "
table.cell(6, 0).text = "Izpildītājs: SIA “STS Group”\nCeļāres 2B, Spilve, Babītes pag.\nTel. 29211780"
# Increment the table count
table_count += 1
# Save the Word document
doc.save('data.docx')

in tkinter.entry using in for loop but when value changed that effect all entery

Here is the code of my application
problem
I have used tkinter Entry() method in for loop in ShowOpeanFile() function and I have make One global list variable where I stored the return value of Entry() but when I enter value in that Entry field it effect on all Entry. But I don't want that.
#importing Required library
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
import pandas as pd
from functools import reduce
#Global Variables to Store FilePath That OPEAN
Opean_file_path = []
#Making gloabl datagram object store variable
datgramoffileVariable = []
datagram_list = []
finaldatagram_list = []
#get Filename and qauntity
def getvalue(i):
if Opean_file_path[i][2].get().isnumeric():
return Opean_file_path[i][1],Opean_file_path[i][2].get(),Opean_file_path[i][0]
else:
return -1
#variable making function for file that map each open file during converxlsx function
def variablemaking(size):
temp = []
for number in range(size):
temp.append(str(number))
temp = (list(set(temp)))
datgramoffileVariable.clear()
for i in range(len(temp)):
datgramoffileVariable.append(temp[i])
#conevrting all file to dataGram using pandas library
def Converxlsx():
#makingVariable functioncall
variablemaking(len(Opean_file_path))
#Now variable Making function Done
#Go for the convert datagram to file
for i in range(len(datgramoffileVariable)):
datgramoffileVariable[i] = pd.DataFrame(pd.read_excel(Opean_file_path[i][0]))
for i in range(len(datgramoffileVariable)):
print(datgramoffileVariable[i])
#subpart of Compute function find in list return filepath
def find(target):
for i in range(len(Opean_file_path)):
if(Opean_file_path[i][1] == target):
return Opean_file_path[i][0]
return -1
def findindex(tar):
for i in range(len(Opean_file_path)):
print(Opean_file_path[i][0])
if(Opean_file_path[i][0] == tar):
return i
#ComputeFile function
def compute():
for i in range(len(Opean_file_path)):
v = getvalue(i)
if v == -1:
pass
else:
answerOffind = v[0]
if( answerOffind == -1):
if(label_for_error.cget('text') == "enter right file name"):
label_for_error.config(text="")
else:
label_for_error.config(text="enter right file name", fg='red')
else:
label_for_error.config(text="")
if(len(v[1]) == 0 or v[1].isalpha() or v[1] == ' '):
label_for_error.config(text="enter right Qauntity", fg='red')
pass
else:
if v[1].isnumeric():
if(label_for_error.cget('text') == "enter right Qauntity"):
label_for_error.config(text='')
indexofmaniuplation = findindex(v[2])
print(indexofmaniuplation)
datgramoffileVariable[indexofmaniuplation].qauntity = datgramoffileVariable[indexofmaniuplation].qauntity * int(v[1])
# opeanfile function
def ShowOpeanFile():
col = 0
ro = 0
for i in range(len(Opean_file_path)):
ro = ro + 1
for j in range(len(Opean_file_path[i])):
if j > 1:
Opean_file_path[i][j] = tk.Entry(window,width=20,textvariable=1)
Opean_file_path[i][j].grid(row=ro,column=col)
else:
e = tk.Entry(window, width=20, fg='blue')
e.grid(row=ro,column=col)
e.insert(tk.END,Opean_file_path[i][j])
col = col + 1
col = col - 2
for i in range(len(Opean_file_path)):
for j in range(len(Opean_file_path[i])):
print(Opean_file_path[i][j])
#browsefile function
def browseFiles():
#opeanFile only allow Excel file
'''
askopenfile return file path of selected file
it return type is String
'''
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = [("Excel file","*.xlsx"),("Excel file", "*.xls")]
)
#After getting filepath storing into Opean_file_path list
if(filename in Opean_file_path):
pass
else:
tmp = []
tmp.append(filename)
f=filename.split('/')
tmp.append(f[-1])
tmp.append('qauntitybox')
Opean_file_path.append(tmp)
print(tmp)
Converxlsx()
ShowOpeanFile()
# print(Opean_file_path)
#making final CSV File function.
def csv_making():
datagram_list.clear()
finaldatagram_list.clear()
#convert dataframe into list
for i in range(len(datgramoffileVariable)):
datagram_list.extend(datgramoffileVariable[i].values.tolist())
#find repted element and compute all at one single
repted_element = []
datagram_index_to_be_removed=[]
for i in range(len(datagram_list)):
temp_id = datagram_list[i][0]
temp_Qauntity = datagram_list[i][1]
for j in range(i+1,len(datagram_list)):
if datagram_list[j][0] == temp_id:
temp_Qauntity = temp_Qauntity + datagram_list[j][1]
datagram_index_to_be_removed.append(j)
datagram_index_to_be_removed.append(i)
if [temp_id,temp_Qauntity] not in repted_element and datagram_list[j][0] == temp_id:
repted_element.append([temp_id,temp_Qauntity])
datagram_index_to_be_removed = list(tuple(datagram_index_to_be_removed))
#remove repeted element
datagram_index_to_be_removed.sort()
for i in range(len(datagram_list)):
if i in datagram_index_to_be_removed:
pass
else:
finaldatagram_list.append(datagram_list[i])
#add repted_element
for i in repted_element:
finaldatagram_list.append(i)
#print final data
# print(finaldatagram_list)
#convert final list to csv
id = []
qauntityto = []
for i in range(len(finaldatagram_list)):
id.append(finaldatagram_list[i][0])
qauntityto.append(finaldatagram_list[i][1])
dict = {'id':id,'qauntity':qauntityto}
df = pd.DataFrame(data=dict)
pathofnewfile = df.to_csv('/home/vegg/Desktop/out.csv',index=False)
print(pathofnewfile)
label_for_error.config(text='file save at /home/vegg/Desktop/out.csv',fg='blue')
#UI
window = tk.Tk()
scrollbar = tk.Scrollbar()
frame = tk.Frame(window)
window.geometry("750x400")
label_for_qautity = tk.Label(window ,text="Enter the Qauntity",
width=50,height=3)
label_for_qautity.grid(column=2,row=0)
# Qauntity = tk.Entry()
# Qauntity.grid(column=2,row=1)
label_for_fileNamepath = tk.Label(window ,text="File Name path",
width=20,height=3)
label_for_fileNamepath.grid(column=0,row=0)
label_for_fileName = tk.Label(window ,text="File Name",
width=20,height=3)
label_for_fileName.grid(column=1,row=0)
label_for_error = tk.Label(window ,text="",
width=20,height=3)
label_for_error.grid(column=4,row=3)
button_explore = tk.Button(window,
text = "Browse Files here",
command=lambda :[browseFiles()] )
button_Compute = tk.Button(window,
text = "Compute File Data",
command=lambda :[compute()] )
button_CSV = tk.Button(window,
text = "Create CSV Here",
command=lambda :[csv_making()] )
button_explore.grid(column=4,row=0)
button_Compute.grid(column=4,row=1)
button_CSV.grid(column=4, row=2)
window.mainloop()
Image
I want to add different value for entry not same value effect to all entry.

Why is my data from my input field inputting all previous data input into my spreadsheet?

i am trying to get data from a text box to an excel document, i have this working but the only problem is that it adds the previous data submitted along with the data in the text box
Here is the get data code and the delete code I'm using.
def clear():
# clear the content of text entry box
name_field.delete(0, END)
build_field.delete(0, END)
price_field.delete(0, END)
contact_no_field.delete(0, END)
email_id_field.delete(0, END)
address_field.delete(0, END)
def insert():
# if user not fill any entry
# then print "empty input"
if (name_field.get() == "" and
build_field.get() == "" and
price_field.get() == "" and
contact_no_field.get() == "" and
email_id_field.get() == "" and
address_field.get() == ""):
print("empty input")
else:
# assigning the max row and max column
# value upto which data is written
# in an excel sheet to the variable
current_row = sheet.max_row
current_column = sheet.max_column
# get method returns current text
# as string which we write into
# excel spreadsheet at particular location
sheet.cell(row=current_row + 1, column=3).value = name_field.get()
sheet.cell(row=current_row + 1, column=5).value = build_field.get()
sheet.cell(row=current_row + 1, column=9).value = price_field.get()
sheet.cell(row=current_row + 1, column=6).value = contact_no_field.get()
sheet.cell(row=current_row + 1, column=7).value = email_id_field.get()
sheet.cell(row=current_row + 1, column=8).value = address_field.get()
Put the value inside a variable 1st then from variable to cell. This way you can clear the variable for each prompt and not just clearing the text box
name_field.delete(0, END)
nameValue = None
nameValue = name_field.get()
sheet.cell(row=current_row + 1, column=3).value = nameValue

how can I find out what button has been selected

I have a piece of code in python which generates buttons dependant on the rooms in a list in my database. I would like the code to return the room name on the button that I have selected and use it to store data in my database for that button
class buttongen():
def __init__(self,i,row):
self.i = i
self.row = row
self.roomname = self.row[0]
roomclicked = self.roomname
self.btn = Button(screen13, text=self.roomname, command=lambda :print("self.roomname"))
self.btn.grid(row=i, column=0)
Here is the class for each button and below is the code which gets the list of room names and prints them out as buttons. Is there a way I can store the text and use either .cget() or get() to return the name of the room
def search():
global screen13
global btn
global roomclicked
screen13 = Tk()
screen13.geometry("300x250")
screen13.title("Rooms")
sitename3_info = sitename.get().strip()
if sitename3_info:
cursor = cnn.cursor()
# combine the two SQL statements into one
sql = ("SELECT roomname FROM rooms, Sites "
"WHERE rooms.siteID_fk2 = Sites.siteID AND siteName = %s")
cursor.execute(sql, [sitename3_info])
rooms = cursor.fetchall()
# remove previous result (assume screen13 contains only result)
for w in screen13.winfo_children():
w.destroy()
if rooms:
for i, row in enumerate(rooms):
buttongen(i, row)
roomname = row[0]
roomclicked = roomname
btn = Button(screen13, text=roomname, command=lambda room=roomname: action(room))
btn.grid(row=i, column=0)
else:
Label(screen13, text="No room found").grid()
EDIT
this is the block to create the audit
def createaudit():
sitename2_info = sitename.get()
print(sitename2_info)
name2_info = name2.get()
print(name2_info)
name3_info = name3.get()
print(name3_info)
# Sql code for writing the data that was written in the regsitering page.
cursor = cnn.cursor()
# the site query matches the inputted username with the corresponding userID and inserts the userID into userID_fk
siteIDQuery = "SELECT siteID FROM Sites WHERE siteName = %s"
cursor.execute(siteIDQuery, [sitename2_info])
siteID_fetch = cursor.fetchall()
print(siteID_fetch[0][0])
sitequery = "INSERT INTO `audit`(`siteID_fk`, `auditor1`, `auditor2`) VALUES (%s, %s, %s)"
sitequery_vals = (siteID_fetch[0][0], name2_info, name3_info)
cursor.execute(sitequery, sitequery_vals)
# prints how many rows were inserted to make sure values are put into the database
print(cursor.rowcount)
cnn.commit()
if siteID_fetch:
for i in siteID_fetch:
search()
break
else:
failed2()
this is the block to print out the rooms within the site that's going to be audited
def search():
screen13 = Tk()
screen13.geometry("300x250")
screen13.title("Rooms")
sitename3_info = sitename.get().strip()
if sitename3_info:
cursor = cnn.cursor()
# combine the two SQL statements into one
sql = ("SELECT roomname FROM rooms, Sites "
"WHERE rooms.siteID_fk2 = Sites.siteID AND siteName = %s")
cursor.execute(sql, [sitename3_info])
rooms = cursor.fetchall()
# remove previous result (assume screen13 contains only result)
for w in screen13.winfo_children():
w.destroy()
if rooms:
for i, row in enumerate(rooms):
roomname = row[0]
btn = Button(screen13, text=roomname, command=lambda room=roomname: action(room))
btn.grid(row=i, column=0)
else:
Label(screen13, text="No room found").grid()
This is the block of code where I wish to answer questions for the room and store the answers in my database for it
def action(roomname):
global screen15
screen15 = Tk()
screen15.geometry("300x250")
screen15.title("Rooms")
global q1
global q2
global q3
q1 = StringVar()
q2 = StringVar()
q3 = StringVar()
Label(screen15, text = "Please enter details below", bg = "LightSkyBlue1", width = "300", height = "2").pack()
Label(screen15, text = "").pack()
Label(screen15, text = "01. Commodes CLEANING").pack()
q1_entry = Entry(screen15, textvariable = q1)
q1_entry.pack()
Label(screen15, text = "02. commodes NURSING").pack()
q2_entry = Entry(screen15, textvariable = q2)
q2_entry.pack()
Label(screen15, text = "03. Bathroom Hoists CLEANING").pack()
q3_entry = Entry(screen15, textvariable = q3)
q3_entry.pack()
Button(screen15, text = "Create an Audit", width = "12", height = "1", command = storescore).pack()
def storescore():
roomname2_info = buttongen(self.roomname).cget()
print(roomname2_info)
sitenameInfo = sitename.get()
# sql to store answer values
cursor = cnn.cursor()
siteID_fetch4 = "SELECT siteID FROM Sites WHERE siteName = %s"
cursor.execute(siteID_fetch4, [sitenameInfo])
siteID_fetch4 = cursor.fetchall()
print(siteID_fetch4[0][0])
roomsFID = "SELECT roomID FROM rooms WHERE siteID_fk2 = %s AND roomname = %s"
cursor.execute(roomsFID, [(siteID_fetch4[0][0]), (roomname2_info)])
roomsFID = cursor.fetchall()
print(roomsFID[0][0])
Code below will do the trick perfectly (just adjust it to your needs):
import tkinter as tk
def safe_to_sql(number):
print("Saving room {} into SQL ...".format(number))
#Save whatever you want
def addButton(window, buttons, room):
new_button = tk.Button(window, text = "Room:" + room, command = lambda: safe_to_sql(room))
new_button.pack()
buttons.append(new_button)
my_buttons = []
rooms = ["Room 1", "Super room 2", "Ever better one"]
window = tk.Tk()
for room in rooms:
addButton(window, my_buttons, room)
window.mainloop()
We are creating dynamical buttons.
To each button we connect this lambda function: command = lambda: safe_to_sql(room).

Python-Tk Inter Object Oriented Programming inheriting attributes

So my program is a quiz where there is a main class that is an overall reaction pathway with sub reaction pathways in other classes. How do I inherit the buttons and labels defined in one page like QUESTIONSTARTER and can be displayed on another class which is STAGE 2. This is a big problem for me i hope you can help me. These are examples of the 2 classes: (I couldnt add one more method in question starter) so I want buttons and labels from question starter to be inherited to stage 2 where i can grid the buttons into stage 2.
class SETOFQUESTIONS(QUESTIONSTARTER):
def __init__ (self):
self.NumberOfStages = NumberOfStages
self.StartingReactant = StartingReactant
def SetStages(self, NumberOfStages):
#If the quiz type is default and customised set number of stages to a minimum of 3 stages and a max of 5 stages for aliphatic reaction
#for aromatic -set min stages 2 and max stages 5
if "Default" == True:
self.NumberOfStages = 5
print ("Number Of Stages = ",NumberOfStages)
return NumberOfStages
else:
self.NumberOfStages = CustomisedNumberOfStages
print ("Number Of Stages = ",CustomisedNumberOfStages)
#Sets Max Number of Stages
def SetNonCompulsoryReagents(self):
SetCompulsoryReagentOptionList(self)
ReagentsList = []
while ReagentsList == True:
for count in range (len(ReagentsList)):
try:
sql = ("""SELECT ReagentName FROM NonCompulsoryReagentDatabase \
ORDER BY RAND() \
LIMIT 1""")
conn.execute(sql)
NonCompulsoryReagents = conn.fetchone()
except:
conn.rollback()
if NonCompulsoryReagents[0] != ReagentsList[count]:
ReagentsList.append(NonCompulsoryReagents[0])
ReagentsList = False
elif NonCompulsoryReagents[1] != ReagentsList[count]:
ReagentsList.append(NonCompulsoryReagents[1])
ReagentsList = False
elif NonCompulsoryReagents[2] != ReagentsList[count]:
ReagentsList.append(NonCompulsoryReagents[2])
ReagentsList = False
else:
ReagentsList = True
for Reagent in ReagentsList:
RandomReagent = random.choice(ReagentsList)
ReagentOption1 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(1))
ReagentOption2 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(2))
ReagentOption3 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(3))
ReagentOption4 = tk.Button(bottomFrame, text = RandomReagent, command=lambda: self.AllocatePoints(4))
def SetNonCompulsoryConditions(self):
SetCompulsoryConditionOptionList(self)
sql = ("""SELECT ConditionName FROM NonCompulsoryConditionsDatabase \
ORDER BY RAND () \
LIMIT 1""")
try:
conn.execute(sql)
NonCompulsoryConditions = conn.fetchone()
except:
conn.rollback()
while ConditionsList == True:
for count in range (len(ConditionsList)):
sql = ("""SELECT ConditionName FROM NonCompulsoryConditionsDatabase \
ORDER BY RAND() \
LIMIT 1""")
conn.execute(sql)
NonCompulsoryReagents = conn.fetchone()
if NonCompulsoryConditions[0] != ConditionsList[count]:
ConditionsList.append(NonCompulsoryReagents[0])
ConditionsList = False
elif NonCompulsoryConditions[1] != ConditionsList[count]:
ConditionsList.append(NonCompulsoryConditions[1])
ConditionsList = False
elif NonCompulsoryConditions[2] != ConditionsList[count]:
ConditionsList.append(NonCompulsoryConditions[2])
ConditionsList = False
else:
ConditionsList = True
for Condition in ConditionsList:
RandomCondition = random.choice(ConditionsList)
ConditionOption1 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(5))
ConditionOption2 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(6))
ConditionOption3 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(7))
ConditionOption4 = tk.Button(bottomFrame, text = RandomCondition, command=lambda: self.AllocatePoints(8))
#call at random the specific products from product database
#depending on class run
def ButtonPressed(self,ReagentsList):
ReagentsList[0] = CorrectReagent
self.CorrectReagent.configure(bg = 'green')
IncorrectReagentsList = []
IncorrectReagentsList.append(ReagentsList[1])
IncorrectReagentsList.append(ReagentsList[2])
IncorrectReagentsList.append(ReagentsList[3])
for Reagents in IncorrectReagentsList:
tk.Button[Reagents].configure(bg = "red")
ConditionsList[0] = CorrectCondition
self.CorrectCondition.configure(bg = "green")
IncorrectConditionsList = []
IncorrectConditionsList.append(ReagentsList[1])
IncorrectConditionsList.append(ReagentsList[2])
IncorrectConditionsList.append(ReagentsList[3])
for Reagents in IncorrectReagentsList:
tk.Button[Reagents].configure(bg = "red")
class STAGE2(SETOFQUESTIONS):
def __init__(self,parent, controller):
tk.Frame.__init__(self, parent)
QuestionFrame.tkraise()
controller.show_frame(QuestionFrame)
Question.pack(side = "top")
Question.grid()
ReagentOption1.grid(column = 0,row = 0)
ReagentOption2.grid(column = 0,row = 1)
ReagentOption3.grid(column = 0,row = 2)
ReagentOption4.grid(column = 0,row = 3)
ConditionOption1.grid(column = 0,row = 0)
ConditionOption2.grid(column = 0,row = 1)
ConditionOption3.grid(column = 0,row = 2)
ConditionOption4.grid(column = 0,row = 3)
Continue = tk.Button(StageFrame, text = "Continue", command=lambda: controller.show_frame(Stage2))
Continue.grid(column = 6)
PointsLabel.grid(row=0,column=6)
AttemptsDisplayed.grid(row=1,column=7)

Categories

Resources