Home > Software engineering >  Python tkinter widget tksheet problem with printing cell values
Python tkinter widget tksheet problem with printing cell values

Time:12-28

I'm trying to print the value from a selected cell into the sheet widget, but every time it returns 'No cell is selected'. Here is the code snippet:

import tkinter as tk
import sqlite3
import tksheet

top = tk.Tk()

sheet = tksheet.Sheet(top, width=943)

sheet.place(relx = 0.0, rely = 0.1)

conn = sqlite3.connect('dbz/data.db')
c = conn.cursor()
c.execute('''SELECT * FROM table''')
rows = c.fetchall()

data = rows

sheet.set_sheet_data(data = data)

sheet.enable_bindings(("single_select",
                       "column_select",
                       "row_select",
                       "column_width_resize",
                       "row_height_resize",
                       "arrowkeys",
                       "right_click_popup_menu",
                       "rc_select",
                       "rc_insert_row",
                       "rc_delete_row",
                       "copy",
                       "cut",
                       "paste",
                       "delete",
                       "undo",
                       "edit_cell",
                       "drag_select"))

selected_cells = sheet.get_selected_cells()

def pr(e):
    # If there is a selected cell, get the data for it
    if selected_cells:
        #row, column = selected_cells[0]
        value = sheet.get_cell_data(r=row, c=column, return_copy=True)
        print(value)
    else:
        print("No cell is selected")

sheet.bind("<1>", pr)
#sheet.bind("cell_update", update_record)
top.mainloop()

I tried most of the things I found in the documentation: https://github.com/ragardner/tksheet/wiki

get_sheet_data(return_copy = False, get_header = False, get_index = False)
get_cell_data(r, c, return_copy = True)

, etc. But nothing seems to work. I would very much appreciate any help. Thanks in advance.

CodePudding user response:

this should work like you want.

Firstly, you need to identify which row and column was clicked. Really useful to get this information with sheet.identify_row and sheet.identify_column.

With sheet.cell_selected we can be sure that cell was actually clicked.

At the end, I've changed sheet.bind("<1>", pr) to sheet.bind("<ButtonPress-1>", pr).

def pr(event):
    row = sheet.identify_row(event, exclude_index = False, allow_end = True)
    column = sheet.identify_column(event, exclude_header = False, allow_end = True)
    # If there is a selected cell, get the data for it
    if sheet.cell_selected(row, column):
        value = sheet.get_cell_data(row, column, return_copy = True)
        print(value)
    else:
        print("No cell is selected")

sheet.bind("<ButtonPress-1>", pr)
  • Related