Python Forum
combobox_callback(choice choice part of openfile name (kind of dependency)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
combobox_callback(choice choice part of openfile name (kind of dependency)
#1
hello.
Goal is: clicking i.e: Akershus in a not placed colmbobox, fills another combo using content of a placed combobox.
(kind of dependency)
Trying to use choice building file (path AND filename.
Then use choice as the clicked textfile and fill a combobox from the textfile.
Issue is, the choice printsout the correct name but cant use choice building the name of text file.
Hard codeing name of file yields expected result.
Below is colde/errorcode.
Thank You in advance.

def fillcombokommuner(window):
    def combobox_callback(choice):
        print("combobox dropdown clicked:", choice)
        #-----------------------
    file = "d:/python311/userfiles/" + choice + ".txt"
    print(file)
    with open(file, "r") as file:
        values = [x for x in file]
        kommu = tk.CTkComboBox(window, values = values, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300")
    kommu.place(x=1140,y=673)
    kommu.set(values[0])
    file.close()
        # ---------------------    
values = [
    'Akershus',
    'Aust-Agder',
    'Buskerud',
    'Finnmark',
    'Hedmark',
    'Hordaland',
    'Møre og Romsdal',
    'Nordland',
    'Nord-Trøndelag',
    'Oppland',
    'Oslo',
    'Rogaland',
    'Sogn og Fjordane',
    'Sør-Trøndelag',
    'Telemark',
    'Troms',
    'Vest-Agder',
    'Vestfold',
    'Østfold'
]
Error:
Traceback (most recent call last): File "d:\Python311\Scripts\nye.py", line 419, in <module> fillcombokommuner(window) File "d:\Python311\Scripts\setuptable.py", line 144, in fillcombokommuner with open(file, "r") as file: ^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'd:/python311/userfiles/.txt' PS C:\Users\jan-e> & D:/Python311/python.exe d:/Python311/Scripts/nye.py d:/python311/userfiles/.txt Traceback (most recent call last): File "d:\Python311\Scripts\nye.py", line 419, in <module> fillcombokommuner(window) File "d:\Python311\Scripts\setuptable.py", line 144, in fillcombokommuner with open(file, "r") as file: ^^^^^^^^^^^^^^^ FileNotFoundError: [Errno 2] No such file or directory: 'd:/python311/userfiles/.txt'
Reply
#2
Your code has print statements. Why don't we get to see what is printed? Is it top secret?

Why are your writing files here? 'd:/python311/userfiles/.txt'. d:/python311 looks like it might be the folder where you would find Python 3.11. You should not be writing any files to this directory or any subdirectory.

Windows does not let you name a file ".txt". That is the reason for the error. Looks like an empty str is passed for choice. How is combobox_callback(choice) getting called. You did not post the code that binds the combobox selection event. For CTk.ComboBox this is done using "command=some_function". I'm pretty sure that is where the error is.

This is odd. I don't think it does what you think.
    with open(file, "r") as file:
        values = [x for x in file]
Let's say that "file" looks like this:
[output]Akershus
Aust-Agder
Buskerud
Finnmark[/output]
This makes a values list like this:
[python]values = ['Akershus\n', 'Aust-Agder\n', 'Buskerud\n', 'Finnmark']
Do you want those newlines? Probably not. Maybe your file looks like this:
Output:
Akershus Aust-Agder Buskerud Finnmark
That makes values look like this:
values = ['Akershus Aust-Agder Buskerud Finnmark']
That's no good. values has only 1 string.

You probably want to do this:
with open("data.csv", "r") as file:
    values = [x.strip() for x in file])
Reply
#3
hi,
Regarding prints:
1) print("combobox dropdown clicked:", choice)
choice has name of dropdown clicked.
ie:Akershus

Akershus is the name of textfile I try to build a full path for opening and reading its content into combobox kommu.
i.e: file = "d:/python311/userfiles/" + choice + ".txt"
This result in an error showing file without its file forname.(see op error

So I guess iits pehaps some with content formatting causing the error(?)
The calllback (CTkCombobox eventwaas found in ctkc document.

Content of textfile is inputs from notepad utf-8:

Akershus
Aust-Agder
.
.
.
i.e:
def fillcombokommuner(window):
    def combobox_callback(choice):
        print("combobox dropdown clicked:", choice)
        #-----------------------
    file = "d:/python311/userfiles/" + choice + ".txt"
    print(file)
I think I followed Your previous advice using another dir for my user files.(named userfiles

I wanted to try this appproach instead of using lots of if.. statements and repeating code for all the values.
But, if I can manage to use choice in callback building a full filepath with content as filename, it will work. <----main issue?
Hardcoding full path gives the wanted result.
Reply
#4
Your comments contradict the facts. You say this:
Quote:Regarding prints:
1) print("combobox dropdown clicked:", choice)
choice has name of dropdown clicked.
ie:Akershus
But this error message is proof that the choice passed to combo_callback(choice) is an empty string:
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'd:/python311/userfiles/.txt'
I have no choice but to believe what Python says and assume that your statement is incorrect.

Much of my doubt is from you not posting the code showing how you make the combobox that calls combo_callback(choice). Is that combobox built from another file?

Can you post the contents of one of these combobox value files?
Reply
#5
(Sep-05-2023, 07:32 PM)deanhystad Wrote: Your code has print statements. Why don't we get to see what is printed? Is it top secret?

Why are your writing files here? 'd:/python311/userfiles/.txt'. d:/python311 looks like it might be the folder where you would find Python 3.11. You should not be writing any files to this directory or any subdirectory.

Windows does not let you name a file ".txt". That is the reason for the error. Looks like an empty str is passed for choice. How is combobox_callback(choice) getting called. You did not post the code that binds the combobox selection event. For CTk.ComboBox this is done using "command=some_function". I'm pretty sure that is where the error is.

This is odd. I don't think it does what you think.
    with open(file, "r") as file:
        values = [x for x in file]
Let's say that "file" looks like this:
[output]Akershus
Aust-Agder
Buskerud
Finnmark[/output]
This makes a values list like this:
[python]values = ['Akershus\n', 'Aust-Agder\n', 'Buskerud\n', 'Finnmark']
Do you want those newlines? Probably not. Maybe your file looks like this:
Output:
Akershus Aust-Agder Buskerud Finnmark
That makes values look like this:
values = ['Akershus Aust-Agder Buskerud Finnmark']
That's no good. values has only 1 string.

You probably want to do this:
with open("data.csv", "r") as file:
    values = [x.strip() for x in file])

(Sep-06-2023, 02:28 AM)deanhystad Wrote: Your comments contradict the facts. You say this:
Quote:Regarding prints:
1) print("combobox dropdown clicked:", choice)
choice has name of dropdown clicked.
ie:Akershus
But this error message is proof that the choice passed to combo_callback(choice) is an empty string:
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'd:/python311/userfiles/.txt'
I have no choice but to believe what Python says and assume that your statement is incorrect.
Much of my doubt is from you not posting the code showing how you make the combobox that calls combo_callback(choice). Is that combobox built from another file?
Can you post the contents of one of these combobox value files?

Attached is one of several text-files and an image of screen.
Ref image:
LAND mean country. FYLKE mean County and KOMMUNE MEANS municipality.

Goal: Click once on the combobox A. with text Klikk meg, så kommune. (Text will be changed to: Velg fylke, så kommune)
From the choice of County, combo A,use name of the county to be part of full filepath, i.e: "d:/python311/userfiles/Akershus.txt)
That is an allready handmade textfile containing names of all municipalities in Akershus county.
Then populate a combobox B with the muncipalities.
If possible, make combobox A invisible after county is choosen and place combobox B at same x,y positiion for user to choose a municipality.
Problem atm. is using the choice type which seemes to contain name of choosen clicke value, to be part of forming a full file path i.e:
"d:/python311/userfiles/" + choice + ".txt"
Output:
combobox dropdown clicked: Akershus

Attached Files

Thumbnail(s)
   

.txt   akershus.txt (Size: 196 bytes / Downloads: 52)
Reply
#6
Everything is working now?

You still have not posted any code showing how your combobox objects are connected to callback functions.

This sounds like a bad idea:
Quote:If possible, make combobox A invisible after county is choosen and place combobox B at same x,y positiion for user to choose a municipality.
How do you go back and pick a different country? Users don't like it when controls change what they do.
Reply
#7
(Sep-05-2023, 07:32 PM)deanhystad Wrote: Your code has print statements. Why don't we get to see what is printed? Is it top secret?

Why are your writing files here? 'd:/python311/userfiles/.txt'. d:/python311 looks like it might be the folder where you would find Python 3.11. You should not be writing any files to this directory or any subdirectory.

Windows does not let you name a file ".txt". That is the reason for the error. Looks like an empty str is passed for choice. How is combobox_callback(choice) getting called. You did not post the code that binds the combobox selection event. For CTk.ComboBox this is done using "command=some_function". I'm pretty sure that is where the error is.

This is odd. I don't think it does what you think.
    with open(file, "r") as file:
        values = [x for x in file]
Let's say that "file" looks like this:
[output]Akershus
Aust-Agder
Buskerud
Finnmark[/output]
This makes a values list like this:
[python]values = ['Akershus\n', 'Aust-Agder\n', 'Buskerud\n', 'Finnmark']
Do you want those newlines? Probably not. Maybe your file looks like this:
Output:
Akershus Aust-Agder Buskerud Finnmark
That makes values look like this:
values = ['Akershus Aust-Agder Buskerud Finnmark']
That's no good. values has only 1 string.

You probably want to do this:
with open("data.csv", "r") as file:
    values = [x.strip() for x in file])

(Sep-06-2023, 04:16 PM)deanhystad Wrote: Everything is working now?

You still have not posted any code showing how your combobox objects are connected to callback functions.

This sounds like a bad idea:
Quote:If possible, make combobox A invisible after county is choosen and place combobox B at same x,y positiion for user to choose a municipality.
How do you go back and pick a different country? Users don't like it when controls change what they do.

Reason for "forcing" choose of municipalities using read only dropdown is to keep infos correct within a specific time periode. there is approx 356 municipalities, too many to present at one time, so I could show them all in a menu ordered in two columns, but think it still would be too much info at a time. So choosing a municipality willl take two steps: Choose county then municipality. Another reason is to be sure user do input county before choosing
municipality. Im glad I dont know what issues will show up in the above.

Binding widgets/functions regarding custom TkComboBox, I dont know other ways shown in documentation.
I prefer to use events click to execute a function.

It doesnt work yet, under construction. Event click "works" printing the "choice" parameter. Now I hope I can use content of choice,containing the filename, to build a path including the filename and its file extention. Ill read in the python and os methodes to check that.
I will rethink Your info regarding structure of fille. Thank You.
Reply
#8
What does this mean?
Quote:Binding widgets/functions regarding custom TkComboBox, I dont know other ways shown in documentation.
I prefer to use events click to execute a function.

The documentation shows binding the combobox to a function like this:
check_var = customtkinter.StringVar(value="on")
checkbox = customtkinter.CTkCheckBox(app, text="CTkCheckBox", command=checkbox_event,
                                     variable=check_var, onvalue="on", offvalue="off")
The only code you have posted is this:
        kommu = tk.CTkComboBox(window, values = values, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300")
These are not the same. When you create the combobox you are not assigning anything to "command".

Where is the code that tells the combobox to call combobox_callback(choice)?

The other confusing thing is you say the print statement prints this:
Quote:Regarding prints:
1) print("combobox dropdown clicked:", choice)
choice has name of dropdown clicked.
ie:Akershus
If this is true, then this error would not occur.
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'd:/python311/userfiles/.txt'
One of these statements is incorrect. Which one?
Reply
#9
(Sep-05-2023, 07:32 PM)deanhystad Wrote: Your code has print statements. Why don't we get to see what is printed? Is it top secret?

Why are your writing files here? 'd:/python311/userfiles/.txt'. d:/python311 looks like it might be the folder where you would find Python 3.11. You should not be writing any files to this directory or any subdirectory.

Windows does not let you name a file ".txt". That is the reason for the error. Looks like an empty str is passed for choice. How is combobox_callback(choice) getting called. You did not post the code that binds the combobox selection event. For CTk.ComboBox this is done using "command=some_function". I'm pretty sure that is where the error is.

This is odd. I don't think it does what you think.
    with open(file, "r") as file:
        values = [x for x in file]
Let's say that "file" looks like this:
[output]Akershus
Aust-Agder
Buskerud
Finnmark[/output]
This makes a values list like this:
[python]values = ['Akershus\n', 'Aust-Agder\n', 'Buskerud\n', 'Finnmark']
Do you want those newlines? Probably not. Maybe your file looks like this:
Output:
Akershus Aust-Agder Buskerud Finnmark
That makes values look like this:
values = ['Akershus Aust-Agder Buskerud Finnmark']
That's no good. values has only 1 string.

You probably want to do this:
with open("data.csv", "r") as file:
    values = [x.strip() for x in file])

(Sep-07-2023, 03:20 AM)deanhystad Wrote: What does this mean?
Quote:Binding widgets/functions regarding custom TkComboBox, I dont know other ways shown in documentation.
I prefer to use events click to execute a function.

The documentation shows binding the combobox to a function like this:
check_var = customtkinter.StringVar(value="on")
checkbox = customtkinter.CTkCheckBox(app, text="CTkCheckBox", command=checkbox_event,
                                     variable=check_var, onvalue="on", offvalue="off")
The only code you have posted is this:
        kommu = tk.CTkComboBox(window, values = values, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300")
These are not the same. When you create the combobox you are not assigning anything to "command".

Where is the code that tells the combobox to call combobox_callback(choice)?

The other confusing thing is you say the print statement prints this:
Quote:Regarding prints:
1) print("combobox dropdown clicked:", choice)
choice has name of dropdown clicked.
ie:Akershus
If this is true, then this error would not occur.
Error:
FileNotFoundError: [Errno 2] No such file or directory: 'd:/python311/userfiles/.txt'
One of these statements is incorrect. Which one?

hello.
Here is the code regarding callback. Last part (command......) didnt get by a copy matter. Sorry for that.
https://customtkinter.tomschimansky.com/...s/combobox

def combobox_callback(choice):
print("combobox dropdown clicked:", choice)

combobox = customtkinter.CTkComboBox(app, values=["option 1", "option 2"],
command=combobox_callback)
The codeline with command:
kommu = tk.CTkComboBox(window, values = values, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300", command=combobox_callback)
code regarding building full file patrh:
[
navn = str(choice)
    navn.strip()
    print("combobox dropdown clicked after strip:", choice)
    # ------------build full path to file, used to fill a combobox which holds the muni's for user to choose.
    file = "d:/Python311/userfiles/" + navn + ".txt"
Output:
output from print(file) i the full path including filename and its extention. output from print(choiice) is the valuename clicked
Reply
#10
Needed 3 custom CTk comboboxes with values showing Countries, Counties and municipalities.
Goal: Write a code in Python without notice of dirty coding. All the dirt is on my behalf.

After selecting county (Fylke) combo, the municipality combo pops up with its municipalities for that county.

Thanks to all helping out.

def fillcomboland(window):
    file = "d:/Python311/userfiles/inpland.txt"
    with open(file, "r") as file:
        values = [x.strip() for x in file]
    
    land = tk.CTkComboBox(window, values=values, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300")
    land.place(x=1140,y=745)
    land.set(values[129])

# ------------------populate county combo by reading hard coded values below-----------------------------------
def fillcombofylker(window):
        values2 = [
            'Akershus',
            'Aust-Agder',
            'Buskerud',
            'Finnmark',
            'Hedmark',
            'Hordaland',
            'Møre og Romsdal',
            'Nordland',
            'Nord-Trøndelag',
            'Oppland',
            'Oslo',
            'Rogaland',
            'Sogn og Fjordane',
            'Sør-Trøndelag',
            'Telemark',
            'Troms',
            'Vest-Agder',
            'Vestfold',
            'Østfold'
        ]
        # --------------------get the selected element from the county combo, which also names the textfile containing municipalities within that county.
        def combobox_callback(choice):
            filnavn2 = str(choice)
            fil = "d:/Python311/userfiles/" + str(filnavn2) + ".txt"
            #--populate combobox kommune from textfile named (selected from combobox fylker) filnavn2-----------------
            with open(fil, "r") as fil:
                values4 = [x.strip() for x in fil]
                # the municipality combo
            kommune = tk.CTkComboBox(window, values = values4, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300")
            kommune.place(x=1140,y=673)
            
            # check if correct filepath
            print(fil)
          # the county combo  
        fylke = tk.CTkComboBox(window, values = values2, font=('Ariel', 14,"bold"), width=200, height=32, corner_radius=10,fg_color="#cdebb0", text_color = "#003300",command=combobox_callback)
        fylke.place(x=1140,y=709)
Output:
PS C:\Users\jan-e> & D:/Python311/python.exe d:/Python311/Scripts/nye.py <_io.TextIOWrapper name='d:/Python311/userfiles/Nord-Trøndelag.txt' mode='r' encoding='cp65001'> <_io.TextIOWrapper name='d:/Python311/userfiles/Akershus.txt' mode='r' encoding='cp65001'> <_io.TextIOWrapper name='d:/Python311/userfiles/Oppland.txt' mode='r' encoding='cp65001'>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] What is the best/pytonic way to import with dependency ? SpongeB0B 2 688 Jul-09-2023, 05:05 AM
Last Post: SpongeB0B
  input variable choice MCL169 7 1,195 Feb-19-2023, 09:00 PM
Last Post: MCL169
  Request Dependency warning thetechnodino 0 941 Dec-20-2022, 02:12 AM
Last Post: thetechnodino
  Menu Choice Selection not Working ChLenx79 5 1,551 Nov-23-2022, 05:56 AM
Last Post: deanhystad
  What kind of list is this? jesse68 2 1,150 Jun-29-2022, 05:02 PM
Last Post: rob101
  random.choice HELP samuelbachorik 4 2,282 Aug-18-2021, 03:24 PM
Last Post: naughtyCat
  Unable to use random.choice(list) in async method spacedog 4 3,452 Apr-29-2021, 04:08 PM
Last Post: spacedog
  Circular import dependency hobbyist 9 3,870 Feb-23-2021, 11:57 AM
Last Post: Gribouillis
  splitting lines, need to add element of same kind tester_V 6 3,152 Feb-20-2021, 11:51 PM
Last Post: tester_V
  Poetry Dependency general Help felipesodre 0 1,452 Jan-14-2021, 07:46 PM
Last Post: felipesodre

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020