最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - How can I loop thru combo boxes and set the value? My code produces the error "An error occurred: 'str

programmeradmin4浏览0评论

I have a set of combo boxes that the user will use to set parameters in a Ham radio. I am trying to 'set' the default values for each combo box when the user asks for a new clean file.

I have saved a dictionary in a json file which contains all the default parameter values. The function opens and loads the json file into a dictionary. Then I want to loop thru each combo box and 'set' its value from the dictionary. My code produces an error, "An error occurred: 'str' object has no attribute 'set' " when attempting to 'set' the combobox value.

I'm building the combobox name with a combination of the text "combobox_" and concatenating the three number key string and setting a string variable. Then using that variable with the 'set' method to change the combobox value. I've replaced the variable with an actual combobox name, and it works fine. So, it doesn't like my variable. Is there a way to loop thru the combobox widgets and set the value for each one?

def new_file() is called from a button to return combobox values to default. I've limited this code to 2 combo boxes. There are 153 in total.

# Load json file ================== 
def load_json_file(file_path): # Load the JSON file with the menu data 
    print(f"Loading data file '{file_path}'...")
    try:
        with open(file_path, 'r') as file:
            data = json.load(file)
        print(f"Loaded data file successfully.")
        return data
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except json.JSONDecodeError as e:
        print(f"Error: Failed to decode JSON. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
# load default values to combo boxes
def new_file():
  global Menu_Value
   # Retrieve data file
  file_path = 'Default_Menu_Values.991A'
  data = load_json_file(file_path)
   # Load Combo Boxes with Default Menu Values
  try:
    for m in range (1, 2):
      ID = f"{m:03}"
      Menu_Value = str(data.get(ID))
      combo = "combobox_" + str(ID)
      combo.set(Menu_Value)            # Error happens here
  except Exception as e:
        print(f"An error occurred: {e}")

# code from main ==========================
# Create Combo Boxes ====================
  # label_001 ==============================================
label_001 = ttk.Label(main_frame, text="001 - AGC FAST DELAY   (msec)", width=35, relief="raised")
label_001.grid(row=0, column=0, padx=5, pady=5, ipadx=1, ipady=1, sticky="e")
  # Combobox 001 ===========================================
values_001 = list(range(20, 4020, 20))
combobox_001 = ttk.Combobox(main_frame, width=15, values=values_001)
combobox_001.set("300 msec")
  # Restrict selection to the drop-down list
combobox_001.state(["readonly"])
combobox_001.grid(row=0, column=1, padx=5, pady=5, sticky="w")

  # label_002 ====================================================
label_002 = ttk.Label(main_frame, text="002 - AGC MID DELAY   (msec)", width=35, relief="raised")
label_002.grid(row=1, column=0, padx=5, pady=5, ipadx=1, ipady=1, sticky="e")
  # Combobox 002 ==================================================
values_002 = list(range(20, 4020, 20))
combobox_002 = ttk.Combobox(main_frame, width=15, values=values_002)
combobox_002.set("700 msec")
  # Restrict selection to the drop-down list
combobox_002.state(["readonly"])
combobox_002.grid(row=1, column=1, padx=5, pady=5, sticky="w")

I have a set of combo boxes that the user will use to set parameters in a Ham radio. I am trying to 'set' the default values for each combo box when the user asks for a new clean file.

I have saved a dictionary in a json file which contains all the default parameter values. The function opens and loads the json file into a dictionary. Then I want to loop thru each combo box and 'set' its value from the dictionary. My code produces an error, "An error occurred: 'str' object has no attribute 'set' " when attempting to 'set' the combobox value.

I'm building the combobox name with a combination of the text "combobox_" and concatenating the three number key string and setting a string variable. Then using that variable with the 'set' method to change the combobox value. I've replaced the variable with an actual combobox name, and it works fine. So, it doesn't like my variable. Is there a way to loop thru the combobox widgets and set the value for each one?

def new_file() is called from a button to return combobox values to default. I've limited this code to 2 combo boxes. There are 153 in total.

# Load json file ================== 
def load_json_file(file_path): # Load the JSON file with the menu data 
    print(f"Loading data file '{file_path}'...")
    try:
        with open(file_path, 'r') as file:
            data = json.load(file)
        print(f"Loaded data file successfully.")
        return data
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except json.JSONDecodeError as e:
        print(f"Error: Failed to decode JSON. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
# load default values to combo boxes
def new_file():
  global Menu_Value
   # Retrieve data file
  file_path = 'Default_Menu_Values.991A'
  data = load_json_file(file_path)
   # Load Combo Boxes with Default Menu Values
  try:
    for m in range (1, 2):
      ID = f"{m:03}"
      Menu_Value = str(data.get(ID))
      combo = "combobox_" + str(ID)
      combo.set(Menu_Value)            # Error happens here
  except Exception as e:
        print(f"An error occurred: {e}")

# code from main ==========================
# Create Combo Boxes ====================
  # label_001 ==============================================
label_001 = ttk.Label(main_frame, text="001 - AGC FAST DELAY   (msec)", width=35, relief="raised")
label_001.grid(row=0, column=0, padx=5, pady=5, ipadx=1, ipady=1, sticky="e")
  # Combobox 001 ===========================================
values_001 = list(range(20, 4020, 20))
combobox_001 = ttk.Combobox(main_frame, width=15, values=values_001)
combobox_001.set("300 msec")
  # Restrict selection to the drop-down list
combobox_001.state(["readonly"])
combobox_001.grid(row=0, column=1, padx=5, pady=5, sticky="w")

  # label_002 ====================================================
label_002 = ttk.Label(main_frame, text="002 - AGC MID DELAY   (msec)", width=35, relief="raised")
label_002.grid(row=1, column=0, padx=5, pady=5, ipadx=1, ipady=1, sticky="e")
  # Combobox 002 ==================================================
values_002 = list(range(20, 4020, 20))
combobox_002 = ttk.Combobox(main_frame, width=15, values=values_002)
combobox_002.set("700 msec")
  # Restrict selection to the drop-down list
combobox_002.state(["readonly"])
combobox_002.grid(row=1, column=1, padx=5, pady=5, sticky="w")
Share Improve this question asked Mar 11 at 6:31 user29962476user29962476 112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

The problem is that you're trying to use a string variable, combo, as if it were a combobox object.
What you can do is store your comboboxes objects in a dictionary and then access them by their keys.

Try this code, it should fix the problem. You can run it to confirm.

import tkinter as tk
from tkinter import ttk
import json

def load_json_file(file_path):
    print(f"Loading data file '{file_path}'...")
    try:
        with open(file_path, 'r') as file:
            data = json.load(file)
        print(f"Loaded data file successfully.")
        return data
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except json.JSONDecodeError as e:
        print(f"Error: Failed to decode JSON. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")


def new_file():
    global combobox_dict
    file_path = 'Default_Menu_Values.991A'
    data = load_json_file(file_path)  # dictionary with the default values
    try:
        for m in range(1, 3):
            ID = f"{m:03}"  # key of the value in dictionary
            Menu_Value = str(data.get(ID))  # default value for each combobox as string
            combobox_dict[f"combobox_{ID}"].set(Menu_Value)  # combobox widget stored in the combobox_dict
    except Exception as e:
        print(f"An error occurred: {e}")


# Main window setup
root = tk.Tk()
main_frame = ttk.Frame(root)
main_frame.pack(padx=10, pady=10)

# Create Combo Boxes and store them in a dictionary
combobox_dict = {}  # store the combobox widgets

label_001 = ttk.Label(main_frame, text="001 - AGC FAST DELAY   (msec)", width=35, relief="raised")
label_001.grid(row=0, column=0, padx=5, pady=5, ipadx=1, ipady=1, sticky="e")
values_001 = list(range(20, 4020, 20))
combobox_001 = ttk.Combobox(main_frame, width=15, values=values_001)
combobox_001.set("300")
combobox_001.state(["readonly"])
combobox_001.grid(row=0, column=1, padx=5, pady=5, sticky="w")
combobox_dict["combobox_001"] = combobox_001  # store the combobox_001 widget

label_002 = ttk.Label(main_frame, text="002 - AGC MID DELAY   (msec)", width=35, relief="raised")
label_002.grid(row=1, column=0, padx=5, pady=5, ipadx=1, ipady=1, sticky="e")
values_002 = list(range(20, 4020, 20))
combobox_002 = ttk.Combobox(main_frame, width=15, values=values_002)
combobox_002.set("700")
combobox_002.state(["readonly"])
combobox_002.grid(row=1, column=1, padx=5, pady=5, sticky="w")
combobox_dict["combobox_002"] = combobox_002  # store the combobox_002 widget

new_file_button = ttk.Button(main_frame, text="New File", command=new_file)
new_file_button.grid(row=2, column=0, columnspan=2, pady=10)


# Example JSON file content (for testing)
with open('Default_Menu_Values.991A', 'w') as f:
    json.dump({"001": "100", "002": "500"}, f)

root.mainloop()

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论