我用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()
答案 0 :(得分:1)
问题:我想要实现的是将解析后的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 )
输出:
Bundesliga 27.08.16 Hamburg Ingolstadt
使用Python测试:3.4.2 - openpyxl:2.4.1
如果这对您有用,请回来并将您的问题标记为已回答,或者为什么不对其进行评论。