我正在尝试在访问数据库中创建一个新表。
应该有两个按钮。
按钮 1(浏览):选择将在其中创建新表的 (.mdb) 文件
按钮 2(运行):创建新表
到目前为止我写的代码:
import pyodbc
from Tkinter import *
import tkFileDialog
def browse():
A = tkFileDialog.askopenfilename()
return str (A)
def run():
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=' + browse())
cur = conn.cursor()
if cur.tables(table = 'new').fetchone():
cur.execute('DROP TABLE new')
cur.execute('CREATE TABLE new( ID integer, Name string)')
conn.commit()
print (' New created')
r = Tk()
r.title ('test')
r.geometry ('200x300')
b1 = Button(r,text = 'Browse', command = browse).place (x = 10, y =10)
b2 = Button (r, text = 'run', command = run).place (x = 10, y =50)
r.mainloop()
问题是当我点击运行按钮时,它再次要求选择文件,运行按钮是否应该在以前选择的(使用浏览按钮)访问数据库中创建一个新表。如果有人能告诉我一种方法。我正在使用 Python 2.7 和 MS Access 2007。
最佳答案
我没有 pyodbc
但其余代码正在运行。
我把它放在类里面以使其更干净。我改了一些名字 - run()
至 create()
因为我用的是名字 run()
用于 mainloop()
的函数.
如果您使用 Create
按钮打开 FileDialog
仅当您之前没有选择文件时。
创建数据库程序后忘记文件名准备直接在Create
中选择另一个文件名按钮
import pyodbc
from Tkinter import *
import tkFileDialog
class Application():
def __init__(self, root):
#print 'debug: __init__()'
self.root = root
self.root.title('Database Creator')
self.root.geometry('300x300')
self.b1 = Button(self.root, text='Browse', command=self.browse)
self.b1.place(x=10, y=10)
self.b2 = Button(self.root, text='Create', command=self.create)
self.b2.place(x=10, y=50)
self.filepath = None
#----------------------
def run(self):
#print 'debug: run()'
self.root.mainloop()
#----------------------
def browse(self):
#print 'debug: browse()'
self.filepath = tkFileDialog.askopenfilename()
if self.filepath:
print 'File selected:', self.filepath
else:
print 'File not selected'
#----------------------
def create(self):
#print 'debug: create()'
if not self.filepath:
self.browse()
if self.filepath:
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=' + self.filepath)
cur = conn.cursor()
if cur.tables(table = 'new').fetchone():
cur.execute('DROP TABLE new')
cur.execute('CREATE TABLE new( ID integer, Name string)')
conn.commit()
print ' New created'
# now I will be ready to select another file
self.filepath = None
#----------------------------------------------------------------------
Application(Tk()).run()
关于python-2.7 - 使用按钮在使用 Python 的访问数据库中创建一个新表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19845956/