我正在使用文本文件来存储tkinter组合框的值。如果用户输入的值不在文件中,我想要添加它。一切正常,但如果用户选择现有值,它也会再次添加到列表中。我相信这是因为我正在返回剥离的值并与' \ n'进行比较。任何有关如何纠正此问题的帮助都非常感谢。
from tkinter import *
from tkinter import ttk
regionList = open('regions1.txt','r')
root = Tk()
root.configure()
varRegions = StringVar(root, value='')
class MainWindow(Frame):
def __init__(self,master = None):
Frame.__init__(self,master)
self.master = master
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create Window Layout"""
Boxfont = ('Arial', 12, 'bold')
self.blank = Label(self,text='').grid(row=2,column=0)
self.label = Label(self, font=Boxfont, text="Regions").grid(row=3,column=1)
self.regcombo = ttk.Combobox(self, font = Boxfont, width = 16, textvariable = varRegions)
self.regcombo.bind("<Return>", self.regcombo_onEnter)
self.regcombo.bind('<<ComboboxSelected>>',self.regcombo_onEnter)
self.regcombo['values'] = regionList.readlines()
self.regcombo.grid(row=3, column=2,sticky = W)
self.blank = Label(self,text='').grid(row=4,column=0)
def regcombo_onEnter(self,event):
varRegions.set(varRegions.get().lower().strip())
mytext = varRegions.get().strip()
vals = self.regcombo.cget('values')
self.regcombo.select_range(0,END)
print(mytext)
if not vals:
self.regcombo.configure(values = (mytext,))
elif mytext not in vals:
with open('regions1.txt','a') as f:
f.write('\n'+ mytext)
self.regcombo.configure(values = vals + (mytext,))
f.close
return 'break'
app = MainWindow(root)
root.mainloop()