我需要在Tkinter中编写一个gui,它可以选择一个csv文件,读入它并根据csv文件第一行中的名称生成一系列按钮(之后应该使用csv文件中的数据)运行一些模拟)。
到目前为止,我已经设法编写了一个能读取csv文件的Tkinter gui,但是我对如何继续下去感到困惑:
from Tkinter import *
import tkFileDialog
import csv
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self,master)
self.grid()
self.createWidgets()
def createWidgets(self):
top = self.winfo_toplevel()
self.menuBar = Menu(top)
top["menu"] = self.menuBar
self.subMenu = Menu(self.menuBar)
self.menuBar.add_cascade(label = "File", menu = self.subMenu)
self.subMenu.add_command( label = "Read Data",command = self.readCSV)
def readCSV(self):
self.filename = tkFileDialog.askopenfilename()
f = open(self.filename,"rb")
read = csv.reader(f, delimiter = ",")
app = Application()
app.master.title("test")
app.mainloop()
非常感谢任何帮助!
答案 0 :(得分:6)
这是一种方法。我不确定你如何绑定到不同的事件处理程序,但你应该能够使用lambda方法传递按钮名称(假设它是唯一的)并以这种方式处理不同的动作。
from Tkinter import *
import tkFileDialog
import csv
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self,master)
self.grid()
self.createWidgets()
def createWidgets(self):
top = self.winfo_toplevel()
self.menuBar = Menu(top)
top["menu"] = self.menuBar
self.subMenu = Menu(self.menuBar)
self.menuBar.add_cascade(label = "File", menu = self.subMenu)
self.subMenu.add_command( label = "Read Data",command = self.readCSV)
def readCSV(self):
self.filename = tkFileDialog.askopenfilename()
f = open(self.filename,"rb")
read = csv.reader(f, delimiter = ",")
buttons = read.next()
print
for btn in buttons:
new_btn = Button(self, text=btn, command=self.btnClick)
new_btn.pack()
def btnClick(self):
pass
app = Application()
app.master.title("test")
app.mainloop()