简体   繁体   中英

Tkinter buttons not showing up

The program should let the user select a file and displays the occurrence counts in a histogram. Clicking the Show Result button displays the result in a text widget. You need to display a message in a message box if the file does not exist.

Image 1 - from Textbook

The buttons and other objects doesn't seem to be showing up as seen in the image below.
Image 2 - my Screenshot

Heres my code:

from tkinter import *
import tkinter.messagebox
from tkinter.filedialog import askopenfilename


def showResult():
    analyzeFile(filename.get())
    
def analyzeFile(filename):
    try:
        infile= open(filename, "r")

        letterCount= 26*[0]
        for line in infile:

            countLetters(line.lower(), letterCount)
        infile.close() 


        
    except IOError: 
        tkinter.messagebox.showwarning("Analyze File", "File " + filename + " does not exist")



    drawHistogram(letterCount)



def countLetters(line, letterCount):
    for chr in line:
        if chr.isalpha():
            letterCount[ord(chr) - ord('a')] +=1


def openFile():
    fileForReading= askopenfilename()

    filename.set(fileForReading)
    

def drawHistogram(count):
    canvas.delete("bar")
    wide = 400
    high = 400

    canvas.create_line(0, high-15,wide , high-15)

    barWidth= (wide-20) / len(count)
    unitHeight= (high-20) /max(count)

    for i in range(len(count)):
        height= count[i] * unitHeight
        canvas.create_rectangle(i*barWidth+10, high-height-15,(i+1)* barWidth+10, high-15, tags = "bar")

        canvas.create_text((i+1)*barWidth,high-5, text= chr(i + ord('a')),tags="bar")

window = Tk()
window.title("Occurrence of Letters Histogram")

size= 400
canvas= Canvas(window, width = size, height = size)
canvas.pack()

frame2= Frame(window)


Label(frame2, text="Enter a filename: ").pack(side=LEFT)
filename= StringVar()
Entry(frame2, width = 20, textvariable = filename).pack(side = LEFT)
Button(frame2, text = "Browse", command = openFile).pack(side = LEFT)
Button(frame2, text = "Show Result", command = showResult).pack(side = LEFT)
window.mainloop()

  

You have never packed frame2 . If you pack it, then everything will show up. Also note that you must call the pack statement on a separate line, lest the variable be None , as pack returns no value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM