ttk.button.cget 用法 - tkinter

ttk.button.cget usage - tkinter

我使用 tk 和 OOP 方法制作了一个训练应用程序。 程序结构为:

class Calculator:
    #constants and needed variables

    def __init__(self):
        #main window stuff
        self.createWidgets()

    def setVal(self): #function
    ...
    #other functions
    ...

    def createWidgets(self): #function creating all widgets

#mainloop

我想出了一种在 createWidgets 函数中快速生成所有按钮的好方法,如下所示:

for i in range(1,10):
        if i in [1,2,3]:
            ttk.Button(self.buttonLF, text=str(i), style="my.TButton", command=self.setVal).grid(row=0, column=i - 1)
        elif i in [4,5,6]:
            ttk.Button(self.buttonLF, text=str(i), style="my.TButton", command=self.setVal).grid(row=1, column=i - 4)
        else:
            ttk.Button(self.buttonLF, text=str(i), style="my.TButton", command=self.setVal).grid(row=2, column=i - 7)

命令函数 self.setVal 如下所示:(self.entry 是一个简单的输入字段,我从中获取数值)

def setVal(self):
    if len(self.entry.get()) >= 20:
        self.entry.delete(0, 20)
        self.entry.insert(0, "Max_length_exceeded!")
    else:
        if self.entry.get() == '':
            Calculator.old = 0
        else:
            Calculator.old = int(self.entry.get())
        self.entry.delete(0, 20)
        Calculator.new = 10 * Calculator.old

        #The part which I have problem with:
        self.entry.insert(0, str(Calculator.new + int(self.cget('text'))))
        Calculator.old = Calculator.new + int(self.cget('text'))

我进行转换以在 entry 中正确显示数字的方式并不重要(Calculator.old 变量等)。
我想做的主要事情是,我想使用 ttk.button 方法 cget('text'),将其转换为 int 并使用它来计算显示在 self.entry 字段中的输出。目前此代码不起作用(因为 self.cget)。
如何正确调用 cget 以从 createWidgets 函数中创建的按钮收集文本?
感谢所有反馈。

您错误地使用了 self 语句。在 class 内,例如Calculator self 总是指向这个 class 所以这里是 Calculator.因此 self.cget 不是指向 ttk.Button 中的 cget 方法,而是在计算器中寻找一个不存在的方法。此外,您不应在计算器 class 中使用计算器,而应使用 self.

现在您可以重写 setVal 函数以包含相应按钮的 cget 函数,但这有点麻烦。相反,我会更改 setVal 函数以具有显式输入值。这也更符合逻辑,可以更容易地重复使用。

def setVal(self,value):
    if len(self.entry.get()) >= 20:
        self.entry.delete(0, 20)
        self.entry.insert(0, "Max_length_exceeded!")
    else:
        if self.entry.get() == '':
            self.old = 0
        else:
            self.old = int(self.entry.get())
        self.entry.delete(0, 20)
        self.new = 10 * self.old

        self.entry.insert(0, str(self.new + value))
        self.old = self.new + value)

当您定义按钮时,您可以简单地使用具有正确输入值的 setVal 函数,在您的情况下是 i,例如:

ttk.Button(self.buttonLF, text=str(i), style="my.TButton", command=lambda:self.setVal(i)).grid(row=0, column=i - 1)