>我用tkinter构建了一个GUI。有两个按钮,一个用于加载 excel 工作表并解析所有单元格并打印其值。另外,我有一系列带有标题的空文本框。我试图实现的是将解析的 excel 单元格分别加载到一个变量上,然后用单元格值(即有问题的变量(填充空文本框。任何指示将不胜感激。这是我到目前为止的代码:
#!/usr/bin/python3
from tkinter import filedialog
from tkinter import *
import openpyxl
from openpyxl import load_workbook
#Define Window Geometry
main = Tk()
main.geometry("1024x768")
main.title("Window Title")
#Define Empty Cells to be Filled in by Excel File & Calculation
def OpenDataInputSpreadsheetCallBack():
main.iconify()
file_path = filedialog.askopenfilename(initialdir = "file_path_goes_here",title = "Choose Input Spreadsheet",filetypes = (("Excel 2010 files","*.xlsx"),("Excel 2003 Files","*.xls")))
wb = load_workbook(filename = file_path, read_only=True)
ws = wb.active
for row in ws.iter_rows():
for cell in row:
if (cell.value==None):
pass
else:
print(cell.value)
#
#
#Function to display empty rows and columns
#
height = 5
width = 6
for x in range(1,height+1): #Rows
for y in range(width): #Columns
b = Entry(main, text='')
b.grid(row=x, column=y)
#
# Define Buttons
b1 = Button(main, text = "Open Data Input Spreadsheet", command = OpenDataInputSpreadsheetCallBack)
b1.place(x = 1,y = 120)
b2 = Button(main, text='Quit', command=main.destroy)
b2.place(x = 1,y = 150)
##
##
### Initialize Column Headers
Label(main, text="Header1").grid(row=0, column=0, sticky=W)
Label(main, text="Header2").grid(row=0, column=1, sticky=W)
Label(main, text="Header3").grid(row=0, column=2, sticky=W)
Label(main, text="Header4").grid(row=0, column=3, sticky=W)
Label(main, text="Header5").grid(row=0, column=4, sticky=W)
Label(main, text="Header6").grid(row=0, column=5, sticky=W)
###
# Define a function to close the window.
def quit(event=None):
main.destroy()
# Cause pressing <Esc> to close the window.
main.bind('<Escape>', quit)
#
#
main.mainloop()
问题:我试图实现的是将解析的 excel 单元格分别加载到一个变量上,然后用单元格值填充空文本框
您不必使用 variable
,您可以将cell values
直接传递到文本框。
例如:
class Textbox(object):
text = None
series_of_textboxes = [Textbox(),Textbox(),Textbox(),Textbox()]
# start reading from row 2
for i, row in enumerate( ws.iter_rows(min_row=2) ):
series_of_textboxes[i].text = ' '.join(cell.value for cell in row)
print( series_of_textboxes[0].text )
输出:
德甲 27.08.16 汉堡 英戈尔施塔特
用 Python 测试 3.4.2 - openpyxl:2.4.1
如果这对您有用,请返回并标记您的问题已回答或评论为什么不。