Allow only one radiobutton selection in Tkinter at a time [duplicate] - python

This question already has answers here:
How to select only one Radiobutton in tkinter
(3 answers)
Closed 6 months ago.
I am trying to learn the basics of the tkinter module. I made this program where I have some questions and each question has some options. My options are displayed using radio button selection. I want to select one choice at a time for each question independently. Currently when I select the 1st option then the 1st option of every question is selected but I don't want the selection for other than the one I am on.
My second question is once the selection [is made] I want to use the selection results and compare them with the answer keys to see how many answers are correct. How do I store the user's answer for each question?
Output result:
Edit:
Sorry for not posting my code as well.
Here is my python file which I am working on.
from tkinter import *
guessOptions =[]
def display():
global guessOptions
if x.get() == 0:
guessOptions.append("A")
elif x.get() == 1:
guessOptions.append("B")
elif x.get() == 2:
guessOptions.append("C")
else:
guessOptions.append("D")
window = Tk()
answers = ['A', 'B', 'C', 'D']
questions = ["Who invented Bulb? ",
"Which is not passive component? ",
"Which is not related to computer? ",
"Opertor used for and operation? "]
options = [['A. Thomas Edison', 'B. Nikola Tesla', 'C. Albert
Einstien', 'D. Michael Faraday'],
['A. Inductor', 'B. op-amp', 'C. Capacitor', 'D.
Resistor'],
['A. RAM', 'B. SSD', 'C. Heat', 'D. Keyboard'],
['!', '~', '||', '&']]
x = IntVar()
for i in range(len(questions)):
label = Label(window,
text=questions[i],
font=('Arial', 15, 'bold'))
label.pack(anchor=W)
for j in range(len(options)):
checkButton = Radiobutton(window,
text=options[i][j],
variable=x,
value=[j],
padx=10,
font=('Arial', 10),
command=display
)
checkButton.pack(anchor=W)
window.mainloop()

Each group of answers to a question needs its own IntVar and you'll need to add a Button to trigger the answer checking process. I've done most of that in the code below, except that check_answers() function doesn't really do anything meaningful since you haven't specified exactly what would be involved (or even what the correct choices are).
from tkinter import *
guessOptions =[]
def display(x):
global guessOptions
if x.get() == 0:
guessOptions.append("A")
elif x.get() == 1:
guessOptions.append("B")
elif x.get() == 2:
guessOptions.append("C")
else:
guessOptions.append("D")
def check_answers():
print(f'{guessOptions=}')
window = Tk()
answers = ['A', 'B', 'C', 'D']
questions = ["Who invented bulb? ",
"Which is not passive component? ",
"Which is not related to computer? ",
"Operator used for and operation? "]
options = [['A. Thomas Edison', 'B. Nikola Tesla', 'C. Albert Einstein',
'D. Michael Faraday'],
['A. Inductor', 'B. Op-amp', 'C. Capacitor', 'D. Resistor'],
['A. RAM', 'B. SSD', 'C. Heat', 'D. Keyboard'],
['!', '~', '||', '&']]
variables = []
for i in range(len(questions)):
label = Label(window, text=questions[i], font=('Arial', 15, 'bold'))
label.pack(anchor=W)
var = IntVar(value=-1)
variables.append(var) # Save for possible later use - one per question.
def handler(variable=var):
"""Callback for this question and group of answers."""
display(variable)
for j in range(len(options)):
checkButton = Radiobutton(window, text=options[i][j], variable=var,
value=j, padx=10, font=('Arial', 10),
command=handler)
checkButton.pack(anchor=W)
comp_btn = Button(window, text="Check Answers", command=check_answers)
comp_btn.pack()
window.mainloop()

Related

How to restrict entry to only available options in AutocompleteCombobox while being able to type in it?

I am using AutocompleteCombobox from ttkwidgets.autocomplete for my selection widget. While all the features are good (like being able to filter the list while typing), I want to be able to type in it but only from the available options ie., I should not be able to type in custom values.
I tried using state=readonly but it doesn't allow me to type in the combobox.
Any solutions would be greatly appreciated.
Since You didn't provide example code and tkinter does not provide default autocomplete combobx, I assumed You are using AutocompleteCombobox from ttkwidgets.autocomplete.
To get only valid entries (no custom one), You have to re-implement autocomplete method of AutocompleteCombobox class.
Logic is simple: check if current user input is in autocomplete list. If not, remove last character and show again last autocomplete suggestion.
I used example code from this source as a base for my answer.
Here is code snippet implementing custom MatchOnlyAutocompleteCombobox:
from tkinter import *
from ttkwidgets.autocomplete import AutocompleteCombobox
countries = [
'Antigua and Barbuda', 'Bahamas', 'Barbados', 'Belize', 'Canada',
'Costa Rica ', 'Cuba', 'Dominica', 'Dominican Republic', 'El Salvador ',
'Grenada', 'Guatemala ', 'Haiti', 'Honduras ', 'Jamaica', 'Mexico',
'Nicaragua', 'Saint Kitts and Nevis', 'Panama ', 'Saint Lucia',
'Saint Vincent and the Grenadines', 'Trinidad and Tobago', 'United States of America'
]
ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#8DBF5A')
class MatchOnlyAutocompleteCombobox(AutocompleteCombobox):
def autocomplete(self, delta=0):
"""
Autocomplete the Combobox.
:param delta: 0, 1 or -1: how to cycle through possible hits
:type delta: int
"""
if delta: # need to delete selection otherwise we would fix the current position
self.delete(self.position, END)
else: # set position to end so selection starts where textentry ended
self.position = len(self.get())
# collect hits
_hits = []
for element in self._completion_list:
if element.lower().startswith(self.get().lower()): # Match case insensitively
_hits.append(element)
if not _hits:
# No hits with current user text input
self.position -= 1 # delete one character
self.delete(self.position, END)
# Display again last matched autocomplete
self.autocomplete(delta)
return
# if we have a new hit list, keep this in mind
if _hits != self._hits:
self._hit_index = 0
self._hits = _hits
# only allow cycling if we are in a known hit list
if _hits == self._hits and self._hits:
self._hit_index = (self._hit_index + delta) % len(self._hits)
# now finally perform the auto completion
if self._hits:
self.delete(0, END)
self.insert(0, self._hits[self._hit_index])
self.select_range(self.position, END)
frame = Frame(ws, bg='#8DBF5A')
frame.pack(expand=True)
Label(
frame,
bg='#8DBF5A',
font=('Times', 21),
text='Countries in North America '
).pack()
entry = MatchOnlyAutocompleteCombobox(
frame,
width=30,
font=('Times', 18),
completevalues=countries
)
entry.pack()
ws.mainloop()

Tkinter AutocompleteCombobox automatically sorts dates in a list

I generate a list of business days like so:
def bdate():
bdate = list((pd.bdate_range(start='1/1/2020', end='1/1/2025')))
for i in bdate:
index = bdate.index(i)
bdate[index] = bdate[index].strftime("%d/%m/%y")
return bdate
This creates the following list:
['01/01/20', '02/01/20', '03/01/20', '06/01/20', '07/01/20', '08/01/20', '09/01/20', '10/01/20', '13/01/20', '14/01/20', '15/01/20', '16/01/20', '17/01/20', '20/01/20', '21/01/20', '22/01/20', '23/01/20', '24/01/20', '27/01/20', '28/01/20', '29/01/20', '30/01/20', '31/01/20', '03/02/20', '04/02/20', '05/02/20', '06/02/20', '07/02/20', '10/02/20', '11/02/20', '12/02/20', '13/02/20', '14/02/20', '17/02/20', '18/02/20', '19/02/20', '20/02/20', '21/02/20', '24/02/20', '25/02/20', '26/02/20', '27/02/20', '28/02/20', '02/03/20', '03/03/20', '04/03/20', '05/03/20', '06/03/20', '09/03/20', '10/03/20', '11/03/20', '12/03/20', '13/03/20', '16/03/20', '17/03/20', '18/03/20', '19/03/20', '20/03/20', '23/03/20', '24/03/20', '25/03/20', '26/03/20', '27/03/20', '30/03/20', '31/03/20', '01/04/20', '02/04/20', '03/04/20', '06/04/20', '07/04/20', '08/04/20', '09/04/20', '10/04/20', '13/04/20', '14/04/20', '15/04/20', '16/04/20', '17/04/20', '20/04/20', '21/04/20', '22/04/20', '23/04/20', '24/04/20', '27/04/20', '28/04/20', '29/04/20', '30/04/20', '01/05/20', '04/05/20', '05/05/20', '06/05/20', '07/05/20', '08/05/20', '11/05/20', '12/05/20', '13/05/20', '14/05/20', '15/05/20', '18/05/20', '19/05/20', '20/05/20', '21/05/20', '22/05/20', '25/05/20', '26/05/20', '27/05/20', '28/05/20', '29/05/20', '01/06/20', '02/06/20', '03/06/20', '04/06/20', '05/06/20', '08/06/20', '09/06/20', '10/06/20', '11/06/20', '12/06/20', '15/06/20', '16/06/20', '17/06/20', '18/06/20', '19/06/20', '22/06/20', '23/06/20', '24/06/20', '25/06/20', '26/06/20', '29/06/20', '30/06/20', '01/07/20', '02/07/20', '03/07/20', '06/07/20', '07/07/20', '08/07/20', '09/07/20', '10/07/20', '13/07/20', '14/07/20', '15/07/20', '16/07/20', '17/07/20', '20/07/20', '21/07/20', '22/07/20', '23/07/20', '24/07/20', '27/07/20', '28/07/20', '29/07/20', '30/07/20', '31/07/20', '03/08/20', '04/08/20', '05/08/20', '06/08/20', '07/08/20', '10/08/20', '11/08/20', '12/08/20', '13/08/20', '14/08/20', '17/08/20', '18/08/20', '19/08/20', '20/08/20', '21/08/20', '24/08/20', '25/08/20', '26/08/20', '27/08/20', '28/08/20', '31/08/20', '01/09/20', '02/09/20', '03/09/20', '04/09/20', '07/09/20', '08/09/20', '09/09/20', '10/09/20', '11/09/20', '14/09/20', '15/09/20', '16/09/20', '17/09/20', '18/09/20', '21/09/20', '22/09/20', '23/09/20', '24/09/20', '25/09/20', '28/09/20', '29/09/20', '30/09/20', '01/10/20', '02/10/20', '05/10/20', '06/10/20', '07/10/20', '08/10/20', '09/10/20', '12/10/20', '13/10/20', '14/10/20', '15/10/20', '16/10/20', '19/10/20', '20/10/20', '21/10/20', '22/10/20', '23/10/20', '26/10/20', '27/10/20', '28/10/20', '29/10/20', '30/10/20', '02/11/20', '03/11/20', '04/11/20', '05/11/20', '06/11/20', '09/11/20', '10/11/20', '11/11/20', '12/11/20', '13/11/20', '16/11/20', '17/11/20', '18/11/20', '19/11/20', '20/11/20', '23/11/20', '24/11/20', '25/11/20', '26/11/20', '27/11/20', '30/11/20', '01/12/20', '02/12/20', '03/12/20', '04/12/20', '07/12/20', '08/12/20', '09/12/20', '10/12/20', '11/12/20', '14/12/20', '15/12/20', '16/12/20', '17/12/20', '18/12/20', '21/12/20', '22/12/20', '23/12/20', '24/12/20', '25/12/20', '28/12/20', '29/12/20', '30/12/20', '31/12/20', '01/01/21', '04/01/21', '05/01/21', '06/01/21', '07/01/21', '08/01/21', '11/01/21', '12/01/21', '13/01/21', '14/01/21', '15/01/21', '18/01/21', '19/01/21', '20/01/21', '21/01/21', '22/01/21', '25/01/21', '26/01/21', '27/01/21', '28/01/21', '29/01/21', '01/02/21', '02/02/21', '03/02/21', '04/02/21', '05/02/21', '08/02/21', '09/02/21', '10/02/21', '11/02/21', '12/02/21', '15/02/21', '16/02/21', '17/02/21', '18/02/21', '19/02/21', '22/02/21', '23/02/21', '24/02/21', '25/02/21', '26/02/21', '01/03/21', '02/03/21', '03/03/21', '04/03/21', '05/03/21', '08/03/21', '09/03/21', '10/03/21', '11/03/21', '12/03/21', '15/03/21', '16/03/21', '17/03/21', '18/03/21', '19/03/21', '22/03/21', '23/03/21', '24/03/21', '25/03/21', '26/03/21', '29/03/21', '30/03/21', '31/03/21', '01/04/21', '02/04/21', '05/04/21', '06/04/21', '07/04/21', '08/04/21', '09/04/21', '12/04/21', '13/04/21', '14/04/21', '15/04/21', '16/04/21', '19/04/21', '20/04/21', '21/04/21', '22/04/21', '23/04/21', '26/04/21', '27/04/21', '28/04/21', '29/04/21', '30/04/21', '03/05/21', '04/05/21', '05/05/21', '06/05/21', '07/05/21', '10/05/21', '11/05/21', '12/05/21', '13/05/21', '14/05/21', '17/05/21', '18/05/21', '19/05/21', '20/05/21', '21/05/21', '24/05/21', '25/05/21', '26/05/21', '27/05/21', '28/05/21', '31/05/21', '01/06/21', '02/06/21', '03/06/21', '04/06/21', '07/06/21', '08/06/21', '09/06/21', '10/06/21', '11/06/21', '14/06/21', '15/06/21', '16/06/21', '17/06/21', '18/06/21', '21/06/21', '22/06/21', '23/06/21', '24/06/21', '25/06/21', '28/06/21', '29/06/21', '30/06/21', '01/07/21', '02/07/21', '05/07/21', '06/07/21', '07/07/21', '08/07/21', '09/07/21', '12/07/21', '13/07/21', '14/07/21', '15/07/21', '16/07/21', '19/07/21', '20/07/21', '21/07/21', '22/07/21', '23/07/21', '26/07/21', '27/07/21', '28/07/21', '29/07/21', '30/07/21', '02/08/21', '03/08/21', '04/08/21', '05/08/21', '06/08/21', '09/08/21', '10/08/21', '11/08/21', '12/08/21', '13/08/21', '16/08/21', '17/08/21', '18/08/21', '19/08/21', '20/08/21', '23/08/21', '24/08/21', '25/08/21', '26/08/21', '27/08/21', '30/08/21', '31/08/21', '01/09/21', '02/09/21', '03/09/21', '06/09/21', '07/09/21', '08/09/21', '09/09/21', '10/09/21', '13/09/21', '14/09/21', '15/09/21', '16/09/21', '17/09/21', '20/09/21', '21/09/21', '22/09/21', '23/09/21', '24/09/21', '27/09/21', '28/09/21', '29/09/21', '30/09/21', '01/10/21', '04/10/21', '05/10/21', '06/10/21', '07/10/21', '08/10/21', '11/10/21', '12/10/21', '13/10/21', '14/10/21', '15/10/21', '18/10/21', '19/10/21', '20/10/21', '21/10/21', '22/10/21', '25/10/21', '26/10/21', '27/10/21', '28/10/21', '29/10/21', '01/11/21', '02/11/21', '03/11/21', '04/11/21', '05/11/21', '08/11/21', '09/11/21', '10/11/21', '11/11/21', '12/11/21', '15/11/21', '16/11/21', '17/11/21', '18/11/21', '19/11/21', '22/11/21', '23/11/21', '24/11/21', '25/11/21', '26/11/21', '29/11/21', '30/11/21', '01/12/21', '02/12/21', '03/12/21', '06/12/21', '07/12/21', '08/12/21', '09/12/21', '10/12/21', '13/12/21', '14/12/21', '15/12/21', '16/12/21', '17/12/21', '20/12/21', '21/12/21', '22/12/21', '23/12/21', '24/12/21', '27/12/21', '28/12/21', '29/12/21', '30/12/21', '31/12/21', '03/01/22', '04/01/22', '05/01/22', '06/01/22', '07/01/22', '10/01/22', '11/01/22', '12/01/22', '13/01/22', '14/01/22', '17/01/22', '18/01/22', '19/01/22', '20/01/22', '21/01/22', '24/01/22', '25/01/22', '26/01/22', '27/01/22', '28/01/22', '31/01/22', '01/02/22', '02/02/22', '03/02/22', '04/02/22', '07/02/22', '08/02/22', '09/02/22', '10/02/22', '11/02/22', '14/02/22', '15/02/22', '16/02/22', '17/02/22', '18/02/22', '21/02/22', '22/02/22', '23/02/22', '24/02/22', '25/02/22', '28/02/22', '01/03/22', '02/03/22', '03/03/22', '04/03/22', '07/03/22', '08/03/22', '09/03/22', '10/03/22', '11/03/22', '14/03/22', '15/03/22', '16/03/22', '17/03/22', '18/03/22', '21/03/22', '22/03/22', '23/03/22', '24/03/22', '25/03/22', '28/03/22', '29/03/22', '30/03/22', '31/03/22', '01/04/22', '04/04/22', '05/04/22', '06/04/22', '07/04/22', '08/04/22', '11/04/22', '12/04/22', '13/04/22', '14/04/22', '15/04/22', '18/04/22', '19/04/22', '20/04/22', '21/04/22', '22/04/22', '25/04/22', '26/04/22', '27/04/22', '28/04/22', '29/04/22', '02/05/22', '03/05/22', '04/05/22', '05/05/22', '06/05/22', '09/05/22', '10/05/22', '11/05/22', '12/05/22', '13/05/22', '16/05/22', '17/05/22', '18/05/22', '19/05/22', '20/05/22', '23/05/22', '24/05/22', '25/05/22', '26/05/22', '27/05/22', '30/05/22', '31/05/22', '01/06/22', '02/06/22', '03/06/22', '06/06/22', '07/06/22', '08/06/22', '09/06/22', '10/06/22', '13/06/22', '14/06/22', '15/06/22', '16/06/22', '17/06/22', '20/06/22', '21/06/22', '22/06/22', '23/06/22', '24/06/22', '27/06/22', '28/06/22', '29/06/22', '30/06/22', '01/07/22', '04/07/22', '05/07/22', '06/07/22', '07/07/22', '08/07/22', '11/07/22', '12/07/22', '13/07/22', '14/07/22', '15/07/22', '18/07/22', '19/07/22', '20/07/22', '21/07/22', '22/07/22', '25/07/22', '26/07/22', '27/07/22', '28/07/22', '29/07/22', '01/08/22', '02/08/22', '03/08/22', '04/08/22', '05/08/22', '08/08/22', '09/08/22', '10/08/22', '11/08/22', '12/08/22', '15/08/22', '16/08/22', '17/08/22', '18/08/22', '19/08/22', '22/08/22', '23/08/22', '24/08/22', '25/08/22', '26/08/22', '29/08/22', '30/08/22', '31/08/22', '01/09/22', '02/09/22', '05/09/22', '06/09/22', '07/09/22', '08/09/22', '09/09/22', '12/09/22', '13/09/22', '14/09/22', '15/09/22', '16/09/22', '19/09/22', '20/09/22', '21/09/22', '22/09/22', '23/09/22', '26/09/22', '27/09/22', '28/09/22', '29/09/22', '30/09/22', '03/10/22', '04/10/22', '05/10/22', '06/10/22', '07/10/22', '10/10/22', '11/10/22', '12/10/22', '13/10/22', '14/10/22', '17/10/22', '18/10/22', '19/10/22', '20/10/22', '21/10/22', '24/10/22', '25/10/22', '26/10/22', '27/10/22', '28/10/22', '31/10/22', '01/11/22', '02/11/22', '03/11/22', '04/11/22', '07/11/22', '08/11/22', '09/11/22', '10/11/22', '11/11/22', '14/11/22', '15/11/22', '16/11/22', '17/11/22', '18/11/22', '21/11/22', '22/11/22', '23/11/22', '24/11/22', '25/11/22', '28/11/22', '29/11/22', '30/11/22', '01/12/22', '02/12/22', '05/12/22', '06/12/22', '07/12/22', '08/12/22', '09/12/22', '12/12/22', '13/12/22', '14/12/22', '15/12/22', '16/12/22', '19/12/22', '20/12/22', '21/12/22', '22/12/22', '23/12/22', '26/12/22', '27/12/22', '28/12/22', '29/12/22', '30/12/22', '02/01/23', '03/01/23', '04/01/23', '05/01/23', '06/01/23', '09/01/23', '10/01/23', '11/01/23', '12/01/23', '13/01/23', '16/01/23', '17/01/23', '18/01/23', '19/01/23', '20/01/23', '23/01/23', '24/01/23', '25/01/23', '26/01/23', '27/01/23', '30/01/23', '31/01/23', '01/02/23', '02/02/23', '03/02/23', '06/02/23', '07/02/23', '08/02/23', '09/02/23', '10/02/23', '13/02/23', '14/02/23', '15/02/23', '16/02/23', '17/02/23', '20/02/23', '21/02/23', '22/02/23', '23/02/23', '24/02/23', '27/02/23', '28/02/23', '01/03/23', '02/03/23', '03/03/23', '06/03/23', '07/03/23', '08/03/23', '09/03/23', '10/03/23', '13/03/23', '14/03/23', '15/03/23', '16/03/23', '17/03/23', '20/03/23', '21/03/23', '22/03/23', '23/03/23', '24/03/23', '27/03/23', '28/03/23', '29/03/23', '30/03/23', '31/03/23', '03/04/23', '04/04/23', '05/04/23', '06/04/23', '07/04/23', '10/04/23', '11/04/23', '12/04/23', '13/04/23', '14/04/23', '17/04/23', '18/04/23', '19/04/23', '20/04/23', '21/04/23', '24/04/23', '25/04/23', '26/04/23', '27/04/23', '28/04/23', '01/05/23', '02/05/23', '03/05/23', '04/05/23', '05/05/23', '08/05/23', '09/05/23', '10/05/23', '11/05/23', '12/05/23', '15/05/23', '16/05/23', '17/05/23', '18/05/23', '19/05/23', '22/05/23', '23/05/23', '24/05/23', '25/05/23', '26/05/23', '29/05/23', '30/05/23', '31/05/23', '01/06/23', '02/06/23', '05/06/23', '06/06/23', '07/06/23', '08/06/23', '09/06/23', '12/06/23', '13/06/23', '14/06/23', '15/06/23', '16/06/23', '19/06/23', '20/06/23', '21/06/23', '22/06/23', '23/06/23', '26/06/23', '27/06/23', '28/06/23', '29/06/23', '30/06/23', '03/07/23', '04/07/23', '05/07/23', '06/07/23', '07/07/23', '10/07/23', '11/07/23', '12/07/23', '13/07/23', '14/07/23', '17/07/23', '18/07/23', '19/07/23', '20/07/23', '21/07/23', '24/07/23', '25/07/23', '26/07/23', '27/07/23', '28/07/23', '31/07/23', '01/08/23', '02/08/23', '03/08/23', '04/08/23', '07/08/23', '08/08/23', '09/08/23', '10/08/23', '11/08/23', '14/08/23', '15/08/23', '16/08/23', '17/08/23', '18/08/23', '21/08/23', '22/08/23', '23/08/23', '24/08/23', '25/08/23', '28/08/23', '29/08/23', '30/08/23', '31/08/23', '01/09/23', '04/09/23', '05/09/23', '06/09/23', '07/09/23', '08/09/23', '11/09/23', '12/09/23', '13/09/23', '14/09/23', '15/09/23', '18/09/23', '19/09/23', '20/09/23', '21/09/23', '22/09/23', '25/09/23', '26/09/23', '27/09/23', '28/09/23', '29/09/23', '02/10/23', '03/10/23', '04/10/23', '05/10/23', '06/10/23', '09/10/23', '10/10/23', '11/10/23', '12/10/23', '13/10/23', '16/10/23', '17/10/23', '18/10/23', '19/10/23', '20/10/23', '23/10/23', '24/10/23', '25/10/23', '26/10/23', '27/10/23', '30/10/23', '31/10/23', '01/11/23', '02/11/23', '03/11/23', '06/11/23', '07/11/23', '08/11/23', '09/11/23', '10/11/23', '13/11/23', '14/11/23', '15/11/23', '16/11/23', '17/11/23', '20/11/23', '21/11/23', '22/11/23', '23/11/23', '24/11/23', '27/11/23', '28/11/23', '29/11/23', '30/11/23', '01/12/23', '04/12/23', '05/12/23', '06/12/23', '07/12/23', '08/12/23', '11/12/23', '12/12/23', '13/12/23', '14/12/23', '15/12/23', '18/12/23', '19/12/23', '20/12/23', '21/12/23', '22/12/23', '25/12/23', '26/12/23', '27/12/23', '28/12/23', '29/12/23', '01/01/24', '02/01/24', '03/01/24', '04/01/24', '05/01/24', '08/01/24', '09/01/24', '10/01/24', '11/01/24', '12/01/24', '15/01/24', '16/01/24', '17/01/24', '18/01/24', '19/01/24', '22/01/24', '23/01/24', '24/01/24', '25/01/24', '26/01/24', '29/01/24', '30/01/24', '31/01/24', '01/02/24', '02/02/24', '05/02/24', '06/02/24', '07/02/24', '08/02/24', '09/02/24', '12/02/24', '13/02/24', '14/02/24', '15/02/24', '16/02/24', '19/02/24', '20/02/24', '21/02/24', '22/02/24', '23/02/24', '26/02/24', '27/02/24', '28/02/24', '29/02/24', '01/03/24', '04/03/24', '05/03/24', '06/03/24', '07/03/24', '08/03/24', '11/03/24', '12/03/24', '13/03/24', '14/03/24', '15/03/24', '18/03/24', '19/03/24', '20/03/24', '21/03/24', '22/03/24', '25/03/24', '26/03/24', '27/03/24', '28/03/24', '29/03/24', '01/04/24', '02/04/24', '03/04/24', '04/04/24', '05/04/24', '08/04/24', '09/04/24', '10/04/24', '11/04/24', '12/04/24', '15/04/24', '16/04/24', '17/04/24', '18/04/24', '19/04/24', '22/04/24', '23/04/24', '24/04/24', '25/04/24', '26/04/24', '29/04/24', '30/04/24', '01/05/24', '02/05/24', '03/05/24', '06/05/24', '07/05/24', '08/05/24', '09/05/24', '10/05/24', '13/05/24', '14/05/24', '15/05/24', '16/05/24', '17/05/24', '20/05/24', '21/05/24', '22/05/24', '23/05/24', '24/05/24', '27/05/24', '28/05/24', '29/05/24', '30/05/24', '31/05/24', '03/06/24', '04/06/24', '05/06/24', '06/06/24', '07/06/24', '10/06/24', '11/06/24', '12/06/24', '13/06/24', '14/06/24', '17/06/24', '18/06/24', '19/06/24', '20/06/24', '21/06/24', '24/06/24', '25/06/24', '26/06/24', '27/06/24', '28/06/24', '01/07/24', '02/07/24', '03/07/24', '04/07/24', '05/07/24', '08/07/24', '09/07/24', '10/07/24', '11/07/24', '12/07/24', '15/07/24', '16/07/24', '17/07/24', '18/07/24', '19/07/24', '22/07/24', '23/07/24', '24/07/24', '25/07/24', '26/07/24', '29/07/24', '30/07/24', '31/07/24', '01/08/24', '02/08/24', '05/08/24', '06/08/24', '07/08/24', '08/08/24', '09/08/24', '12/08/24', '13/08/24', '14/08/24', '15/08/24', '16/08/24', '19/08/24', '20/08/24', '21/08/24', '22/08/24', '23/08/24', '26/08/24', '27/08/24', '28/08/24', '29/08/24', '30/08/24', '02/09/24', '03/09/24', '04/09/24', '05/09/24', '06/09/24', '09/09/24', '10/09/24', '11/09/24', '12/09/24', '13/09/24', '16/09/24', '17/09/24', '18/09/24', '19/09/24', '20/09/24', '23/09/24', '24/09/24', '25/09/24', '26/09/24', '27/09/24', '30/09/24', '01/10/24', '02/10/24', '03/10/24', '04/10/24', '07/10/24', '08/10/24', '09/10/24', '10/10/24', '11/10/24', '14/10/24', '15/10/24', '16/10/24', '17/10/24', '18/10/24', '21/10/24', '22/10/24', '23/10/24', '24/10/24', '25/10/24', '28/10/24', '29/10/24', '30/10/24', '31/10/24', '01/11/24', '04/11/24', '05/11/24', '06/11/24', '07/11/24', '08/11/24', '11/11/24', '12/11/24', '13/11/24', '14/11/24', '15/11/24', '18/11/24', '19/11/24', '20/11/24', '21/11/24', '22/11/24', '25/11/24', '26/11/24', '27/11/24', '28/11/24', '29/11/24', '02/12/24', '03/12/24', '04/12/24', '05/12/24', '06/12/24', '09/12/24', '10/12/24', '11/12/24', '12/12/24', '13/12/24', '16/12/24', '17/12/24', '18/12/24', '19/12/24', '20/12/24', '23/12/24', '24/12/24', '25/12/24', '26/12/24', '27/12/24', '30/12/24', '31/12/24', '01/01/25']
However when I pass this onto my combolist like so:
deliverydate_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
deliverydate_box.place(x=100,y=230,width=200,height=25)
I am given the following result:
What I want is the dates in the combolist displayed in the same order as the original list, eg, like a normal calendar.
What solutions exist?
I have included a full example of my code, in order for the scenario to be replicated.
from ttkwidgets.autocomplete import AutocompleteCombobox
from tkinter import messagebox
import tkinter as tk
import pandas as pd
def ask_confirm():
confirm = messagebox.askquestion('Warning', 'Are you sure you want to send this ticket?')
if confirm == "yes":
global data_container
data_container = [buyer_box.get(), seller_box.get(), metal_box.get(), tonnage_box.get(),
deliverydate_box.get(), price_box.get(), premium_box.get(), pricingdate_box.get(),
location_box.get(), deliveryterms_box.get()]
print(data_container)
def bdate():
bdate = list((pd.bdate_range(start='1/1/2020', end='1/1/2025')))
for i in bdate:
index = bdate.index(i)
bdate[index] = bdate[index].strftime("%d/%m/%y")
return bdate
bdate_list = bdate()
root = tk.Tk()
root.title("Physical Deal Porter")
width=400
height=500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
HELLO = tk.Label(root, text = " HELLO ", background = '#3b5997', foreground ="white", font = ("Times New Roman", 25))
HELLO.place(x=100,y=20,width=200,height=50)
buyer = tk.Label(root, text="Buyer :")
buyer.place(x=10,y=90,width=70,height=25)
buyer_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
buyer_box.place(x=100,y=90,width=200,height=25)
seller = tk.Label(root, text="Seller :")
seller.place(x=10,y=125,width=70,height=25)
seller_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
seller_box.place(x=100,y=125,width=200,height=25)
metal = tk.Label(root, text="Commodity :")
metal.place(x=10,y=160,width=70,height=25)
metal_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
metal_box.place(x=100,y=160,width=200,height=25)
tonnage = tk.Label(root, text="Tonnage :")
tonnage.place(x=10,y=195,width=70,height=25)
tonnage_note = tk.Label(root, text="(MT)")
tonnage_note.place(x=290,y=195,width=70,height=25)
tonnage_box = tk.Entry(root, width=20)
tonnage_box.place(x=100,y=195,width=200,height=25)
deliverydate = tk.Label(root, text="Delivery :")
deliverydate.place(x=10,y=230,width=70,height=25)
deliverydate_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
deliverydate_box.place(x=100,y=230,width=200,height=25)
price = tk.Label(root, text="Price :")
price.place(x=10,y=265,width=70,height=25)
price_note = tk.Label(root, text="(USD)")
price_note.place(x=290,y=265,width=70,height=25)
price_box = tk.Entry(root, width=20)
price_box.place(x=100,y=265,width=200,height=25)
premium = tk.Label(root, text="Premium :")
premium.place(x=10,y=300,width=70,height=25)
premium_note = tk.Label(root, text="(USD)")
premium_note.place(x=290,y=300,width=70,height=25)
premium_box = tk.Entry(root, width=20)
premium_box.place(x=100,y=300,width=200,height=25)
pricingdate = tk.Label(root, text="Pricing :")
pricingdate.place(x=10,y=335,width=70,height=25)
pricingdate_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
pricingdate_box.place(x=100,y=335,width=200,height=25)
location = tk.Label(root, text="Location :")
location.place(x=10,y=370,width=70,height=25)
location_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
location_box.place(x=100,y=370,width=200,height=25)
deliveryterms = tk.Label(root, text="Terms :")
deliveryterms.place(x=10,y=405,width=70,height=25)
deliveryterms_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
deliveryterms_box.place(x=100,y=405,width=200,height=25)
send = tk.Button(root, text = " Send ", background = '#3b5997', foreground ="white", font = ("Times New Roman", 16), command = ask_confirm)
send.place(x=150,y=450,width=100,height=30)
root.mainloop()
tl;dr: The sort appears to be an undocumented "feature" of the AutocompleteCombobox. It does not happen if you use the regular Combobox.
At the bottom is the minimal reproducible example. Here is an explanation that shows the difference between the behaviour of the two Comboboxes:
# AutocompleteCombobox is in ttkwidgets
from ttkwidgets.autocomplete import AutocompleteCombobox
# Regular Combobox is in ttk
from tkinter import ttk
Use a list comprehension to generate the dates from the range. Learn list, dict and set comprehensions, they are amazing:
bdate_list = [ xdate.strftime("%d/%m/%y") for xdate in \
pd.bdate_range(start='1/1/2020', end='1/1/2025') ]
# Note the only difference between the two is that the regular
# Combobox uses values
deliverydate_box = ttk.Combobox(root, width=20, values=bdate_list)
# AutocompleteCombobox uses completevalues
pricingdate_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
Interestingly, according to an error message I got while testing, completevalues maps onto values. I would guess this has a different name because it applies the sort before passing the values off to the combobox, unlike the regular which accepts the raw values as expected.
Looking at the code from the author's mailing list post, the relevant line is:
def set_completion_list(self, completion_list):
"""Use our completion list as our drop down selection menu, arrows move through menu."""
self._completion_list = sorted(completion_list, key=str.lower) # Work with a sorted list
This means the behaviour is explicit. To overcome it, if you really want to use AutoComplete over a regular Combobox, you would have to use the International Date Format:
bdate_list = [ xdate.strftime("%Y-%m-%d") for xdate in \
pd.bdate_range(start='1/1/2020', end='1/1/2025') ]
Full working code here:
import tkinter as tk
import pandas as pd
from tkinter import messagebox
from ttkwidgets.autocomplete import AutocompleteCombobox
from tkinter import ttk
bdate_list = [ xdate.strftime("%d/%m/%y") for xdate in \
pd.bdate_range(start='1/1/2020', end='1/1/2025') ]
root = tk.Tk()
root.title("Physical Deal Porter")
width=400
height=500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
deliverydate = tk.Label(root, text="Delivery :")
deliverydate.place(x=10,y=230,width=70,height=25)
deliverydate_box = ttk.Combobox(root, width=20, values=bdate_list)
deliverydate_box.place(x=100,y=230,width=200,height=25)
pricingdate = tk.Label(root, text="Pricing :")
pricingdate.place(x=10,y=335,width=70,height=25)
pricingdate_box = AutocompleteCombobox(root, width=20, completevalues=bdate_list)
pricingdate_box.place(x=100,y=335,width=200,height=25)
root.mainloop()
Otherwise, pretty good. Well done!

Printing the results of a function into a tkinter message box?

I've been coding for years and I have always been able to find an answer on google, until now. I cannot manage to make this work in any way.
Before this I have several lists of different countries, and a dozen or so functions that just print stuff for the user, it is not relevant here.
I use tkinter to create an input box where a user can type a country (input gets assigned to typedCountry). I then search for the country in each and every list in the mainProgram() function, and every time I find a list that matches I return another function. Everything works marvelously as it should, except I want mainProgram() to return the information to a tkinter GUI box and not the terminal. I've been fighting with it for hours and I cannot find a way to make it work, I am willing to take any advice, even changing the code significantly or using something other than tkinter would work just fine.
def mainProgram():
typedCountry = e.get()
Country = typedCountry.lower()
print 'Your country is: ' + typedCountry + '\n'
if Country in bannedCountries:
banned(typedCountry)
if Country in cpBannedCountries:
cpBanned(typedCountry)
if Country in skrillBannedCountries:
skrillBanned(typedCountry)
if Country in bacsCountries:
Bacs(typedCountry)
if Country in sepaCountries:
sepa(typedCountry)
if Country in eftCountries:
eft(typedCountry)
if Country in ltdCountries:
ltd(typedCountry)
if Country in marketsCountries:
markets(typedCountry)
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
var = mainProgram()
def textBox():
root = Tk()
label = Message(root, textvariable=var)
label.pack()
root.mainloop()
b = Button(master, text = "Search", command = mainProgram)
b.pack()
mainloop()
And here is the main code if you want it (if you want to run this in your end for example):
from tkinter import *
import tkMessageBox
bannedCountries = ['afghanistan','american samoa','belarus','brazil','burundi',
'central african republic','congo','cook islands','cote d\'ivoire',
'crimea','cuba','guam','iran','japan','liberia','libya','myanmar',
'new zealand','north korea','northern mariana islands','puerto rico',
'russia','singapore','somalia','south korea','sudan','syria','tokelau',
'turkey','ukraine','united states','vanuatu','virgin islands',
'western sahara','zimbabwe']
cpBannedCountries = ['belarus','bosnia and herzegovina','burundi','cote d\'ivoire',
'cuba','iran','iraq','kosovo','lebanon','liberia','macedonia','montenegro','myanmar',
'nigeria','north korea','saint helena','somalia','sudan']
skrillBannedCountries = ['angola','barbados','benin','burkina faso','cape verde',
'comoros','djibouti','faroe islands','gambia','greenland','grenada','guyana','laos',
'liechtenstein','macao','martinique','mongolia','namibia','niger','palau','samoa',
'suriname','tajikistan','togo','trinidad and tobago','turkmenistan']
bacsCountries = ["united kingdom"]
eftCountries = ['australia']
sepaCountries = ['austria','belgium','bulgaria','cyprus','czech republic','check',
'denmark','estonia','finland','france','germany','greece','hungary','iceland',
'ireland','italy','latvia','liechtenstein','lithuania','luxembourg','malta',
'martinique','mayotte','monaco','netherlands','norway','poland','portugal',
'romania','slovakia','slovenia','spain','sweden','switzerland','united kingdom']
ltdCountries = ['austria','belgium','bulgaria','croatia','cyprus','czech republic',
'denmark','estonia','finland','france','germany','greece','hungary','ireland',
'italy','latvia','lithuania','luxembourg','malta','netherlands','poland','portugal',
'romania','slovakia','slovenia','spain','united kingdom']
marketsCountries = ['albania','algeria','andorra','angola','anguilla','armenia',
'aruba','bahamas','bangladesh','barbados','belize','benin','bermuda','bhutan',
'bonaire','bosnia','herzegovina','bosnia and herzegovina','botswana','brunei',
'burkina faso','burma','cambodia','cameroon','cape verde','cayman islands',
'chad','comoros','djibouti','equatorial guinea','eritrea','ethiopia','falkland islands (malvinas)',
'faroe islands','gabon','gambia','ghana','greenland','grenada','guinea','guinea-bissau',
'guyana','haiti','iceland','india','jamaica','jordan','kazakhstan','kenya',
'kiribati','kosovo','kyrgyzstan','laos','lesotho','liechtenstein','macao',
'macedonia','madagascar','malawi','malaysia','maldives','mali','marshall islands',
'mauritania','mauritius','micronesia','mongolia','morocco','mozambique','namibia',
'nauru','nepal','niger','nigeria','norway','pakistan','palau','papua new guinea',
'philippines','rwanda','saint helena','saint kitts and nevis','saint lucia','saint vincent and the grenadines',
'samoa','sao tome and principe','senegal','serbia','seychelles','sierra leone',
'solomon islands','sri lanka','suriname','swaziland','tajikistan','tanzania','togo',
'tonga','trinidad and tobago','tunisia','turkmenistan','turks and caicos islands','tuvalu',
'uganda','uzbekistan','yemen','zambia']
def banned(x):
if 'kingdom' not in x:
return 'Clients from %s are not able to open an account with FXCM' % x
else:
return
def cpBanned(x):
return "FXCM does not accept cards issued in %s" % x
def skrillBanned(x):
return "Clients from %s cannot use Skrill" % x
def Bacs(x):
return """Clients from %s can use BACS if their bank account is located in
%s and both their bank account and their FXCM account is in GBP""" % (x, x)
def sepa(x):
return """Clients from %s can use SEPA if their bank account is located either in
%s or in another European country, and both their bank account and their FXCM account is in EUR""" % (x, x)
def eft(x):
return """Clients from %s can use EFT if their bank account is located in
%s, and both their bank account and their FXCM account is in AUD""" % (x, x)
print "Clients from %s must open with FXCM AU" % x
def ltd(x):
return "Clients from %s must open with FXCM LTD" % x
def markets(x):
return "Clients from %s must open with FXCM Markets" % x
def mainProgram():
typedCountry = e.get() # This is the text you may want to use later
Country = typedCountry.lower()
print 'Your country is: ' + typedCountry + '\n'
if Country in bannedCountries:
banned(typedCountry)
if Country in cpBannedCountries:
cpBanned(typedCountry)
if Country in skrillBannedCountries:
skrillBanned(typedCountry)
if Country in bacsCountries:
Bacs(typedCountry)
if Country in sepaCountries:
sepa(typedCountry)
if Country in eftCountries:
eft(typedCountry)
if Country in ltdCountries:
ltd(typedCountry)
if Country in marketsCountries:
markets(typedCountry)
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
var = mainProgram()
def textBox():
root = Tk()
label = Message(root, textvariable=var)
label.pack()
root.mainloop()
b = Button(master, text = "Search", command = mainProgram)
b.pack()
mainloop()
Just replace for example:
return "FXCM does not accept cards issued in %s" % x
with:
Label(master, text="FXCM does not accept cards issued in %s" % x).pack()
in each of your functions.
Or better add:
lbl = Label(master)
lbl.pack()
under your e lines and then replace the returns with:
lbl['text'] = x
You don't call the textBox function. For this to work, if I understand the problem correctly, the called function has to update the text box label. Also, you don't send the lower() county to the function. A shortened version of your code
import sys
if sys.version_info[0] < 3:
import Tkinter as tk ## Python 2.x
else:
import tkinter as tk ## Python 3.x
ltdCountries = ['austria','belgium','bulgaria','croatia','cyprus','czech republic']
sepaCountries = ['austria','belgium','bulgaria','cyprus','czech republic','check']
marketsCountries = ['albania','algeria','andorra','angola','anguilla']
def ltd(country):
var.set(var.get() +" *** ltd " + country)
def sepa(country):
var.set(var.get() +" *** sepa " + country)
def markets(country):
var.set(var.get() +" *** markets " + country)
def mainProgram():
typedCountry = e.get()
print('Your country is: ' + typedCountry + '\n')
country_lower=typedCountry.lower()
for country_list, country_function in ((ltdCountries, ltd),
(sepaCountries, sepa),
(marketsCountries, markets)):
if country_lower in country_list:
country_function(country_lower)
master = tk.Tk()
e = tk.Entry(master)
e.pack()
e.focus_set()
var=tk.StringVar()
var.set("")
tk.Label(master, textvariable=var, bg="lightyellow",
width=25).pack()
b = tk.Button(master, text = "Search", command = mainProgram)
b.pack()
tk.Button(master, text="Quit", bg="orange",
command=master.quit).pack()
master.mainloop()
# First create a text box
txt = scrolledtext.ScrolledText(root)
# this line is for deleting it's content
txt.delete(1.0, END)
# this other line is for inserting text in it
txt.insert(1.0, 'Some Text')

How to display a value in the window using tkinter?

What can I do to get the result in the interface instead of the terminal in the given code? I want the random.choice result to appear in the table.
import random
import tkinter, sys
from tkinter import *
lista = ['Kamil Winnicki', 'Wiktor Jasiński', 'Adam Turowski', 'Arek Major',
'Dominik Piechotka', 'Jakub Laskowski', 'Jakub Materak', 'Kacper Kołodziejski',
'Kamil Stankiewicz', 'Konrad Nosek', 'Krzysiek Wawszczak', 'Andrzej Oplebsiak',
'Miłosz Tarucin', 'Paweł Pawłowski', 'Mateusz Lebioda']
def koniec():
sys.exit()
def losowanie():
print(random.choice(lista))
main = tkinter.Tk()
#nagłowek
te = tkinter.Label(main, text = 'Lista 1T:')
te.pack()
#Wyswietla liste 1T
listbox = Listbox(main)
listbox.insert(1, '1. Mateusz Lebioda', '2. Jakub Laskowski', '3. Kamil Winnicki',
'4. Wiktor Jasiński', '5. Adam Turowski', '6. Arek Major',
'7. Dominik Piechotka', '8. Jakub Materak', '9. Kacper Kołodziejski',
'10. Kamil Stankiewicz', '11. Konrad Nosek', '12. Krzysiek Wawszczak',
'13. Andrzej Oplebsiak', '14. Miłosz Tarucin', '15. Paweł Pawłowski')
listbox.pack()
#losuje
y = tkinter.Button(main, text = 'losuj', command = losowanie)
y.pack()
#wyjscie z aplikacji
x = tkinter.Button(main, text = 'Zakoncz', command = koniec)
x.pack()
main.mainloop()
One way to do it would be to show a dialog with the choice.
import tkinter.messagebox as messagebox
def losowanie():
messagebox.showinfo(message=random.choice(lista))
If I understand the question correctly you need to append the result of random.choice(lista) to the listbox element, this can be achieved by the following code:
def losowanie():
listbox.insert(END, str(listbox.size() + 1) + ". " + random.choice(lista))
Like Dan-Dev suggested you could do that but you can also get rid of the function
This will do what you intend to, but without the function losowaine:
y = tkinter.Button(main, text = 'losuj', command = lambda :
listbox.insert(END, str(listbox.size() + 1) + ". " + random.choice(lista)))
This below code will just insert the random choice at the end of the table (with function losowanie)
def losowanie():
listbox.insert(END, (random.choice(lista)))

IndexError: list index out of range with tkinter and procedures

I'm recently adjusting to using tkinter alongside Python and as part of an assignment I've been asked to produce a tkinter-based program.
I decided I'd attempt a quiz which has three difficulties and is able to choose a question out of random from the list available for that difficulty.
When I run the program and select the difficulty (easy is all I've done up to now) it continues running but I get an error within the IDE:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "E:\Unit 6 - Software Development\randomtkintergame.py", line 98, in easy_mode
question, answer, wrong_1, wrong_2, wrong_3 = easy[question_choice]
IndexError: list index out of range
This is the code I have:
import Tkinter as tk
from tkSimpleDialog import *
import math
import string
import time
from random import randint
global question_title, button_1, button_2, button_3, button_4, question_number, score_count, easy, question_choice, question, answer, wrong_1, wrong_2, wrong_3
question_number = 1
score_count = 0
question_choice = 0
question = 0
answer = 0
wrong_1 = 0
wrong_2 = 0
wrong_3 = 0
easy = [("What is the longest river in the world?", "The River Nile", "The Amazon River", "The River Humber", "The River Trent"),
("What is Doctor Who`s time box called?", "TARDIS", "TIMEY-WIMEY", "TASDIR", "WIMEY-TIMEY"),
("How many faces are on a die?", "6", "5", "7", "4"),
("How many wives did Henry VIII have?", "6", "8", "4", "9"),
("What is the square root of 169?", "13", "11", "17", "19"),
("In a game of chess, what is the only piece able to jump over other pieces?", "Knight", "Pawn", "Bishop", "All"),
("Who is the author of the `Harry Potter` books?", "J.K. Rowling", "J.R.R. Tolkien", "George R.R. Martin", "Julius Caesar"),
("What is the name of the clockwork device used by musicians to measure time?", "Metronome", "Tuner", "Amplifier", "Time Measurer"),
("Which two colours are Dennis the Menace`s jumper?", "Red and black", "Blue and black", "White and gold", "Red and blue"),
("An octagon has how many sides?", "8", "6", "10", "7"),
("Which sign of the zodiac is represented by the Ram?", "Aries", "Scorpio", "Ophiuchus", "Aquarius"),
("Which animal is associated with the beginning of an MGM film?", "A lion", "An alpaca", "A very small albatross", "A tiger"),
("What was the hunchback of Notre Dame`s name?", "Quasimodo", "Esmerelda", "Frollo", "Not Re Dame"),
("Who is the animated star of the computer game Tomb Raider?", "Lara Croft", "Sara Craft", "Tom Cruise", "Bill Gates"),
("What is the name of the city in which The Simpsons live?", "Springfield", "Quahog", "South Park", "Boston"),
("In which film would you first have come across the character of Marty McFly?", "Back to the Future", "Lord of the Rings", "The IT Crowd", "Harry Potter"),
("How many years are there in a millennium?", "1,000", "10,000", "100", "1,000,000"),
("In Greek mythology, what was Medusa`s hair made of?", "Snakes", "Threads of silk", "Stone", "Leeches"),
("What is the first letter of the Greek alphabet?", "A - Alpha", "B - Beta", "G - Gamma", "E - Epsilon"),
("What type of animal was Stuart, in the 1999 film `Stuart Little`?", "Mouse", "Frog", "Guinea pig", "Porcupine"),
("What creature appears on the flag of Wales?", "Dragon", "Alligator", "Crocodile", "Lizard"),
("On what part of the body would you wear a `sombrero`?", "Head", "Feet", "Hands", "Chest"),
("How many wheels are on a tricycle?", "3", "2", "6", "8"),
("Oxygen and which other element makes up water?", "Hydrogen", "Helium", "Ytterbium", "Einsteinium"),
("How many inches are in a yard?", "36", "12", "8", "24"),
("What colour is an emerald?", "Green", "Black", "Orange", "White")]
def easy_mode():
global button_1, button_2, button_3, button_4, question_number, question_title, score_count, easy, question_choice, question, answer, wrong_1, wrong_2, wrong_3
repeat = True
while repeat == True:
for i in range (0, len(easy)): #the code works through all the questions
question_choice = randint(0, 25)#generate random int
question, answer, wrong_1, wrong_2, wrong_3 = easy[question_choice]
easy.pop(question_choice)
root = tk.Tk()
root.geometry("700x500")
root.title("Educational Quiz")
root.configure(background="#f2e5ff")
question_title = tk.Label(root, text="Please select a difficulty.", relief=GROOVE, bd=5, bg="#66b2ff", fg="black", font=("Calibri Light", 20))
question_title.place(x = 50, y = 25, width=625, height=80)
button_1 = tk.Button(root, text = "EASY", relief=GROOVE, bd=5, command = easy_mode, bg="#0055ff", fg="black", font=("Calibri Light", 20))
button_1.place (x = 50, y = 180 , width=300, height=80)
Of course, it's not the entire code as I didn't want to paste things that aren't actually related to the problem, but I can provide the rest if needed.
(Also, I might not need all the global variables set, but I'll deal with that when it's needed.)
The problem is that you continually select for the original range while shrinking the list, until you eventually get an index too large. You could replace the while loop with
while easy:
question_choice = randint(0, len(easy)-1) #generate random int
question, answer, wrong_1, wrong_2, wrong_3 = easy[question_choice]
easy.pop(question_choice)
but even better, I think, to present all questions in random order,
random.shuffle(easy)
for q_and_a in easy:
question, answer, wrong_1, wrong_2, wrong_3 = q_and_a
Neither replacement is tested, so there may be a typo.

Categories