Search code examples
pythonarraysuser-interfacecomboboxfiremonkey

How can I create a dropdown combobox from a list in a Python FMX GUI App?


I'm creating a GUI using DelphiFMX GUI library for Python that has a ComboBox on it and I also have a list (array) of strings that I want to put into the ComboBox. Here's my current code:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        self.Caption = 'My Form with ComboBox'
        self.Width = 600
        self.Height = 250

        self.myComboBox = ComboBox(self)
        self.myComboBox.Parent = self
        self.myComboBox.Align = "Top"
        self.myComboBox.Margins.Top = 20
        self.myComboBox.Margins.Right = 20
        self.myComboBox.Margins.Bottom = 20
        self.myComboBox.Margins.Left = 20

        Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

def main():
    Application.Initialize()
    Application.Title = "My Application"
    Application.MainForm = frmMain(Application)
    Application.MainForm.Show()
    Application.Run()
    Application.MainForm.Destroy()

main()

I've tried doing things like:

  1. self.myComboBox.Items.AddStrings(Months), but then I get a TypeError: "AddStrings" called with invalid arguments. Error: Could not find a method with compatible arguments error.
  2. self.myComboBox.Items.Text(Months), but then I get a TypeError: 'str' object is not callable error.
  3. self.myComboBox.Text = Months, but then I get an AttributeError: Error in setting property Text error.

How can I get the Months array into the ComboBox?


Solution

  • Use the following code:

    for i in range(0, len(Months)):
        self.myComboBox.Items.Add(Months[i])
    

    Python GUI with ComboBox

    So the full code is:

    from delphifmx import *
    
    class frmMain(Form):
        def __init__(self, owner):
            self.Caption = 'My Form with ComboBox'
            self.Width = 600
            self.Height = 250
    
            self.myComboBox = ComboBox(self)
            self.myComboBox.Parent = self
            self.myComboBox.Align = "Top"
            self.myComboBox.Margins.Top = 20
            self.myComboBox.Margins.Right = 20
            self.myComboBox.Margins.Bottom = 20
            self.myComboBox.Margins.Left = 20
    
            Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    
            for i in range(0, len(Months)):
                self.myComboBox.Items.Add(Months[i])
    
    def main():
        Application.Initialize()
        Application.Title = "My Application"
        Application.MainForm = frmMain(Application)
        Application.MainForm.Show()
        Application.Run()
        Application.MainForm.Destroy()
    
    main()