MessageBox未在Python GUI中显示正确的输出

2024-05-20 00:38:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用messagebox显示我的函数的输出,但是当函数显示在终端中时,它不会显示在messagebox中。messagebox是正确的还是我应该使用其他功能?我只是希望x字显示在GUI上

#Imports
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from collections import Counter
from tkinter import messagebox
import collections

# Initialize the dictionary
wordcount = {}

#open Macbeth text file
file = open('Macbeth Entire Play.txt', encoding="utf8")
a= file.read()

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__()  # Call __init__() method in parent (tk.Frame)
        
        self.label = tk.Button(self, text='How many words to Sort?', command=self.ask_count)
        self.label.grid(row=0)
        self.open_btn = tk.Button(text='Compute', command=self.ask_count)
        self.open_btn.pack(pady=(30,10))
        self.exit_btn = tk.Button(text='Exit', command=master.destroy)
        self.exit_btn.pack()

    def ask_count(self):
        
        with open('Macbeth Entire Play.txt', encoding="utf8") as file:
            self.file_text = file.read()
        for word in a.lower().split():
          word = word.replace(".","")
          word = word.replace(",","")
          word = word.replace(":","")
          word = word.replace("\"","")
          word = word.replace("!","")
          word = word.replace("“","")
          word = word.replace("‘","")
          word = word.replace("*","")
          if word not in wordcount:
              wordcount[word] = 1
          else:
              wordcount[word] += 1
        n_print = int(input("How many most common words are: "))
        print("\nThe {} most common words are as follows\n".format(n_print))
        word_counter = collections.Counter(wordcount)
        for word, count in word_counter.most_common(n_print):
          print(word, ": ", count)
        messagebox.showinfo("The top words are: " == n_print)

        # Close the file
        file.close()
        messagebox.showinfo("The top words are: ")

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Count words")
    root.geometry('400x400+900+50')
    app = Application(root)
    app.pack(expand=True, fill='both')
    root.mainloop()


Tags: textimportselftkintercountrootopenwordcount
1条回答
网友
1楼 · 发布于 2024-05-20 00:38:15

解决方案:

我不确定您试图使用==做什么,但应该是:

messagebox.showinfo(f"The top words are: {n_print}")

甚至:

messagebox.showinfo("The top words are: "+n_print)

原因:

错误在于,当您说"The top words are: " == n_print时,表示您正在将字符串与n_print进行比较,它将返回TrueFalse。因此,您要求messagebox显示False,这是一个bool,但它无法显示bool,因此您得到一个空的messagebox。见:

[In] : "The top words are: " == n_print # Assuming n_print = 'hey'
[Out]: False

只要n_print"The top words are: ",它将始终返回False

相关问题 更多 >