首页 > 解决方案 > 如何在 Tkinter 中将垂直滚动条插入到我的输出小部件?

问题描述

我正在继续开发翻译/词典应用程序,将英语单词翻译成我的母语。我想在输出小部件上插入一个垂直滚动条,以便用户可以上下滚动以查看溢出内容。请问,我该怎么做?谢谢。

下面是代码:

from tkinter import *
root=Tk()
root.geometry('250x250')
root.configure(background="#35424a")

#Entry widget object
textin = StringVar()

def clk():
    entered = ent.get().lower() #get user input and convert to lowercase
    output.delete(0.0,END)
    if len(entered) > 0:
        try:
            textin = exlist[entered]
        except:
            textin = 'Word not found'
        output.insert(0.0,textin)

#Entry field
ent=Entry(root,width=15,font=('Times 18'),textvar=textin,bg='white')
ent.place(x=30,y=15)

#Search button
but=Button(root,padx=1,pady=1,text='Translate',command=clk,bg='powder blue',font=('none 18 
bold'))
but.place(x=60,y=60)

#output field
output=Text(root,width=15,height=4,font=('Times 18'),fg="black")
output.place(x=30,y=120)

#prevent sizing of window
root.resizable(False,False) 

#Dictionary
exlist={
    "drum":"drum: (with skin) ŋgɔ̀m; (long, single-headed, skin-covered) ɨbûm ŋgɔ̀m; (with one 
end) ŋgɔ̀m ə̀tu", 
    "bag":"bag: (n) ə̀bàmɨ̀ pl. ɨ̀bàmɨ̀; (assp) (fibre bag) ə̀bàmɨ̀ tɨswé; (a type of bag made of 
animal skin) ndoŋ",
    "ant":"ant: ɨgwírɨ́ (pl. əgwirɨ); (has a big croup) ɨgwírɨ́ ndiŋ; (ant species, very 
small, attack and destroy white ants)"
    }

root.mainloop()

在此处输入图像描述

标签: pythontkinter

解决方案


您需要的是一个可滚动的文本小部件,tkinter 也内置了它。你需要使用tkinter.scrolledtext.ScrolledText. 所以只需将您的Text小部件更改为:

from tkinter import scrolledtext
# Rest of your code

output = scrolledtext.ScrolledText(root,width=15,height=4,font=('Times 18'),fg="black")
output.place(x=30,y=120)

推荐阅读