对于用户来说,查看字符串列表并在tkinter窗口中编辑这些字符串的最佳方式是什么



这个标题可能会让我的目标听起来有点困惑,因为我不确定用什么最好的方式来表达它,但我想增加编辑字符串列表的功能,允许用户编辑它们,然后将它们保存到我目前正在处理的程序中。一种简单的方法是创建一个具有与其对应的entrylabel,并将变量的值设置为entry.get()。例如:

row=0
for line in build: # build is a list of strings
Label(build_window,text=line).grid(row=row,column=0,sticky=W) 
# build_window is a Toplevel of 'main_screen'
Entry(build_window).grid(row=row,column=1,sticky=W) 
# I know I'd need to save the entry as a variable or some other way in order to access
# the value but I left it like this for demonstration
row+=1

这将在同一行上创建一个标签和一个条目,然后将保存entry.get()的值。但问题是build包含50多行字符串,并且这种设置需要非常大的空间才能使用。你能用Listbox()Scrollbar()来达到这个效果吗?(询问,因为这是我之前在程序中列出它们的方式(我尝试过像普通列表(ListboxObject[1](一样索引Listbox()对象,但它只是返回一个错误,说它需要一个字符串,而不是int。

根据acw1668的建议,可以使用ListboxEntry的组合。每当列表框的选择发生变化(<<ListboxSelect>>事件(时,条目的内容都会设置为当前选择的字符串。然后,用户可以编辑条目中的字符串,并单击编辑按钮来验证更改。

import tkinter as tk
def on_listbox_select(event):
index = listbox.curselection()  # get index of selected line in listbox
entry.delete(0, 'end')          # clear the entry
if not index:
return
entry.insert(0, listbox.get(index))  # put the selected string in the entry
def edit():
index = listbox.curselection()  # get index of selected line in listbox
if not index:  
return  # no selected line, do nothing
# replace lisbox line with new string
listbox.delete(index)  
listbox.insert(index, entry.get())
listbox.see(index)
entry.delete(0, 'end')  # clear the entry
root = tk.Tk()
root.rowconfigure(0, weight=1)
build = ['string %i' % i for i in range(50)]
listbox = tk.Listbox(root, exportselection=False)
listbox.grid(row=0, column=0, sticky='ewsn')
# scrollbar
sb = tk.Scrollbar(root, orient='vertical', command=listbox.yview)
sb.grid(row=0, column=1, sticky='ns')
listbox.configure(yscrollcommand=sb.set)
# put content in listbox
for line in build:
listbox.insert('end', line)
# entry to edit the strings
entry = tk.Entry(root)
entry.grid(row=1, column=0, sticky='ew')
# validate button
tk.Button(root, text='Edit', command=edit).grid(row=2)
listbox.bind('<<ListboxSelect>>', on_listbox_select)
root.mainloop()

另一个解决方案是使用Text()对象,因为我没有使用它们,所以我忘记了它。

def edit_current_build(self,build_window,build):
perkList=tk.Text(build_window,width=59)
perkList.grid()
perkScrollbar=tk.Scrollbar(build_window,orient='vertical',command=perkList.yview)
perkScrollbar.grid(row=0,column=1,sticky='ns')
perkList.configure(yscrollcommand=perkScrollbar.set)
for line in build:
perkList.insert(END,line)
tk.Button(build_window,text='Save',command=lambda:self.save(build_window,build,perkList)).grid(sticky=W)
def save(self,build_window,build,perkList):
currentBuild=[]
for line in perkList.get('1.0','end-1c').split('n'): # seperates lines but 'n' is added later as I still want the newlines
line+='n'
currentBuild.append(line)

最新更新