【发布时间】:2021-09-14 02:18:45
【问题描述】:
我正在使用 Jupyter notebook 编写一个包含大量“if”语句的 tkinter 算法。
我希望这些“if”语句中的一些在某些点停止运行程序(但不停止运行 tkinter 窗口)而不返回到代码的主要流程。我写了一个小示例应用程序(如下)来说明我的意思。
我尝试过使用 quit()、exit()、sys.exit() 和 os.exit()。 quit() 和 exit() 似乎都可以正常工作,正如预期的那样,他们说“嗨”而不是“再见”。但是当我关闭 tkinter 窗口时,我仍然会得到一些不需要的读数——我认为这可能比 python 或 tkinter 更多的是 Jupyters 错误。它通常说,“内核似乎已经死了。它将自动重新启动。”
示例脚本包含上面的每个命令,它使用注释“#”来打开和关闭行。每个案例的不需要的读数和消息也在脚本中的代码旁边注释。
我担心如果我进一步编码,不需要的读数是否会出现问题甚至是安全威胁,因为其中一些 if 语句将在密码保护区域中使用。我是否正确假设,如果不需要的消息来自 Jupyter,一旦我将代码编译为 exe,这些消息将是良性和透明的?
我的代码如下:
import tkinter
from tkinter import *
import tkinter as tk
import sys
import os
def routine ():
x = 0
if x < 1:
print("Hi")
# quit() # Prints Hi and not bye;
# when destroyed, it says Kernel Restarting
# The kernel appears to have died. It will restart automatically.
# exit() # On an apparent level - it seems to do all the same things as quit.
# sys.exit() # Prints Hi
# and then...
# An exception has occurred, use %tb to see the full traceback.
# SystemExit
# Then the entire systems, including the tkinter window,
# locks up and spin doing nothing.
# The close button wont even work.
# os._exit() # Exception in Tkinter callback
# Traceback (most recent call last):
# File "C:\Users\rrr\lib\tkinter\__init__.py", line 1705, in __call__
# return self.func(*args)
# File "<ipython-input-3-c9d340ae6a31>", line 31, in routine
# os._exit()
# TypeError: _exit() missing required argument 'status' (pos 1)
if x > 1:
print("bye...")
root = Tk()
root.geometry("300x200+200+200")
btn1 = Button(root, text ="Run A Routine", command = routine)
btn1.pack(pady = 20, anchor='center')
btn1 = Button(root, text ="Close Window", command = root.destroy)
btn1.pack(pady = 20, anchor='center')
root.mainloop()
【问题讨论】:
-
你的问题来自 jupyter。 Jupyter 通过内核运行你的所有笔记本。当您使用 exit() 时,您会关闭内核并且 jupyter 会抱怨。这就带来了一个问题,如果要将 jupyter 编译成 exe,为什么要使用它来编码?另外,
code any further是什么意思?杀死内核后没有代码运行。
标签: python tkinter jupyter-notebook exit