在这种情况下,需要将scrolledText设置为只读,因此用户只能通过按钮向其添加值,如下所示:

from tkinter import *
from tkinter import scrolledtext

startingWin = Tk()

myEntry = Entry(startingWin, font=("Courier",25, "bold"), width=15)
myScrolledText = scrolledtext.ScrolledText(startingWin, font=("Courier",25, "bold"),width=15, height=3, state='disabled')

def addEntryContentToScrolledText(entry, scrolledText):
    entryValue = str((entry.get()).strip())
    scrolledtext.config(state='normal')
    if entryValue not in str(scrolledText.get('1.0', 'end-1c')) and entryValue != "":
        scrolledText.insert(INSERT, (entryValue + "\n"))
    scrolledtext.config(state='disabled')

myAddButton = Button(startingWin, text="Add")
myAddButton.config(command=lambda: addEntryContentToScrolledText(myEntry, myScrolledText))

myScrolledText.grid(row=0, column=1)
myEntry.grid(row=0, column=0)
myAddButton.grid(row=1, column=0)
startingWin.mainloop()


但是,出现此错误AttributeError: module 'tkinter.scrolledtext' has no attribute 'config'

如何重新配置​​scrolledText?

最佳答案

您的小部件名称是myScrolledText,而不是scrolledtext :( scrolledtext是导入的模块名称)

from tkinter import *
from tkinter import scrolledtext


startingWin = Tk()

myEntry = Entry(startingWin, font=("Courier",25, "bold"), width=15)
myScrolledText = scrolledtext.ScrolledText(startingWin, font=("Courier",25, "bold"),width=15, height=3, state='disabled')

def addEntryContentToScrolledText(entry, textwidget):
    entryValue = str((entry.get()).strip())
    textwidget.configure(state='normal')
    if entryValue not in str(textwidget.get('1.0', 'end-1c')) and entryValue != "":
        textwidget.insert(INSERT, (entryValue + "\n"))
    textwidget.configure(state='disabled')


myAddButton = Button(startingWin, text="Add", command=lambda: addEntryContentToScrolledText(myEntry, myScrolledText))

myScrolledText.grid(row=0, column=1)
myEntry.grid(row=0, column=0)
myAddButton.grid(row=1, column=0)
startingWin.mainloop()

关于python - 如何配置Tkinter scrolledtext,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51759683/

10-10 03:59