繁体   English   中英

如何将滚动条附加到 tkinter 上的文本框?

[英]How can i attach my scroll bar to my text box on tkinter?

我试图为我的文本框使用垂直滚动条,但遇到了一些问题:

  1. 我无法让滚动条直接触摸文本框的右侧(因此它们已连接)
  2. 滚动条似乎不会影响我的文本框

我查看了一些解决方案,但似乎都没有。 这是我的代码:

from tkinter import *

writtenQ = Tk()
writtenQ.title("Written Response Question")
writtenQ.resizable(0,0)

header = LabelFrame(writtenQ, bg="white")
content = LabelFrame(writtenQ, bg="white")

header.columnconfigure(0, weight=1) # Forces column to expand to fill all available space
homeButton=Button(content,width=50,height=50)
try:
    homeIcon=PhotoImage(file="yes.png")
    homeButton.config(image=homeIcon)
    homeButton.image = homeIcon
except TclError:
    print("Home")
homeButton.grid(row=1, sticky="w", padx=15, pady=2)

#the image of the question will be put here
titleHeader = Label(content, text="Question Image here",pady=15, padx=20, bg="white", font=("Ariel",20, "bold"), anchor="w", relief="solid", borderwidth=1)
titleHeader.grid(row=2, column=0, columnspan=3, padx=15, pady=5, ipadx=370, ipady=150)

#this will allow the user to input their written response
answerInput = Text(content, width = 60, borderwidth=5, font=("HelvLight", 18)) 
answerInput.grid(row=3, column=0, ipady = 10, sticky="w", padx=(20,0), pady=20)
answerScrollBar= Scrollbar(content, command=answerInput.yview, orient="vertical")
answerScrollBar.grid(row=3, column=1, sticky="w")

submitButton = Button(content, borderwidth=1, font=("Ariel", 22), text="Submit", bg="#12a8e3", fg="black", activebackground="#12a8e3", relief="solid")
submitButton.grid(row=3, column=2, ipady=50, ipadx=70, sticky="nw", pady=20)

header.grid(row=0, sticky='NSEW')
content.grid(row=1, sticky='NSEW')

您是否尝试过这里的解决方案?

假设文本小部件称为文本。 您的代码可能是(不包括窗口的设置):

import tkinter
import tkinter.ttk as ttk
scrollb = ttk.Scrollbar(self, command=text.yview)
scrollb.grid(row=0, column=1, sticky='nsew')
text['yscrollcommand'] = scrollb.set

我已经从Honest Abe的回答中挑选出我认为对你有用的东西。 希望它有所帮助。 请记住在使用代码之前设置您的 window...

配置滚动条需要双向连接:滚动条需要调用widget的yviewxview方法,widget需要调用滚动条的set方法。

通常,这分三个步骤完成,如下例所示:

answerInput = Text(...)
answerScrollBar= Scrollbar(..., command=answerInput.yview)
answerInput.configure(yscrollcommand=answerScrollBar.set)

你忘记了最后一步。


与实际运行的滚动条无关,您将希望能够看到滚动条。 您需要为滚动条使用sticky="ns" ,以便它在Y 方向上伸展。 否则它将只有几十个像素高。

answerScrollBar.grid(row=3, column=1, sticky="ns")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM