【问题标题】:Python/ttk/tKinter - passing an argument with a button click func?Python/ttk/tKinter - 通过按钮单击功能传递参数?
【发布时间】:2013-01-13 05:57:52
【问题描述】:

我正在尝试将参数传递给按钮单击函数并遇到问题。

简而言之,我试图按下按钮以弹出askColor() 方法,并将该颜色值作为相关文本框的背景颜色返回。

它的功能是使联觉者可以将颜色与字母/数字相关联并记录生成的颜色列表。

具体行:

    self.boxA = Text(self.mainframe, state='normal', width=3, height=1, wrap='word', background=self.AVal).grid(column=2, row=2, padx=4)
    self.boxB = Text(self.mainframe, state='normal', width=3, height=1, wrap='word', background=self.AVal).grid(column=3, row=2, padx=4)
    self.boxC = Text(self.mainframe, state='normal', width=3, height=1, wrap='word', background=self.AVal).grid(column=4, row=2, padx=4)

    self.ABlob = ttk.Button(self.mainframe, text="A",style= 'mainSmall.TButton', command= lambda: self.getColour(self.boxA)).grid(column=2, row=3)
    self.BBlob = ttk.Button(self.mainframe, text="B",style= 'mainSmall.TButton', command= lambda: self.getColour(self.boxB)).grid(column=3, row=3)
    self.CBlob = ttk.Button(self.mainframe, text="C",style= 'mainSmall.TButton', command= lambda: self.getColour(self.boxC)).grid(column=4, row=3)

和:

def getColour(self,glyphRef):
    (triple, hexstr) = askcolor()
    if hexstr:
            glyphRef.config(bg=hexstr)

问题是我似乎无法以我尝试的方式引用self.ABlob - 它返回类型None。我尝试在按钮单击功能中包含pack.forget 命令,但这也不起作用。

【问题讨论】:

    标签: python tkinter ttk


    【解决方案1】:

    您问题的主要部分似乎是:

    问题是我似乎无法以我的方式引用 self.ABlob 我正在尝试 - 它返回类型 None

    当您执行x=ClassA(...).func(...) 时,x 包含调用func 的结果。因此,当您执行self.ABlob = ttk.Button(...).grid(...) 时,存储在self.ABlob 中的是None,因为这是网格函数返回的内容。

    如果您想存储对按钮的引用,您需要创建按钮,然后将网格作为两个单独的步骤调用:

    self.ABlob = ttk.Button(...)
    self.ABlob.grid(...)
    

    我个人认为这是一种最佳做法,尤其是在您使用网格时。通过将所有网格语句放在一个块中,可以更轻松地可视化布局和发现错误:

    self.ABlob.grid(row=3, column=2)
    self.BBlob.grid(row=3, column=3)
    self.CBlob.grid(row=3, column=4)
    

    【讨论】:

    • 我认为你是对的,我叫错了树。删除了我的答案。
    • 工作就像一个魅力,我学到了一些关于“嵌套”命令的东西。欣赏它。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多