如何使用wxpython实时重置组合框的选项?

2024-10-03 11:18:09 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着用语音模块制作一个相对简单的TTS程序。我陷入困境的地方是:我想通过窗口中的组合框列出保存的文本列表,如果你从中添加或删除任何预设,它不会更新选项,直到程序重新加载。有没有办法实时更新选项?在

组合框初始化如下:

#I have a previously set txt file with a list of presets, and its partial destination saved in a variable "savefile"
fh = open(savefile + '//presets.txt')
presets = fh.read().split('\n')
self.presetList = presets
#self.presetList is now the list of choices for the combobox, causing it to update upon loading the program
self.presetbox = wx.ComboBox(self, pos=(90, 100), size=(293, -1), choices=self.presetList, style=wx.CB_READONLY)
self.Bind(wx.EVT_COMBOBOX, self.EvtComboBox, self.presetbox)

后来,比如说,要清除所有的选择,我需要这样的东西:

^{pr2}$

有办法吗?如果是这样,那太好了!:)


Tags: oftheself程序txt选项listchoices
3条回答

这对我很有效,绑定EVT_COMBOBOX_下拉列表来更新列表,而绑定EVT_COMBOBOX来运行用户选择的函数。这样更新,然后显示更新的内容。如果新的选择更少,它就不会留下先前选择的空白。您还可以将组合框设置为只读,以作为选项小部件(用户不可编辑),如下所示。这段代码在Windows、python3.6和更新的wxpython(phoenix)下进行了测试。在

import wx  
class Mywin(wx.Frame): 
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title,size = (300,200)) 

      panel = wx.Panel(self) 
      box = wx.BoxSizer(wx.VERTICAL) 
      self.label = wx.StaticText(panel,label = "Your choice:" ,style = wx.ALIGN_CENTRE) 
      box.Add(self.label, 0 , wx.EXPAND |wx.ALIGN_CENTER_HORIZONTAL |wx.ALL, 20) 
      cblbl = wx.StaticText(panel,label = "Combo box",style = wx.ALIGN_CENTRE) 

      box.Add(cblbl,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5) 
      #                initial chioces are 5
      #                           
      languages = ['C', 'C++', 'Python', 'Java', 'Perl']
      #                           
      self.combo = wx.ComboBox(panel,choices = languages, style = wx.CB_READONLY)
      box.Add(self.combo,0,wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALL,5) 

      self.combo.Bind(wx.EVT_COMBOBOX         ,self.OnCombo)
      self.combo.Bind(wx.EVT_COMBOBOX_DROPDOWN,self.updatelist)

      panel.SetSizer(box) 
      self.Centre() 
      self.Show() 

   def OnCombo(self, event): 
      self.label.SetLabel("You selected "+self.combo.GetValue()+" from Combobox")

   def updatelist(self, event):
      #             Chioces are now just 2
      #                           
      OtrosLanguajes = ['C++', 'Python']
      #                           
      self.combo.SetItems(OtrosLanguajes)

app = wx.App() 
Mywin(None,  'ComboBox and Choice demo') 
app.MainLoop()

我引用C++ WxWiWestReX文档而不是WxPython文档,因为它们通常更好:但是,名称应该是相同的。在

wxComboBox派生自wxItemContainer,它有一系列简单称为Set的函数,您可以传入一个字符串列表来设置组合框的内容。您还可以使用AppendInsert函数,以及清除所有选项的Clear函数。在

wxItemContainer文档在此处:http://docs.wxwidgets.org/trunk/classwx_item_container.html

组合框是textcrl和ListBox(http://wxpython-users.1045709.n5.nabble.com/Question-on-wx-ComboBox-Clear-td2353059.html)的混合体

要重置字段,可以使用self.presetbox.SetValue('')

(如果组合框不是只读的)

相关问题 更多 >