0
from Tkinter import *
import MySQLdb

def tran() :
 first= Tk()

 label1 = Label(first ,text="From")
 label1.pack()

 box1=Entry(first )
 box1.pack()

 label2=Label(first ,text="To")
 label2.pack()

 box2=Entry(first )
 box2.pack()

 label3=Label(first ,text="Amt")
 label3.pack()

 box3=Entry(first )
 box3.pack()

 Button1 = Button(first , text="Next", command=func3).pack() 


def func3() :
 conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "natty", db = "dbms")
 cursor=conn.cursor()

 From=int(box1.get().strip())
 To=int(box2.get().strip())
 Amt=int(box3.get().strip())

 cursor.execute ("select bal from account where acc="+str(From)+"")

 a=cursor.fetchone()
 fromval=int(a[0])

 cursor.execute ("select bal from account where acc="+str(To)+"")

 b=cursor.fetchone()
 toval=int(b[0])

 fromval=fromval-Amt
 toval=toval+Amt

 cursor.execute("update account set bal="+str(fromval)+" where acc="+str(From)+"")
 cursor.execute("update account set bal="+str(toval)+" where acc="+str(To)+"")

 cursor.close ()
 conn.close ()

master = Tk()
Button3 = Button(master, text="Transaction", command=tran).pack()
mainloop()

截屏

下一步按钮不起作用。当我单击“下一步”按钮时,我收到以下错误:

func3 中的文件“disp.py”,第 24 行
    从 = int (box1.get().strip())
NameError:未定义全局名称“box1”

我是否必须将按钮放在 func3 内

4

2 回答 2

3

将您的代码更改为:

from Tkinter import *

import MySQLdb

class App:

    def __init__(self, master):
        Button3 = Button(master, text="Transaction", command=self.tran).pack()

    def tran(self) :

        first = Tk()

        label1 = Label(first ,text="From")

        label1.pack()

        self.box1=Entry(first )

        self.box1.pack()

        label2=Label(first ,text="To")

        label2.pack()

        self.box2=Entry(first )

        self.box2.pack()


        label3=Label(first ,text="Amt")

        label3.pack()

        self.box3=Entry(first )

        self.box3.pack()

        Button1 = Button(first , text="Next", command=self.func3).pack() 


    def func3(self) :

        conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "natty", db = "dbms")

        cursor=conn.cursor()

        From=int(self.box1.get().strip())

        To=int(self.box2.get().strip())

        Amt=int(self.box3.get().strip())
        cursor.execute ("select bal from account where acc="+str(From)+"")

        a=cursor.fetchone()

        fromval=int(a[0])

        cursor.execute ("select bal from account where acc="+str(To)+"")

        b=cursor.fetchone()

        toval=int(b[0])

        fromval=fromval-Amt

        toval=toval+Amt

        cursor.execute("update account set bal="+str(fromval)+" where acc="+str(From)+"")

        cursor.execute("update account set bal="+str(toval)+" where acc="+str(To)+"")

        cursor.close ()

        conn.close ()

master = Tk()

app = App(master)

master.mainloop()

我认为这应该有效。

于 2012-04-25T13:33:37.603 回答
0

box1 是在 tran() 函数内部定义的,因此(如错误消息所述)不是全局定义的。

于 2012-04-25T13:19:50.960 回答