在tkinter框架中放置直方图

1 投票
1 回答
3827 浏览
提问于 2025-04-18 10:27

我正在尝试把两个Tkinter程序合在一起。第一个程序是从用户输入的网址中获取每个字母出现的次数,并在一个文本框中显示每个字母的计数。第二个程序是使用turtle模块来创建一个直方图。我想把每个字母的出现次数显示为一个直方图,并在x轴上标注字母。

这是我为这两个程序写的代码:

from tkinter import *
import tkinter.messagebox
import urllib.request
import turtle

counts = 0

def main():
    analyzeFile(url.get())
    list = [counts]
    drawHistogram(list)

def analyzeFile(url):
    try:
        infile = urllib.request.urlopen(url)
        s = str(infile.read().decode()) # Read the content as string from the URL

        counts = countLetters(s.lower())

        infile.close() # Close file
    except ValueError:
        tkinter.messagebox.showwarning("Analyze URL", 
                                    "URL " + url + " does not exist")

def countLetters(s): 
    counts = 26 * [0] # Create and initialize counts
    for ch in s:
        if ch.isalpha():
            counts[ord(ch) - ord('a')] += 1
    return counts

def drawHistogram(list):
    WIDTH = 400
    HEIGHT = 300

    raw_turtle.penup()
    raw_turtle.goto(-WIDTH / 2, -HEIGHT / 2)
    raw_turtle.pendown()
    raw_turtle.forward(WIDTH)

    widthOfBar = WIDTH / len(list)

    for i in range(len(list)):
        height = list[i] * HEIGHT / max(list)
        drawABar(-WIDTH / 2 + i * widthOfBar,
            -HEIGHT / 2, widthOfBar, height)

    raw_turtle.hideturtle()

def drawABar(i, j, widthOfBar, height):
    raw_turtle.penup()
    raw_turtle.goto(i, j)
    raw_turtle.setheading(90)
    raw_turtle.pendown()

    raw_turtle.forward(height)
    raw_turtle.right(90)
    raw_turtle.forward(widthOfBar)
    raw_turtle.right(90)
    raw_turtle.forward(height)

window = Tk()
window.title("Occurrence of Letters in a Histogram from URL")

frame1 = Frame(window)
frame1.pack()

scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)

canvas = tkinter.Canvas(frame1, width=450, height=450)
raw_turtle = turtle.RawTurtle(canvas)

scrollbar.config(command = canvas.yview)
canvas.config( yscrollcommand=scrollbar.set)
canvas.pack()

frame2 = Frame(window)
frame2.pack()

Label(frame2, text = "Enter a URL: ").pack(side = LEFT)
url = StringVar()
Entry(frame2, width = 50, textvariable = url).pack(side = LEFT)
Button(frame2, text = "Show Result", command = main).pack(side = LEFT)

window.mainloop()

def main():开始的是直方图的部分。我该怎么把这两个程序结合起来,让直方图替代文本框显示出来呢?提前感谢任何建议!

编辑:

在这里输入图片描述

1 个回答

2

你可以使用 RawTurtle(详细信息可以查看 这个话题)。所以,在你的代码中定义一个 raw_turtle

canvas = tkinter.Canvas(frame1, width=450, height=450)
raw_turtle = turtle.RawTurtle(canvas)

然后用它来绘制直方图。完整的代码看起来是这样的:

from tkinter import *
import tkinter.messagebox
import urllib.request
import turtle


def main():
    counts = analyzeFile(url.get())
    drawHistogram(counts)

def analyzeFile(url):
    try:
        infile = urllib.request.urlopen(url)
        s = str(infile.read().decode()) # Read the content as string from the URL

        counts = countLetters(s.lower())

        infile.close() # Close file
    except ValueError:
        tkinter.messagebox.showwarning("Analyze URL",
            "URL " + url + " does not exist")

    return counts

def countLetters(s):
    counts = 26 * [0] # Create and initialize counts
    for ch in s:
        if ch.isalpha():
            counts[ord(ch) - ord('a')] += 1
    return counts

def drawHistogram(list):

    WIDTH = 400
    HEIGHT = 300

    raw_turtle.penup()
    raw_turtle.goto(-WIDTH / 2, -HEIGHT / 2)
    raw_turtle.pendown()
    raw_turtle.forward(WIDTH)

    widthOfBar = WIDTH / len(list)

    for i in range(len(list)):
        height = list[i] * HEIGHT / max(list)
        drawABar(-WIDTH / 2 + i * widthOfBar,
            -HEIGHT / 2, widthOfBar, height, letter_number=i)

    raw_turtle.hideturtle()

def drawABar(i, j, widthOfBar, height, letter_number):
    alf='abcdefghijklmnopqrstuvwxyz'
    raw_turtle.penup()
    raw_turtle.goto(i+2, j-20)

    #sign letter on histogram
    raw_turtle.write(alf[letter_number])
    raw_turtle.goto(i, j)

    raw_turtle.setheading(90)
    raw_turtle.pendown()


    raw_turtle.forward(height)
    raw_turtle.right(90)
    raw_turtle.forward(widthOfBar)
    raw_turtle.right(90)
    raw_turtle.forward(height)

window = Tk()
window.title("Occurrence of Letters in a Histogram from URL")

frame1 = Frame(window)
frame1.pack()

scrollbar = Scrollbar(frame1)
scrollbar.pack(side = RIGHT, fill = Y)

canvas = tkinter.Canvas(frame1, width=450, height=450)
raw_turtle = turtle.RawTurtle(canvas)

scrollbar.config(command = canvas.yview)
canvas.config( yscrollcommand=scrollbar.set)
canvas.pack()

frame2 = Frame(window)
frame2.pack()

Label(frame2, text = "Enter a URL: ").pack(side = LEFT)
url = StringVar()
Entry(frame2, width = 50, textvariable = url).pack(side = LEFT)
Button(frame2, text = "Show Result", command = main).pack(side = LEFT)

window.mainloop()

这个话题关于在画布上使用滚动条的内容也可能会对你有帮助。

编辑
当我运行上面的代码时,我看到这个:

enter image description here

撰写回答