Skma84
Skma84

Reputation: 1

Dynamically fill the entry in tkinter and xlwings

I have an entry widget in my GUI to be dynamically filled with the cell range based on the cells have selected in the spreadsheet.

For example, if I selected A1:F30 in a sheet, it will put the range A1:F30 in the entry widget. below is the portion my entry widget in the GUI

Here is an example of selecting a range from a spreadsheet with in an inputbox that I was able to do. But I want to apply the same concept with a tkinter GUi

wb = xw.books.active
sheet = wb.sheets.active
        selectedRange = sheet.api.Application.InputBox(
            'Select your range:', Type=8)
        selectedRangeAdd = sheet.range(selectedRange.Address)

Upvotes: 0

Views: 91

Answers (1)

moken
moken

Reputation: 6620

Getting the selected range is not difficult per se
It may be how you interact tkinter with xlwings that is the question.

You could use your example code as you have above, an input dialogue and then just copy the selection in to the entry box when you click OK on the input box.
But otherwise the question of how you indicate that selection has been made may be a question.

Tkinter itself may be a limiting factor in how you can implement this however the the following code might help.
When run it will display a Excel Sheet on which you can select a range and the code will copy that selection to the 'entry' box. As you change the selected range the entry value will update at the rate on the loop.
The continually loops re-calling the update selection function so you need to determine how you would determine selection is completed.

Code Example
Uses your original tkinter example base
While the timer waits, select the required range and that range will appear in the entry box

import tkinter as tk
from time import sleep
from tkinter.font import Font
import xlwings as xw

def update_selection():
    # Delay to make a range selection
    print("Sleep for range selection")
    sleep(1)
    # Get selection range
    selectedRange = wb.app.selection.address
    print(f"Range:{selectedRange}")

    # Clear existing entry update with new
    entry.delete(0, "end")
    entry.insert(0, selectedRange)

    # Run function again after 1000 ms
    root.after(1000, update_selection)


root = tk.Tk()
wb = xw.Book()
ws = wb.sheets["Sheet1"]

root.geometry('800x640')
font1 = Font(family="Helvetica")

framelabel = tk.LabelFrame(root, text="Orthogonal Option only", bg="lightblue", font=font1, bd=2, relief="solid")
framelabel.place(x=5, y=440, height=80, width=460)

label = tk.Label(framelabel, text='selected range:', fg='black', bg="lightblue", font=10)
label.place(x=10, y=10)

entry = tk.Entry(framelabel, width=40)
entry.insert(0, "Default Text")
entry.place(x=125, y=10)

# Run selection update
update_selection()

root.mainloop()

Upvotes: 0

Related Questions