在这里编写新手代码,尝试掌握Python 3。
是否可以使用从文本文件中读取的单个单词值来填充tkinter Combobox
?
我想做的是用从文本文件中读取的值(每个单词在单独的一行上)替换“鱼”,“鸟”等的硬编码值(见下文)。我一直在阅读有关字典,数组等的内容,而我所做的只是让自己感到困惑!
谢谢。
此代码段适用于硬编码的组合值。我该如何更改它才能从文件中读取值?
# imports
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Combo Test")
# Creature Drop Down
ttk.Label(win, text="Select Creature").grid(column=1, row=3)
creature_box = tk.StringVar()
creature_chosen = ttk.Combobox(win, width=20, state='readonly')
creature_chosen['values'] = ('Fish', 'Birds', 'Insects', 'Reptiles')
creature_chosen.grid(column=2, row=3)
creature_chosen.current(0)
# Start GUI
win.mainloop()
答案 0 :(得分:0)
您可以轻松地将这些值存储在txt
文件中并从那里读取它们。考虑到文件的内容格式如下:
Fish
Birds
Insects
Reptiles
您可以按以下方式修改代码:
# imports
import tkinter as tk
from tkinter import ttk
# Read values from file
creatures = []
with open('data.txt') as inFile:
creatures = [line for line in inFile]
# Create instance
win = tk.Tk()
# Add a title
win.title("Combo Test")
# Creature Drop Down
ttk.Label(win, text="Select Creature").grid(column=1, row=3)
creature_box = tk.StringVar()
creature_chosen = ttk.Combobox(win, width=20, state='readonly')
creature_chosen['values'] = tuple(creatures)
creature_chosen.grid(column=2, row=3)
creature_chosen.current(0)
# Start GUI
win.mainloop()