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

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')

Related

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

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()

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!

Problem with writing to file second time, Python3

I have created a phonebook with tkinker using Python 3.6
When I add persons to phonebook it save it to a file.
When I load the program again it loads the file as it should.
If I add 2 person at first run, all works fine.
Second run, I add one person and it adds an empty line at index 1 and adds the person below as it should.
Third run, I add one person, it adds a new line at index 1 and a person last in the list.
Now I get 2 empty lines.
I can't figure out why it creates an empty space at index 1 . It should not do it.
Here is the code, comments are in Swedish so sorry about it.
How I write to the file is in function lägg_till()
It will auto create kontakter.txt when you run it first time.
"Lägg till" means add in Sweden and "Avsluta" is quit the program.
from tkinter import *
import os.path
root = Tk()
root.geometry("640x640+200+100")
root.title("Telefon listan")
def avsluta():
quit()
def spara():
#Spara kontakter till fil.
name = entry_1.get()
mobil = entry_2.get()
if name == "" or mobil == "" :
pass
else:
with open("kontakter.txt","w") as file:
file.write("\n".join(kontakter.get(0,END)))
def ta_bort():
# Ta bort kontakter,genom att välja index av element och sparar värdet i variabel index.
index = kontakter.curselection()
print(index)
kontakter.delete(index)
def lägg_till():
# Ta inmatade värden från name,mobil och spara i kontakter.
# Använder .get() för att hämta
name = entry_1.get()
mobil = entry_2.get().replace(" ", "") # Använder replace för att rensa whitespace
# Varning när alla värden inte är ifyllda
if name == "" or mobil == "" :
label_error.config(text="Alla fälten är inte ifyllda")
else:
# trycka in dessa i kontakter med .insert() END för slutet av listan, dvs index "kan vara 0,1,2,3"
#Rensar error fältet innan man lägger till kontakten
label_error.config(text="")
kontakter.insert(END,name + " - " + mobil)
# Rensa fältet efter lägg till
entry_1.delete(0,END)
entry_2.delete(0,END)
kontakt = kontakter.get(0,END)
with open("kontakter.txt","w") as file:
file.write("\n".join(kontakt))
def uppdatera():
# Hämta det markerade data
index = kontakter.curselection()
name = entry_1.get()
mobil = entry_2.get()
# Varning när alla värden inte är ifyllda
if name == "" or mobil == "" :
label_error.config(text="Alla fälten är inte ifyllda")
else:
# trycka in dessa i kontakter med .insert() END för slutet av listan, dvs index "kan vara 0,1,2,3"
#Rensar error fältet innan man lägger till kontakten
label_error.config(text="")
# Raderar det ifyllda data
kontakter.delete(index)
#Skriver nytt
kontakter.insert(index,name + "-" + mobil)
entry_1.delete(0,END)
entry_2.delete(0,END)
# Skapar frame
#Namn
fram_1 = Frame(root)
fram_1.pack()
#Mobil
fram_2 = Frame(root)
fram_2.pack()
#Knappar
fram_3 = Frame(root)
fram_3.pack()
# Listbox
fram_4 = Frame(root)
fram_4.pack()
#Skapar label
#Namn
label_1 = Label(fram_1,text="Name:")
label_1.grid(row=0, column=0)
#Mobil
label_2 = Label(fram_2,text="Mobil:")
label_2.grid(row=1,column=0)
# Skapar entry
#namn
entry_1 = Entry(fram_1)
entry_1.grid(row=0,column=1)
#Mobil
entry_2 = Entry(fram_2)
entry_2.grid(row=1,column=2,)
# Kolla om filen finns, annars skapa den, behöver importera os.path
if not os.path.exists("kontakter.txt"):
open('kontakter.txt', 'w').close()
else:
pass
# Läsa från fil
data = []
with open("kontakter.txt" ,"r") as fil:
for line in fil:
data += [line]
# Listbox
kontakter = Listbox(fram_4,height=8,width=40,bg="pink")
kontakter.grid(row=0,column=0)
# Lägger till kontakter , första värdet är index följt av värde,
kontakter.insert(END,)
#Läsa in från fil
for i in range(len(data)):
kontakter.insert(i+0 , data[i])
# Error
label_error = Label(root,text="",fg="red")
label_error.pack()
# Knappar
# knapp Lägg till
button_1 = Button(fram_3,text="Lägg till",command=lägg_till)
button_1.grid(row=0,column=0)
# knapp edit
button_2 = Button(fram_3,text="Uppdatera",command=uppdatera)
button_2.grid(row=0,column=1)
# Knapp delete
button_3 = Button(fram_3,text="Radera",command=ta_bort)
button_3.grid(row=0,column=2)
# Knapp avsluta
button_4 = Button(fram_3,text="Avsluta",command=avsluta)
button_4.grid(row=0,column=3)
button_5 = Button(fram_3,text="Spara",command=spara)
button_5.grid(row=0,column=4)
root.attributes("-topmost", True)
root.mainloop()
Inside lägg_till() when you open the file use ab instead of w:
with open("kontakter.txt","ab") as file:
file.write("\n".join(kontakt))
By adding .strip() , I made workaround, but I think problem is still there.
# Läsa från fil
data = []
with open("kontakter.txt" ,"r") as fil:
for line in fil.readlines():
data += [line.strip()] #.strip() fix the problem
fil.close()
The problem in your program is kontakt = kontakter.get(0,END), which returns your data as follows :
('1 - 1\n', '2 - 2', '3 - 3')
Note that the third entry (3 - 3) is made after the GUI was closed once. By joining together with '\n'.join(), you get an additional space character:
'1 - 1\n\n2 - 2\n3 - 3\n'
I don't know the exact reason why this only happens if you close the program once.
You can avoid this conflict by using 'a' instead of 'w', which simply appends the string in the text file.
with open("kontakter.txt","a") as file:
file.write(name + " - " + mobil + '\n')

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)))

how to allow Tkinter to generate a listbox from list input

I am trying to insert the output of a SparQL query (via rdflib) into a listbox in a Tkinter GUI. The current version of the code is:
Button_4 = Button(self, text="Load object list", command=self.populateListbox)
Button_4.grid(row=14, column=0, sticky=N)
self.List_3 = Listbox(self, height=7, width=40, selectmode='single', exportselection=0)
self.List_3.grid(row=15, column=0, sticky=N)
def populateListbox(self):
g=rdflib.Graph()
filename = r'bim\Perceel4.owl'
g.load(filename, format='xml')
Layer = u'Asfaltplak_onderlaag'
qres = g.query(
"""SELECT DISTINCT ?value ?name ?file ?frag
WHERE {
-- SparQL query for results--
}""",
initNs=dict(
cbim=Namespace("http://www.coinsweb.nl/cbim-1.1.owl#")))
for row in qres:
if (rdflib.term.Literal(Layer, datatype=rdflib.term.URIRef(u'http://www.w3.org/2001/XMLSchema#string')) in row):
self.lst = row['file']
self.List_3.insert("end",self.lst)
If I print the SparQL query using the command: print: self.lst, I get the following print message:
DTB HRB 166.495 - 166.038 VH_gml.xml
DTB OPR 167.647 - 167.601 VH_gml.xml
DTB PST 170.824 - 170.769 VH_gml.xml
DTB HRB 166.038 - 164.169 VH_gml.xml
DTB PST 167.696 - 167.767 VH_gml.xml
...etc (more of these filenames)
When I run the program and click on the button to populate the listbox, I only get one name in the listbox, namely the first one of the list. How can I get the entire list inserted in the listbox, such as it comes out the print command?
Ps. I tried the '*' by using self.List_3.insert("end",self.*lst), but that only splits the name into a list that consist of the name split, as such:
D
T
S
1
2
..etc
U p d a t e :
I have added the list split as such:
...
output = row['file']
self.lst = output.split("\n")
self.List_3.insert("end",*self.lst)
but it still only gives one list entry in the listbox (the last one of the list). If I print self.lst in the new setup, it prints:
[u'DTB HRB 167.639 - 167.696 VH_gml.xml']
[u'DTB PST 167.134 - 167.274 VH_gml.xml']
[u'DTB HRB 166.038 - 164.169 VH_gml.xml']
...etc
import Tkinter as tk
def populateListbox(lstt):
listbox.insert("end", *lstt)
root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
lst = ["one", "two", "three", "four"]
btn = tk.Button(root, text="Populate listbox", command = lambda: populateListbox(lst))
btn.pack()
root.mainloop()
This is the simplified version of how you can populate listbox with a list of items. If you are getting list in your callback, you can remove lambda and parameter which leads to something like this.
def populateListbox():
lst = [...] #gathered inside
listbox.insert("end", *lst)
btn = tk.Button(..., command = populateListbox)
Also, those return statement in selectOwl is useless since there is nothing to assign that return values. Try to use your value in your command if they are needed.
Looking at the edit, it seems like all items in a single string. You need to split them by something. (In here it seems like it is new line \n). .split() will create a list then you can use *lst format.
outp = "DTB HRB 166.495 - 166.038 VH_gml.xml\nDTB OPR 167.647 - 167.601 VH_gml.xml\nDTB PST 170.824 - 170.769 VH_gml.xml"
print outp
DTB HRB 166.495 - 166.038 VH_gml.xml
DTB OPR 167.647 - 167.601 VH_gml.xml
DTB PST 170.824 - 170.769 VH_gml.xml
lst = outp.split("\n")
lst
Out[5]:
['DTB HRB 166.495 - 166.038 VH_gml.xml',
'DTB OPR 167.647 - 167.601 VH_gml.xml',
'DTB PST 170.824 - 170.769 VH_gml.xml']

Categories