0

我在尝试使用类在 tkinter 中使用组合框创建简单计算时遇到问题。对我来说,这很棘手,很难理解!希望你能帮我解决这个问题。

提前致谢。

赫克托。

这是我的代码:

from Tkinter import *
import ttk
from ttk import Combobox

root= Tk()
root.minsize(550,450)
root.maxsize(560,460)
root.title('myAPP')

class Calculation:
    def __init__(self, parent):
        self.parent = parent
        self.Value1()
        self.Value2()
        self.Result()

        Label(self.parent,text='Num 1').grid(column=2, row=5,sticky=W,pady=3)
        Label(self.parent,text='Num 2').grid(column=2, row=6,sticky=W,pady=3)
        Label(self.parent,text='result').grid(column=9,row=9,sticky=W,pady=3)

        self.msg =Label(self.parent,text='Sum of 2 number')
        self.msg.grid(row=3,column=1,columnspan=2)

        self.Button =Button(text='Calculate',width=8,command =self.Result)
        self.Button.grid(row=9,column=2,padx=2,pady=3)

    def Value1(self):
        self.field1 = StringVar()
        self.field1 = ttk.Combobox(self.parent, textvariable= self.field1)
        self.field1['values'] = ('5', '6', '7')
        self.field1.grid(column=3, row=5)

    def Value2(self):
        self.field2 = StringVar()
        self.field2 = ttk.Combobox(self.parent, textvariable=self.field2)
        self.field2['values'] = ('1', '2', '3')
        self.field2.grid(column=3, row=6)

    def Result(self):
        self.entry = StringVar()
        self.entry = ttk.Entry(self.parent, textvariable = self.entry)
        #self.entry = field1 + field2 ----> Here is the problem I have!
        self.entry.grid(column=3, row=9)

#End Code
if __name__ == '__main__':
    app = Calculation (root) 
    root.mainloop()
4

3 回答 3

1
from Tkinter import *
import ttk

root= Tk()
root.minsize(550,450)
root.maxsize(560,460)
root.title('myAPP')

class Calculation:
    def __init__(self, parent):
        self.parent = parent
        self.Value1()
        self.Value2()
        self.Result()

        Label(self.parent,text='Num 1').grid(column=2, row=5, sticky=W, pady=3)
        Label(self.parent,text='Num 2').grid(column=2, row=6, sticky=W, pady=3)
        Label(self.parent,text='result').grid(column=9,row=9, sticky=W, pady=3)

        self.msg = Label(self.parent,text='Sum of 2 number')
        self.msg.grid(row=3,column=1,columnspan=2)

    def Value1(self):
        self.field1_value = StringVar()
        self.field1_value.trace('w', self.Calc)
        self.field1 = ttk.Combobox(self.parent, textvariable=self.field1_value)
        self.field1['values'] = ('5', '6', '7')
        self.field1.grid(column=3, row=5)

    def Value2(self):
        self.field2_value = StringVar()
        self.field2_value.trace('w', self.Calc)
        self.field2 = ttk.Combobox(self.parent, textvariable=self.field2_value)
        self.field2['values'] = ('1', '2', '3')
        self.field2.grid(column=3, row=6)

    def Result(self):
        self.entry = StringVar()
        self.entry = ttk.Entry(self.parent, textvariable=self.entry)
        self.entry.grid(column=3, row=9)

    def Calc(self, *args):
        self.entry.delete(0, END)
        try:
            value = int(self.field1.get()) + int(self.field2.get())
        except ValueError:
            self.entry.insert(0, 'Input numbers.')
        else:
            self.entry.insert(0, str(value))

if __name__ == '__main__':
    app = Calculation(root) 
    root.mainloop()

我将 Result 方法拆分为两种方法:Result、Calc

  • 结果():制作一个将显示总和的条目小部件。这仅被调用一次(当创建计算对象时。)
  • Calc():计算总和并显示。单击“计算”按钮时会调用此方法。

编辑 - 删除按钮。- 将文本变量(field1_value、field2_value)附加到组合框。- 当变量更改(= 组合框值更改)时,使用 StringVar.trace 调用 Calc()

于 2013-06-07T16:53:48.333 回答
0

I think this does what you're trying to accomplish:

from Tkinter import *
import ttk
from ttk import Combobox

class Calculation(object):
    def __init__(self, parent):
        self.parent = parent
        self.create_widgets()

    def create_widgets(self):
        self.msg = Label(self.parent, text='Sum of 2 numbers:')
        self.msg.grid(row=3, column=1, columnspan=2)

        Label(self.parent, text='Num 1').grid(row=5, column=2, sticky=W, pady=3)
        self.number1 = IntVar()
        self.widget1 = ttk.Combobox(self.parent, textvariable=self.number1)
        self.widget1['values'] = '5', '6', '7'
        self.widget1.grid(row=5, column=3)

        Label(self.parent, text='Num 2').grid(row=6, column=2, sticky=W, pady=3)
        self.number2 = IntVar()
        self.widget2 = ttk.Combobox(self.parent, textvariable=self.number2)
        self.widget2['values'] = '1', '2', '3'
        self.widget2.grid(row=6, column=3)

        self.button = Button(text='Calculate', command=self.calculate_result)
        self.button.grid(row=9, column=2, padx=2, pady=3)
        self.result = StringVar()
        self.widget3 = ttk.Entry(self.parent, textvariable=self.result)
        self.widget3.grid(row=9, column=3)
        Label(self.parent, text='result').grid(row=9, column=9, sticky=W, pady=3)

    def calculate_result(self):
        self.result.set(self.number1.get() + self.number2.get())

if __name__ == '__main__':
    root= Tk()
    root.minsize(550, 450)
    root.maxsize(560, 460)
    root.title('myAPP')
    app = Calculation(root)
    root.mainloop()

I also highly recommend that you read and start following the recommendations in PEP 8 -- Style Guide for Python Code especially in regards to naming of entities in your code. In addition, I think if you were more consistent in the ordering of keyword arguments and spacing of them that it would be a great improvement in your coding style. It's good to establish doing things properly early on, so that they'll become habits you won't even have to think about doing later.

于 2013-06-07T18:44:12.520 回答
0

您的界面代码将分为两部分:将在初始化时运行的小部件的描述和应用程序的动态行为。

您已经有了 GUI 的描述。对于该行为,command在按钮上定义 a 是一个好的开始,但是此代码看起来不像您的Result方法(它创建一个条目)。在此方法(称为回调)中,您将操纵您已经存在的对象:读取组合框的值,设置条目的新值...例如(改编自falsetru 的答案

self.button  = Button(... , command=self.calcultate)

def calculate(self):
    self.entry.delete(0, END)
    value = int(self.field1.get()) + int(self.field2.get())
    self.entry.insert(0, str(value))

还有其他方法可以定义应用程序的行为,例如,您可以将变量与具有值(条目、组合框...)的小部件相关联,并在修改此变量后立即触发操作:

self.number1 = IntVar()
self.field1 = ttk.Combobox(self.parent, textvariable=self.number1)


self.number1.trace("w", self.calculate) 

(请注意,我选择使用 IntVar 以避免需要int()解析先前的解决方案)。

为避免用户在组合框中输入非数字时出错,您可以在读取值时捕获异常,或使用验证命令禁止非数字输入。

def ensure_digit(candidate_string):
    return candidate_string.isdigit()

self.field1.config(validate = "key", validatecommand =(self.field1.register(ensure_digit),  "%S"))
于 2013-06-07T19:31:26.853 回答