[英]How to change a the colors of specific rows and columns in a table?
I've been working on a project where I intend to use tkinter to create a window with a table containing all my results.我一直在从事一个项目,我打算使用 tkinter 创建一个 window ,其中包含一个包含我所有结果的表。 To do this, I have the following code.
为此,我有以下代码。 The code runs just fine, but the problem is I need to attribute some colors to specific rows and columns while with the current code it all ends up in blue.
代码运行得很好,但问题是我需要将一些 colors 归因于特定的行和列,而当前的代码最终都是蓝色的。 Let's say for example I need to have the first 3 rows of column 1 in red.
例如,假设我需要将第 1 列的前 3 行设为红色。 Any ideas about howthis can be done?
关于如何做到这一点的任何想法? Thank you very much for any help.
非常感谢您的帮助。
# Create a table for tkinter
class Table:
def __init__(self, root):
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
self.e = Entry(root, width=20, fg='blue',
font=('Arial', 16, 'bold'))
self.e.grid(row=i, column=j)
self.e.insert(END, lst[i][j])
# take the data
lst = [(1, 'Raj', 'Mumbai', 19),
(2, 'Aaryan', 'Pune', 18),
(3, 'Vaishnavi', 'Mumbai', 20),
(4, 'Rachna', 'Mumbai', 21),
(5, 'Shubham', 'Delhi', 21)]
# find total number of rows and columns in list for tkinter
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
root.title("Results")
t = Table(root)
root.mainloop()
Try this:尝试这个:
import tkinter as tk
# It's better to inherit from `tkinter.Frame` so we can use the table
# as a normal tkinter widget
class Table(tk.Frame):
def __init__(self, master=None, data=[], **kwargs):
super().__init__(master, **kwargs)
self.table = []
for i, _list in enumerate(data):
row = []
for j, entry_data in enumerate(_list):
entry = tk.Entry(self, width=20, fg="blue",
font=("Arial", 16, "bold"))
entry.grid(row=i, column=j)
entry.insert("end", entry_data)
row.append(entry)
self.table.append(row)
def column_config(self, column_number, **kwargs):
for row in self.table:
# Call `<tkinter.Entry>.config(**kwargs)`
row[column_number].config(**kwargs)
# take the data
data = [(1, "Raj", "Mumbai", 19),
(2, "Aaryan", "Pune", 18),
(3, "Vaishnavi", "Mumbai", 20),
(4, "Rachna", "Mumbai", 21),
(5, "Shubham", "Delhi", 21)]
# create root window
root = tk.Tk()
root.title("Results")
table = Table(root, data)
table.pack()
# Column 3 is the last one
table.column_config(3, fg="red", bg="cyan")
root.mainloop()
I made a few changes:我做了一些改变:
Table
act as any other tkinter
widget by inheriting from tkinter.Frame
tkinter.Frame
继承使Table
充当任何其他tkinter
小部件column_config
methodcolumn_config
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.