【发布时间】:2016-11-12 01:49:57
【问题描述】:
我是一名新的 Python 用户 (v3.5),正在尝试使用 Tkinter 和 SQLite。我在将用户输入从小部件(组合和旋转框)输入变量然后将这些变量输入 SQLite 数据库时遇到问题。我试图自己诊断问题,我相信问题是将数据从小部件获取到变量中。我已经修改了代码并在网上搜索了解决方案,但我还没有能够得到任何工作。相关代码如下。为了简洁起见,我试图删除不相关的部分。
from tkinter import *
from tkinter.ttk import *
import sqlite3
conn = sqlite3.connect("database.db")
c = conn.cursor()
class GUI:
def __init__(self):
self.root = Tk()
self.player_selection_and_score()
self.process_button()
self.create_table()
def player_selection_and_score(self):
player = StringVar
top = LabelFrame(self.root)
top.grid(column=0, row=0)
player1_selection = Combobox(top, width=10, textvariable=player, state='readonly')
player1_selection["values"] = ("Player1", "Player2", "Player3")
player1_selection.grid(column=1, row=0, sticky="w")
player1_selection.current(0)
player1_selection.bind("<<ComboboxSelected>>")
global player1_var
player1_var = player1_selection.get()
player1_score_entry = Spinbox(top, width=5, from_=0, to=10)
player1_score_entry.grid(column=4, row=0)
player1_score_entry.bind("<<SpinboxSelected>>")
global player1_score_var
player1_score_var = player1_score_entry.get()
def process_button(self):
bottom = LabelFrame(self.root)
bottom.grid(column=0, row=2)
process_button = Button(bottom, text="Process Result", command=self.data_entry)
process_button.pack()
def create_table(self):
c.execute("CREATE TABLE IF NOT EXISTS fixtures (player1 TEXT, player1_score REAL)")
def data_entry(self):
c.execute("INSERT INTO fixtures (player1, player1_score) VALUES (?, ?, ?, ?)", (player1_var, player1_score_var))
conn.commit()
player1_var = GUI()
player1_score_var = GUI()
# Start GUI
gui = GUI()
gui.root.mainloop()
conn.close()
c.close()
我很确定问题出在这些特定的代码行上:
player1_selection.bind("<<ComboboxSelected>>")
global player1_var
player1_var = player1_selection.get()
player1_score_entry.bind("<<SpinboxSelected>>")
global player1_score_var
player1_score_var = player1_score_entry.get()
谢谢!!
【问题讨论】:
-
您必须将函数绑定到
"<<ComboboxSelected>>"和"<<SpinboxSelected>>",这将使用get()来获取选定的值。现在您只在开始时获得价值。 -
并使用
self.player而不是global