Hello,
i was creating a program to present number of each character out of a file the user browse for and present it on a text widget. The next phase was to have the same count presented as a histogram displayed on the text widget. I managed to find something smaller with a URL selection but i find it difficult to incorporate the same logic into my original code. Asking for help with using the same logic from the URL code into the original one so it could display the same as in the attached file.
the original code:
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
# Construct root window
root = Tk()
# Construct top frame
topframe = Frame(root)
topframe.pack(side=TOP)
# Add text area with scrollbar
scrollbar = Scrollbar(topframe)
text = Text(topframe, width=35, height=10, yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)
scrollbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT)
# Construct bottom frame
bottomframe = Frame(root)
bottomframe.pack(side=TOP)
# Add label to enter filename
var = StringVar()
label = Label(bottomframe, textvariable=var)
var.set(‘Enter filename:’)
label.pack(side=LEFT)
# Add entry for filename
entry = Entry(bottomframe, width=15)
entry.pack(side=LEFT)
# Callback function to get filename with file dialog
def getFilename():
filename = filedialog.askopenfilename(initialdir = ‘.’,
title = ‘Select a File’,
filetypes = ((‘Text files’,
‘*.txt*’),
(‘all files’,
‘*.*’)))
entry.delete(0, END)
entry.insert(0, filename)
# Add browse button to get filename
browseButton = Button(bottomframe, text=’Browse’, command=getFilename)
browseButton.pack(side=LEFT)
# Callback function to count characters from file
def countCharacters():
filename = entry.get()
alphabet = ‘abcdefghijklmnopqrstuvwxyz’
counts = {c: 0 for c in alphabet}
try:
with open(filename) as f:
for line in f:
for c in line:
if c in alphabet:
counts[c] += 1
text.delete(1.0, END)
for c in alphabet:
text.insert(END, c + ‘ appears ‘ + str(counts[c]) + ‘ times’)
if c != ‘z’:
text.insert(END, ‘n’)
except FileNotFoundError:
if filename == ”:
filename = ‘(empty)’
messagebox.showinfo(‘Error’, ‘Invalid filename: ‘ + filename)
# Add show result button to count characters
showResultButton = Button(bottomframe, text=’Show Result’, command=countCharacters)
showResultButton.pack(side=LEFT)
# Run main window
root.title(‘Occurrence of Letters’)
root.geometry(‘300×190’)
root.mainloop()
the histogram code and logic to be incorporated into the original code so this logic is preform on a text file selected by the user using browse:
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()


0 comments