Home > Net >  Python: Colorize a row by clicking a button
Python: Colorize a row by clicking a button

Time:07-12

I'm trying to colorize a specific row in the output when I click on the "Sortiert" button". Is there any quick way to include this into my code? Another option would be that clicking the button deletes the entire row. I haven't found a solution for tkinter for now, maybe somebody has an idea or has had a similar problem.

import pandas as pd 
import tkinter as tk
from tkinter import *

eingabe = pd.read_excel("xxx.xlsx")
eingabe.drop(eingabe.columns[[0,1,2,3,4,5,9,10,11,12,17]], axis=1, inplace = True)
eingabe["Liefer-/Fälligkeitsdatum"] = eingabe["Liefer-/Fälligkeitsdatum"].dt.strftime("%d.%m.%Y")
writer = pd.ExcelWriter("yyy.xlsx")
eingabe.to_excel(writer,"Sheet1")
writer.save()

ausgabe = tk.Tk()
ausgabe.iconbitmap("ccc.ico")
ausgabe.title("Sortierliste")
ausgabe.geometry("1900x900")

df = pd.read_excel("aaa.xlsx")
df.drop(df.columns[[0]], axis=1, inplace = True) 
n_rows = df.shape[0]
n_cols = df.shape[1]

column_names = df.columns
i=0
for j, col in enumerate(column_names):
    text = Text(ausgabe, width=16, height=1.2, bg = "#9BC2E6")
    text.config(font=("Arial", 20))
    text.grid(row=i,column=j)
    text.insert(INSERT, col)
      
for i in range(n_rows):
    for j in range(n_cols):
        text = Text(ausgabe, width=16, height=1.2)
        text.config(font=("Arial", 20))
        text.grid(row=i 1,column=j)
        text.insert(INSERT, df.loc[i][j])
        button1=tk.Button(ausgabe, text="Sortiert", bg = "green")
        button1.grid(row=i 1,column=8)
  
ausgabe.mainloop()

CodePudding user response:

You can simply use a list to store those Text boxes in a row and pass this list to a function associated to the button of the corresponding row. Then you can go through the list inside the function to change the background color of those Text boxes:

def change_color(widgets, color):
    for widget in widgets:
        widget.config(bg=color)

for i in range(n_rows):
    widgets = []  # list to store the text boxes in this row
    for j in range(n_cols):
        text = Text(ausgabe, width=16, height=1.2)
        text.config(font=("Arial", 20))
        text.grid(row=i 1, column=j)
        text.insert(INSERT, df.loc[i][j])
        widgets.append(text) # add the text box to the list
    button1 = tk.Button(ausgabe, text="Sortiert", bg="green", command=lambda w=widgets: change_color(w, "green"))
    button1.grid(row=i 1, column=n_cols)

Note that I have moved the creation of the Sortiert button outside the inner for loop.

  • Related