【问题标题】:Tkinter buttons not showing upTkinter 按钮未显示
【发布时间】:2020-08-01 15:13:19
【问题描述】:

程序应该让用户选择一个文件并在直方图中显示出现次数。单击“显示结果”按钮会在文本小部件中显示结果。如果文件不存在,您需要在消息框中显示一条消息。

Image 1 - from Textbook

如下图所示,按钮和其他对象似乎没有显示出来。
Image 2 - my Screenshot

这是我的代码:

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()

  

【问题讨论】:

  • 您从未在 frame2 上调用过 .pack(),因此它以及其中包含的任何小部件都不会变得可见。

标签: python tkinter histogram


【解决方案1】:

你从来没有打包过frame2。如果你打包它,那么一切都会出现。另请注意,您必须在单独的行中调用 pack 语句,以免变量为None,因为pack 没有返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2021-07-25
    • 1970-01-01
    • 2022-10-24
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多