You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python FMX GUI应用中从列表创建下拉ComboBox?

DelphiFMX for Python:将字符串数组导入ComboBox组件的正确方法

我正在使用DelphiFMX GUI library for Python创建GUI,需要将一个字符串数组放入ComboBox组件中,当前代码如下:

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()

尝试了以下三种方法均报错:

  • self.myComboBox.Items.AddStrings(Months):报错 TypeError: "AddStrings" called with invalid arguments. Error: Could not find a method with compatible arguments
  • self.myComboBox.Items.Text(Months):报错 TypeError: 'str' object is not callable
  • self.myComboBox.Text = Months:报错 AttributeError: Error in setting property Text

正确解决方案

方法1:遍历数组逐个添加(最直接)

利用Python循环遍历字符串数组,通过ComboBox的Items.Add()方法逐个添加元素:

Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
# 添加遍历逻辑
for month in Months:
    self.myComboBox.Items.Add(month)

方法2:使用TStringList批量导入

DelphiFMX的AddStrings()方法要求参数是Delphi原生的TStringList对象而非Python列表,可先将Python数组转为TStringList,再通过Assign()方法批量导入:

from delphifmx import *

class frmMain(Form):
    def __init__(self, owner):
        # ... 原有代码省略 ...

        Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
        
        # 创建TStringList并导入数组内容
        month_list = TStringList(self)
        month_list.AddStrings(Months)
        # 将TStringList内容赋值给ComboBox的Items
        self.myComboBox.Items.Assign(month_list)

错误原因说明

  1. AddStrings(Months):该方法要求参数为DelphiFMX的TStringList类型,而非Python原生列表,直接传数组会导致类型不匹配。
  2. Items.Text(Months):Items.Text是只读属性(返回下拉列表所有项的换行分隔字符串),不是可调用方法,无法传入参数调用。
  3. ComboBox.Text = Months:Text属性用于设置/获取ComboBox当前选中项的文本,无法接收数组作为值。

内容的提问来源于stack exchange,提问作者Shaun Roselt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:33:26