Python tkinter 组件只有在 Jupyter notebook 中点击后才会显示

Python tkinter components not showing until clicked on in a Jupyter notebook

我正在尝试使用 Python tkinter 和 Jupyter notebook 练习基本的 GUI。我正在研究 Mac 蒙特雷。我遇到的问题是,在单击它们所在的 space 之前,Scale、Message 和 Spinbox 元素不会显示。这种情况大多数时候都会发生,但偶尔也会按预期显示。

我创建了一个只有 Spinbox 组件的新笔记本,以确保它没有受到其他代码的干扰,但我得到了相同的结果。还有其他人遇到过这个问题吗?

这是我的代码

from tkinter import *

# create root window
root = Tk()
 
# root window title and dimension
root.title("GUI Components")

# Set geometry (widthxheight)
root.geometry('1350x1250')
 
# all widgets will be here
text = Label(root, text='GUI Components')
text.pack()

#SpinBox – select from a range of values using arrow (up/down) selectors.
spnlabel = Label(root, text = 'Spin box')

sp = Spinbox(root, from_ = 0, to = 20)

spnlabel.pack()
sp.pack()

root.mainloop()

由于 tkinter 比 jupyter notebooks 早了几十年,因此从未在这样的环境中构想 运行。

将您的脚本保存为文件,然后 运行 直接使用 Python。在那种情况下它工作正常。

编辑: 您应该知道 Python 生态系统中有几项不适用于 jupyter notebooks。 tkinter 之类的 GUI 工具包是一回事。 multiprocessingconcurrent.futures 是另一个。

一般来说,如果您的 Python 代码没有 运行 或者做一些奇怪的事情 IDE,请尝试将其保存为脚本并 运行首先从命令行。