use*_*648 4 tkinter ms-access-2007 python-2.7
我正在尝试在 Access 数据库中创建一个新表。
应该有两个按钮。
按钮 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()
Run Code Online (Sandbox Code Playgroud)
问题是,当我点击运行按钮时,它再次要求选择文件,运行按钮是否应该在先前选择的(使用浏览按钮)访问数据库中创建新表。如果有人能告诉我一种方法。我正在使用 Python 2.7 和 MS access 2007。
我没有pyodbc,但其余代码正在工作。
我把它放在课堂上是为了让它更干净。我更改了一些名称 - run()tocreate()因为我使用名称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()
Run Code Online (Sandbox Code Playgroud)