首页 > 解决方案 > Tkinter 显示类列表文本

问题描述

我有以下代码:我正在尝试从函数 showText 获取文本以实际出现在窗口中

from tkinter import *
import wikipedia
from nltk.tokenize import sent_tokenize, word_tokenize
import time

subject = wikipedia.page("Assembly language")
#print(p.url)
#print(p.title)
plain_text = subject.content
plain_text_words = word_tokenize(plain_text)



class Window(Frame):

    def __init__(self, master= None):
        Frame.__init__(self, master)

        self.master = master

        self.init_window()

    def init_window(self):

        self.master.title('Test')

        self.pack(fill=BOTH, expand =1)

        quitButton = Button(self, text = 'Exit', command=self.client_exit)

        quitButton.place(x=500, y=300)

        menu = Menu(self.master)
        self.master.config(menu=menu)
        file = Menu(menu)

        menu.add_cascade(label='File', menu=file)
        file.add_command(label='Run', command=self.showText)
        file.add_command(label='Exit', command=self.client_exit)

        help_menu = Menu(menu)
        menu.add_cascade(label='Help', menu=help_menu)
        help_menu.add_command(label='About')


    def showText(self):
        for i in range (0, len(plain_text_words)):
            words = [i]
            time.sleep(3)
            words.pack()


    def client_exit(self):
        exit()


root = Tk()

w = 600 # width of the window
h = 370 # height of the window

# get screen width and height
ws = root.winfo_screenwidth() 
hs = root.winfo_screenheight()

# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)


root.geometry('%dx%d+%d+%d' % (w, h, x, y))

让我伤心的部分是这样的:

def showText(self):
        for i in range (0, len(plain_text_words)):
            words = [i]
            time.sleep(3)
            words.pack()

我试图让每段文本在窗口上显示为单个单词,但无论我如何尝试,我都会收到错误消息。我已经尝试过各种事情,例如转换为列表等希望有人可以提供帮助..

PS:在运行此代码之前,您需要下载 nltk 数据集

标签: python-3.xtkintertokenize

解决方案


首先,您的 pack 函数缺少括号。其次,您的 varwords是一个列表。不是 tkinter 小部件。您只能打包 tkinter 小部件。

例如,要解决它,您需要将列表添加到文本小部件。


推荐阅读