【问题标题】:visual studio code canvas opens then closes视觉工作室代码画布打开然后关闭
【发布时间】:2019-01-18 19:18:39
【问题描述】:

当我在本机 python 编辑器中运行基本代码时,画布保持打开状态。

当我使用 Visual Studio 代码(按 F5 运行)执行相同的 Python 代码时,应用程序会运行,但随后会立即关闭并返回到编辑器。

下面是代码示例:

import sys
from tkinter import *

def mHello():
    mtext = ment.get()
    mlabel2 = Label(mGui, text = mtext).pack()
    for i in range(0, 10):
        Label(mGui, text = "hello " + str(i+1)).pack()

mGui = Tk()
ment = StringVar()

mGui.geometry('450x450+500+300')
mGui.title("my test thing")

mlabel = Label(mGui, text = "press to okay button to run the code").pack()
mbutton = Button(mGui, text = "ok", command = mHello, fg = "white", bg = "blue").pack()

mEntry = Entry(mGui, textvariable = ment).pack()

请问如何让 VS 代码的行为与本机编辑器相同?

【问题讨论】:

  • 可能是你的窗口没有调用mainloop?

标签: python python-3.x tkinter visual-studio-code


【解决方案1】:

Visual Studio 代码使用 python 解释器,它会在运行脚本之前对其进行编译。 您的窗口会立即关闭,因为您没有在窗口上调用 mainloop()。这意味着一旦窗口被绘制,程序就结束,窗口关闭。

您的窗口不会在 IDLE 中关闭,因为它在交互式 shell 中运行。 shell 等待命令,所以它让你的窗口保持打开状态。有关详细信息,请参阅此问题:When do I need to call mainloop in a Tkinter application?

你需要做的就是添加:

mGui.mainloop()

到脚本的结尾。

【讨论】:

    【解决方案2】:

    在代码末尾添加 input() 有效。

    input("press enter to close >>>")
    

    【讨论】:

    • 即使这样可行,我还是从@strava 添加了上述答案来代替我自己的答案,因为它是一个更好的解决方案。
    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    相关资源
    最近更新 更多