Home > Software design >  Python tk scrollbar on listbox not working in windows 10
Python tk scrollbar on listbox not working in windows 10

Time:01-28

I have python3 tk code that seems to work okay in linux (ubuntu) but bizarely does not work in windows 10. The scrollbar on the listbox doesn't scroll in windows ...

import tkinter as tk

root = tk.Tk()
root.title("My MHT")
root.geometry("500x500")

# create all of the main containers
toppest_frame = tk.Frame(root, bg='thistle3', width=500, height=25, pady=3)
top_frame = tk.Frame(root, bg='cyan', width=500, height=250, pady=3)
bottom_frame = tk.Frame(root, bg='lavender', width=500, height=250, pady=3)

# layout all of the main containers
root.grid_rowconfigure(0, weight=1)
root.grid_rowconfigure(1, weight=1)
root.grid_rowconfigure(2, weight=1)
root.grid_columnconfigure(0, weight=1)

toppest_frame.grid(row=0, sticky="nesw")
top_frame.grid(row=1, sticky="nesw")
bottom_frame.grid(row=2, sticky="nesw")

#create scrollbar
sb1 = tk.Scrollbar(top_frame,orient="vertical")
sb1.grid(row=0,column=5)

sb2 = tk.Scrollbar(top_frame,orient="horizontal")
sb2.grid(row=1,columnspan=5)

# create the widgets for the top frame
listBox = tk.Listbox(top_frame, relief="sunken",bd=2,selectmode="single")

# layout the widgets in the top frame
top_frame.grid_rowconfigure(0,weight=1)
top_frame.grid_columnconfigure(0,weight=1)
listBox.grid(row=0,sticky="nesw",columnspan=5)

#populate listbox
listBox.delete(0, "end")
for values in range(100):
    listBox.insert("end", values)

#attach scrollbar to listbox
listBox.configure(xscrollcommand=sb1.set)
sb1.configure(command=listBox.yview)

listBox.configure(yscrollcommand=sb2.set)
sb2.configure(command=listBox.xview)

root.mainloop()

Am I doing something wrong?

Many thanks.

CodePudding user response:

I do not know how you got this to work in Linux with tkinter, but anyway you are setting the scrollbar for the wrong axis.

listBox.configure(yscrollcommand=sb1.set) # Was xscrollcommand
sb1.configure(command=listBox.yview)

listBox.configure(xscrollcommand=sb2.set) # Was yscrollcommand
sb2.configure(command=listBox.xview)

Then you also need the scrollbar to expand along its field, with grid you use sticky, if you were using pack then an appropriate combination of fill and side, sometimes expand too:

sb1 = tk.Scrollbar(top_frame,orient="vertical")
sb1.grid(row=0,column=5,sticky='ns') # Expand north to south

sb2 = tk.Scrollbar(top_frame,orient="horizontal")
sb2.grid(row=1,columnspan=5,sticky='ew') # Expand east to west

I also hope you have a good reason to use columnspan=5 and did not get it confused with column. Ideally in this situation, it should be column 1 and 0 for sb1 and sb2 respectively.

  •  Tags:  
  • Related