[英]tkinter drop down menu from excel
我想使用tkinter
瀏覽一個Excel工作表,並對該Excel工作表的行進行下拉菜單。 我是python
新手,不知道如何解決它。 到目前為止的代碼如下所示:
import xlrd
import os
from subprocess import call
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfiles(title='Choose an excel file')
print(filename)
print type(filename)
#file = str(filename)
file = [filetypes for filetypes in filename if ".xlsx" in filetypes]
workbook = xlrd.open_workbook(filename)
for file in filename:
sheet = workbook.sheet_by_index(0)
print(sheet)
for value in sheet.row_values(0):
print(value)
這將引發錯誤:
追溯(最近一次通話):工作簿中的文件“ C:/Geocoding/test.py”,第14行= xlrd.open_workbook(文件名)文件“ C:\\ Python27 \\ ArcGIS10.3 \\ lib \\ site-packages \\ xlrd__init__ .py“,第394行,在open_workbook中,f = open(filename,” rb“)TypeError:強制轉換為Unicode:需要字符串或緩沖區,找到列表
我什至無法閱讀用戶瀏覽的Excel工作表。 我不知道為什么這個錯誤。 如果有人可以幫助我,我將不勝感激。 我在正確的道路上嗎?
謝謝
起作用的新代碼:從Tkinter import *導入xlrd
import Tkinter,tkFileDialog
root = Tkinter.Tk()
root.withdraw()
filename = tkFileDialog.askopenfilename(title='Choose an excel file')
print(filename)
print type(filename)
#file = str(filename)
file = [filetypes for filetypes in filename if ".xlsx" in filetypes]
workbook = xlrd.open_workbook(filename)
#for file in filename:
sheet = workbook.sheet_by_index(0)
print(sheet)
for value in sheet.row_values(0):
print(value)
print(type(value))
master = Tk()
variable=StringVar(master)
#variable=sheet.row_values(0)[0]
variable.set(sheet.row_values(0)[0])
#for var in value:
# variable = StringVar(master)
# variable.set(value) # default value
#w = OptionMenu(master, variable, value)
w = apply(OptionMenu, (master, variable) + tuple(sheet.row_values(0)))
w.pack()
mainloop()
您可能會在此過程中遇到更多錯誤,但在此處的代碼中:
filename = tkFileDialog.askopenfiles(title='Choose an excel file')
該對話框的結果是文件對象列表。 因此,您要將文件對象列表傳遞給open_workbook:
workbook = xlrd.open_workbook(filename)
相反,您需要做的是將您關心的文件名作為字符串傳遞給open_workbook:
workbook = xlrd.open_workbook(filename[0].name) # the name of the first file in the list
這是tkinter正確選擇文件名的有效Python3示例(對不起,我放棄了Python2):
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
filename = filedialog.askopenfiles(title='Choose an excel file')
print(filename) # filename is a list of file objects
print(filename[0].name) # this is the name of the first selected in the dialog that you can pass to xlrd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.