我最近試圖在tkinter中創建一個表格。幸運的是,我找到了一段能夠正常工作的代碼,但是,我需要爲此表添加標題。你有什麼建議,如何將其納入代碼,我發現這裏的論壇?:將標題添加到在tkinter python中創建的現有表格
import tkinter as tk
class SimpleTableInput(tk.Frame):
def __init__(self, parent, rows, columns):
tk.Frame.__init__(self, parent)
self._entry = {}
self.rows = rows
self.columns = columns
# register a command to use for validation
vcmd = (self.register(self._validate), "%P")
# create the table of widgets
for row in range(self.rows):
for column in range(self.columns):
index = (row, column)
e = tk.Entry(self, validate="key", validatecommand=vcmd)
e.grid(row=row, column=column, stick="nsew")
self._entry[index] = e
# adjust column weights so they all expand equally
for column in range(self.columns):
self.grid_columnconfigure(column, weight=1)
# designate a final, empty row to fill up any extra space
self.grid_rowconfigure(rows, weight=1)
def get(self):
'''Return a list of lists, containing the data in the table'''
result = []
for row in range(self.rows):
current_row = []
for column in range(self.columns):
index = (row, column)
current_row.append(self._entry[index].get())
result.append(current_row)
return result
def _validate(self, P):
'''Perform input validation.
Allow only an empty value, or a value that can be converted to a float
'''
if P.strip() == "":
return True
try:
f = float(P)
except ValueError:
self.bell()
return False
return True
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.table = SimpleTableInput(self, 3, 4)
self.submit = tk.Button(self, text="Submit", command=self.on_submit)
self.table.pack(side="top", fill="both", expand=True)
self.submit.pack(side="bottom")
def on_submit(self):
print(self.table.get())
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
我曾嘗試以下,但它顯然不是我所追求的:
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
names = ["header1", "header2", "header3"]
self.label = tk.Label(self, text=names)
self.table = SimpleTableInput(self, 3, 4)
self.submit = tk.Button(self, text="Submit", command=self.on_submit)
self.label.pack(side="top")
self.table.pack(side="top", fill="both", expand=True)
self.submit.pack(side="bottom")
如前所述下面,我想擁有動態顯示在表格上方的標題。任何幫助表示讚賞。謝謝
你不應該要求例子,甚至沒有顯示你的努力。你嘗試過什麼嗎?如果是這樣,你嘗試了什麼。您可以從閱讀[如何提出一個好問題](https://stackoverflow.com/help/how-to-ask)以及[最小,完整和可驗證示例](https://stackoverflow.com/幫助/ mcve) –