Using python 3.2.2 tkinter I create a canvas with scrollbars attached but the data inside the canvas doesn't scroll when I move the scrollbars. Syntax issue or bug with tkinter?
example code:
from tkinter import *
## GUI color map ###
black = "#000000"
root = Tk()
root.minsize(100,100)
root.maxsize(500,500)
root.resizable(0,0)
topFrame = Frame(root, bd=2, relief=SUNKEN)
topFrame.pack()
xscrollbar = Scrollbar(topFrame, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)
yscrollbar = Scrollbar(topFrame, orient=VERTICAL)
yscrollbar.pack(side=RIGHT, fill=Y)
conFrame = Canvas(topFrame, bd=0, scrollregion=(0, 0, 1000, 1000),
xscrollcommand=xscrollbar.set,
yscrollcommand=yscrollbar.set)
conFrame.pack(side=TOP, fill=BOTH, expand=1)
xscrollbar.config(command=conFrame.xview)
yscrollbar.config(command=conFrame.yview)
for i in range(1,30):
function_name = 'my'+str(i)+'ItemList = StringVar()'
exec(function_name)
function_name = 'my'+str(i)+'Item = '+str(i)
exec(function_name)
function_name = 'my'+str(i)+'ItemList.set(my'+str(i)+'Item)'
exec(function_name)
function_name = 'my'+str(i)+'ItemListEntry = Entry(conFrame, width=148, foreground=black, textvariable=my'+str(i)+'ItemList)'
exec(function_name)
function_name = 'my'+str(i)+'ItemListEntry.pack(side=TOP, padx=2)'
exec(function_name)
mainloop()
解决方案
The scrollbars do scroll the canvas. The widgets you are creating (in a highly unusual fashion) are not part of the canvas, so they don't scroll. If you use the drawing commands on the canvas you'll see that the canvas items do in fact scroll.
In order for the widgets to scroll, you must embed them in the canvas with create_window. If you're trying to create a scrolling frame, the typical solution is to put all your widgets in a frame, use create_window to add that frame to the canvas, then set the scrollregion to the size of the frame (which you have to do after a screen update since the size isn't calculated until the widget is actually rendered)
On a side note, why are you using exec? It makes your code extremely hard to understand, and you get no benefit in return. Are you aware you can replace those 10 lines with something considerably more simple? For example:
var = {}
for i in range(1,30):
var[i] = StringVar()
var[i].set(i)
e = Entry(conFrame, width=148, foreground=black, textvariable=var[i])
e.pack(side=TOP, padx=2)