2017-07-27 96 views
0

我想用tkinter來瀏覽一個excel表格,並製作一個excel表格的行的下拉菜單。 我是python的新手,不知道如何解決問題。該代碼到現在爲止是這樣的:tkinter從excel下拉菜單

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) 

這將引發一個錯誤:

Traceback (most recent call last): File "C:/Geocoding/test.py", line 14, in workbook = xlrd.open_workbook(filename) File "C:\Python27\ArcGIS10.3\lib\site-packages\xlrd__init__.py", line 394, in open_workbook f = open(filename, "rb") TypeError: coercing to Unicode: need string or buffer, list found

我甚至無法讀取用戶瀏覽Excel工作表。我不知道爲什麼這個錯誤。如果有人能幫助我,我會很感激。我在正確的道路上嗎?

感謝

,工程的新代碼: 進口從Tkinter的進口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() 
+0

askopenfiles返回一個列表。您正在將文件名分配給列表,而不是字符串。您可能需要該列表中的第一個項目 –

+0

如何讓用戶有機會打開他希望的excel文件,然後我必須讀取列名稱並將這些名稱作爲下拉菜單輸入傳遞? @VinceWest – PowerToYou

回答

0

您可以沿的方式,但在這裏你的代碼更錯誤:

filename = tkFileDialog.askopenfiles(title='Choose an excel file') 

該對話框的結果是文件對象列表。那麼,你是通過fileobjects的清單提交給這裏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 

這裏一個正在運行的Python3(對不起,我放棄了Python2)tkinter的例子來正確選擇文件名:

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 
+0

嗨@Vince我能夠做到這一點。我想從下拉列表中選擇一個值,並使用文本輸入替換它。這是我的新代碼。任何建議將不勝感激。謝謝。 – PowerToYou