有谁知道为什么我的tkinter按钮没有呈现?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (62)

这是在GitHub上的一个python项目,我正在为Magic 8 Ball模拟制作一个GUI。我似乎无法使用.pack()函数或我的窗口只是永远加载而无需实例化。

创建时

当我单击按钮时,文本出现

window = Tk()
window.configure(bg="black")
window.title("Magic 8 Ball")
Label(window, text="Ask the Magic 8 Ball the question on your mind or enter X to exit: ", bg="black", fg="white")\
    .grid(row=0, column=0)


# Create entry box to type question
entrybox = Entry(window, width=30, bg="white")
entrybox.grid(row=1, column=0)


# Create output box at below buttons
output = Text(window, bg="white", fg="black", width=40, height=5)
output.grid(row=4, column=0)


# Create 4 button: Ask, Clear, Play Again, Quit
button_frame = Frame(window)
button_frame.configure(bg="black")
button_frame.grid(row=2, column=0)

#button_frame.pack(fill=X, side=BOTTOM)
Button(button_frame, text="Ask", width=10, bg="black", fg="white", command=click).grid(row=2, column=0)
Button(button_frame, text="Clear", width=10, command=clear).grid(row=2, column=1)
Button(button_frame, text="Play Again", width=10,command=repeat).grid(row=3, column=0)
Button(button_frame, text="Quit", width=10, command=close).grid(row=3, column=1)


window.mainloop()
提问于
用户回答回答于

我想我们需要更多关于你的操作系统和python版本的规范。我在Python 3.5.0和Windows 10上运行它,结果如下:

所以我不认为这是你的代码中的错误。我确实必须添加你失去的所有功能和导入,所以我跑的最终看起来像:

from tkinter import *
window = Tk()
def click():
    print('click')
def clear():
    print('clear')
def repeat():
    print('repeat')
def close():
    print('close')
window.configure(bg="black")
window.title("Magic 8 Ball")
Label(window, text="Ask the Magic 8 Ball the question on your mind or enter X to exit: ", bg="black", fg="white")\
    .grid(row=0, column=0)


# Create entry box to type question
entrybox = Entry(window, width=30, bg="white")
entrybox.grid(row=1, column=0)


# Create output box at below buttons
output = Text(window, bg="white", fg="black", width=40, height=5)
output.grid(row=4, column=0)


# Create 4 button: Ask, Clear, Play Again, Quit
button_frame = Frame(window)
button_frame.configure(bg="black")
button_frame.grid(row=2, column=0)

#button_frame.pack(fill=X, side=BOTTOM)
Button(button_frame, text="Ask", width=10, bg="black", fg="white", command=click).grid(row=2, column=0)
Button(button_frame, text="Clear", width=10, command=clear).grid(row=2, column=1)
Button(button_frame, text="Play Again", width=10,command=repeat).grid(row=3, column=0)
Button(button_frame, text="Quit", width=10, command=close).grid(row=3, column=1)


window.mainloop()
用户回答回答于

你不能使用.pack()是因为.grid().pack()不能在同一个程序中。如果你这样做,你会收到错误。

至于冻结,只要确保你没有无限循环,因为tkinter是一个线程模块,这意味着它通过命令逐行完成。

扫码关注云+社区

领取腾讯云代金券