【问题标题】:How do I view or update a single record from a database list with a button in Python?如何使用 Python 中的按钮查看或更新数据库列表中的单个记录?
【发布时间】:2017-03-22 22:25:01
【问题描述】:

首先,我从表中选择所有记录并在我的 GUI 中列出它们。 每行旁边都有两个按钮,一个用于删除记录,一个用于在弹出屏幕中查看/更新该特定记录。我尝试了几种不同的方法,但似乎无法从我想要查看/更新的特定记录中获取信息。我尝试将文本变量添加到按钮等。

我的问题是,您如何查看和/或更新我表中所有行的列表中的特定行?

def Show_Keylog_Records(self):
            data = self.Select_Keylog_Records()
            for index, dat in enumerate(data):
                Row_ID = index
                Key_Num = dat[0]
                self.Row_ID = Frame(self.Result_Frame, bg='#333')
                Label(self.Row_ID, text=dat[0]).pack(side=LEFT, expand=YES, fill=X)
                Label(self.Row_ID, text=dat[1]).pack(side=LEFT, expand=YES, fill=X)
                Label(self.Row_ID, text=dat[2]).pack(side=LEFT, expand=YES, fill=X)
                Label(self.Row_ID, text=dat[3]).pack(side=LEFT, expand=YES, fill=X)
                Button(self.Row_ID, text='view', textvariable=Row_ID, command=self.View_Keylog_Record).pack(side=RIGHT)
                Button(self.Row_ID, text='Delete', command=self.Delete_Keylog_Record).pack(side=RIGHT, padx=5)
                self.Row_ID.pack(side=TOP, fill=X, pady=3)


def Select_Keylog_Records(self):
        c.execute("SELECT * FROM KeyLog")
        return c.fetchall() 

def View_Keylog_Record(self):
        Record = (Row_ID.get(),)
        c.execute('SELECT * FROM KeyLog WHERE index=?', Record)
        print c.fetchone()

【问题讨论】:

  • 您是在询问如何与View_Keylog_Record 通信您对哪个数据库行感兴趣?
  • 我要问的问题是:如何将我想要从 Show_Keylog_Records 更改为 View_Keylog_Record 的任何行的索引(或任何其他数据)传递给 View_Keylog_Record

标签: python tkinter sqlite


【解决方案1】:

我认为您需要将index 传递给函数。如果是这样,请像这样更改 Button 实例化:

Button(self.Row_ID, text='view', command=lambda index=index: self.View_Keylog_Record(index)).pack(side=RIGHT)

Button(self.Row_ID, text='view', command=functools.partial(self.View_Keylog_Record, index)).pack(side=RIGHT)

请注意,您必须import functools 才能使用第二个选项。

对删除按钮进行类似的更改,然后修改如下功能:

def View_Keylog_Record(self, index):
    c.execute('SELECT * FROM KeyLog WHERE index=?', (index,))
    print c.fetchone()

对 Delete_Keylog_Record 进行相应的更改,看看是否适合您。

【讨论】:

  • 不幸的是,这不起作用,我收到一个错误(c.execute('SELECT * FROM KeyLog WHERE index=?',index)sqlite3.OperationalError:靠近“index”:语法错误。当我打印 index 的输出,无论我按下哪个按钮,它总是打印 9(我有 11 行,所以它选择 9 很奇怪)
  • @SparkBarisart 对不起,我的错。您必须在 lambda 中绑定变量。还有functools.partial,我加了一个例子。
  • 哦,cursor.execute 也期望参数在一个可迭代对象中。因此,不要将index 作为第二个参数传递给c.execute,而是传递(index,)
  • 太棒了,谢谢。它有效,但只有当我将索引作为(索引,)传递时。我将阅读 functools,因为它们看起来非常方便!再次感谢!
  • 我需要做一个小改动,因为它看到我的第一行是第 0 行(当我显示它时,它会说第一行是第 1 行)def View_Keylog_Record(self, index): c.execute('SELECT * FROM KeyLog WHERE rowid=?', (index+1,)) Test = c.fetchone() print (Test)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-07
  • 1970-01-01
  • 2012-04-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多