在tkinter中无法使用画布上的滚动(布局在网格系统中)?

时间:2017-12-12 10:47:31

标签: python tkinter tkinter-canvas

当我尝试在画布上使用滚动时,我的画布消失,当我取消注释滚动行时,仅显示滚动。

from tkinter import *
from utils import editionMap, topicMap, langMap

root = Tk()

''' Top Frame to filter News by Country, Location, Language '''
Top_Frame = Frame(root)

editionMap_dropdown = StringVar()
topicMap_dropdown = StringVar()
langMap_dropdown = StringVar()
Button_Go = StringVar()

editionMap_dropdown.set("Country")
topicMap_dropdown.set("Topic")
langMap_dropdown.set("Language")
Button_GetNews = Button(Top_Frame, text="Get News")


e = OptionMenu(Top_Frame, editionMap_dropdown, *editionMap.keys())
t = OptionMenu(Top_Frame, topicMap_dropdown, *topicMap.keys())
l = OptionMenu(Top_Frame, langMap_dropdown, *langMap.keys())

e.grid(row=0, column=0)
t.grid(row=0, column=1)
l.grid(row=0, column=2)
Button_GetNews.grid(row=0, column=3)


Top_Frame.grid(row=0, column=0)


c = Canvas(root, bg="red", width=900, height=500, scrollregion=(1,0,1000,1000))
#scrollbar = Scrollbar(c)            <---Uncomment
#scrollbar.grid(row=1, column=0)     <---Uncomment

c.grid(row=1, column=0)


root.mainloop()

在画布的右侧,应该有一个Y方向的滚动条。 enter image description here

当我取消注释滚动条语句时,我得到了奇怪的输出(见截图)。

enter image description here

1 个答案:

答案 0 :(得分:2)

问题是您将画布设置为滚动条父级:scrollbar = Scrollbar(c),因此当您对滚动条进行网格化时,画布会缩小以适合滚动条。

因此,解决方案是为画布和滚动条使用相同的父级并将它们并排排列:

c = Canvas(root, bg="red", width=900, height=500, scrollregion=(1,0,1000,1000))
scrollbar = Scrollbar(root)            

c.grid(row=1, column=0)
scrollbar.grid(row=1, column=1, sticky='ns')