来自excel的tkinter下拉菜单

时间:2017-07-27 17:16:36

标签: python excel tkinter

我想使用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行,in       workbook = xlrd.open_workbook(filename)     在open_workbook中的文件“C:\ Python27 \ ArcGIS10.3 \ lib \ site-packages \ xlrd__init __。py”,第394行       f = open(filename,“rb”)   TypeError:强制转换为Unicode:需要字符串或缓冲区,列出找到

我甚至无法阅读用户浏览的Excel工作表。我不知道为什么会出现这个错误。如果有人能帮我,我真的很感激。我在正确的道路上吗?

由于

有效的新代码:     导入xlrd     来自Tkinter import *

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()

1 个答案:

答案 0 :(得分:0)

您可能会遇到更多错误,但在此处的代码中可能会有错误:

var notifyStatus = function(title, message, timeout) {
  chrome.notifications.create({
    type: 'progress',
    iconUrl: 'images/icon128.png',
    title: title,
    message: message || '',
    progress: 0
  }, function(id) {
    // Automatically close the notification in 4 seconds by default
    var progress = 0;
    var interval = setInterval(function() {
      if (++progress <= 100) {
        chrome.notifications.update(id, {progress: progress}, function(updated) {
          if (!updated) {
            // the notification was closed
            clearInterval(interval);
          }
        });
      } else {
        chrome.notifications.clear(id);
        clearInterval(interval);
      }
    }, (timeout || 4000) / 100);
  });
};

该对话框的结果是文件对象列表。所以你将这个文件对象列表传递给open_workbook:

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

相反,您需要做的是将您关注的文件的名称作为字符串传递给open_workbook:

workbook = xlrd.open_workbook(filename)

这是一个工作的Python3(对不起,我放弃了Python2)tkinter的例子,以正确选择文件名:

workbook = xlrd.open_workbook(filename[0].name)  # the name of the first file in the list