tkinter中text文本与scroll滚动条控件(五)

text与scroll控件

复制代码
 1 import tkinter
 2 
 3 wuya = tkinter.Tk()
 4 wuya.title("wuya")
 5 wuya.geometry("300x200+10+20")
 6 
 7 # 创建文本框text,设置宽度100,high不是高度,是文本显示的行数设置为3行
 8 text = tkinter.Text(wuya, width='30', height='3')
 9 text.pack()
10 
11 # 设置文本框内容
12 txt = 'China urges the U.S. to abide by the one-China principle and the principles of the three Sino-U.S.' 
13       ' Joint Communiques, and stop all forms of military contact with Taiwan including arms sales, Wu said.'
14 # 将文本内容插入文本框
15 text.insert('insert',txt)
16 
17 
18 
19 wuya.mainloop()
复制代码

结果为:

可以观察到内容不太多,显示不下,加个滚动条使显示,可以上下滚动:

复制代码
 1 import tkinter
 2 
 3 wuya = tkinter.Tk()
 4 wuya.title("wuya")
 5 wuya.geometry("300x50+10+20")
 6 
 7 # 创建滚动条
 8 scroll = tkinter.Scrollbar()
 9 # 创建文本框text,设置宽度100,high不是高度,是文本显示的行数设置为3行
10 text = tkinter.Text(wuya)
11 # 将滚动条填充
12 scroll.pack(side=tkinter.RIGHT,fill=tkinter.Y) # side是滚动条放置的位置,上下左右。fill是将滚动条沿着y轴填充
13 text.pack(side=tkinter.LEFT,fill=tkinter.Y) # 将文本框填充进wuya窗口的左侧,
14 # 将滚动条与文本框关联
15 scroll.config(command=text.yview) # 将文本框关联到滚动条上,滚动条滑动,文本框跟随滑动
16 text.config(yscrollcommand=scroll.set) # 将滚动条关联到文本框
17 
18 # 设置文本框内容
19 txt = 'China urges the U.S. to abide by the one-China principle and the principles of the three Sino-U.S.' 
20       ' Joint Communiques, and stop all forms of military contact with Taiwan including arms sales, Wu said.'
21 # 将文本内容插入文本框
22 text.insert('insert',txt)
23 
24 
25 
26 wuya.mainloop()
复制代码

结果如下:

原文地址:https://www.cnblogs.com/anita-harbour/p/9315438.html