Python tkinter combobox, how can I select dictionary key and print corresponding value?

Viewed 578

Very new to python and tkinter. I would like to create multiple comboboxes, independently selecting from a single dictionary, then print the corresponding values after clicking the "Submit" button. All I can manage from looking at somewhat similar questions without errors and frustration is printing the selected keys.

Simply put, I want to select A4 in the first combobox and A7 in the second combobox, click Submit, producing this result in the python shell:

8.3 x 11.7

2.9 x 4.1

Instead of this result:

A4

A7

Any advice would be appreciated.

import tkinter as tk
from tkinter import ttk

# Create instance
win = tk.Tk()

# Dictionary for combobox selection
Paper_sizes = {"":"", "A9":"1.5 x 2.0", "A8":"2.0 x 2.9",
               "A7":"2.9 x 4.1", "A6":"4.1 x 5.8", "A5":"5.8 x 8.3",
               "A4":"8.3 x 11.7", "A3":"11.7 x 16.5", "A2":"16.5 x 23.4",
               "A1":"23.4 x 33.1", "A0":"33.1 x 46.8"}
# Combobox 1
ttk.Label(win, text="Choose a paper size").grid(column=1, row=0)
paper1 = tk.StringVar()
paper1_chosen = ttk.Combobox(win, width=12, textvariable=paper1, state='readonly')
paper1_chosen['values']  = sorted(list(Paper_sizes.keys()))
paper1_chosen.grid(column=1, row=1)     
paper1_chosen.current(0)

# Combobox 2
ttk.Label(win, text="Choose a 2nd paper size").grid(column=1, row=2)
paper2 = tk.StringVar()
paper2_chosen = ttk.Combobox(win, width=12, textvariable=paper2, state='readonly')
paper2_chosen['values']  = sorted(list(Paper_sizes.keys()))
paper2_chosen.grid(column=1, row=3)     
paper2_chosen.current(0)

# Button Click Event Function
def submit_button():
    print(paper1_chosen.get())
    print(paper2_chosen.get())
    
# Adding a Button
action = ttk.Button(win, text = "Submit", command = submit_button)
action.grid(column=2, row=4)  

# Start GUI
win.mainloop()
1 Answers

Does changing your function to this, help you?

def submit_button():
    key1 = paper1_chosen.get()
    key2 = paper2_chosen.get()
    print(Paper_sizes[key1])
    print(Paper_sizes[key2])

Nothing much is happening inside, all thats happening is that you are taking the key from the combobox selection and printing out the corresponding value pair.

Hope you understood, let me know if you have more doubts.

Cheers

Related