简体   繁体   English

重新启动后,简单的Python GUI程序将无法运行

[英]Simple Python GUI program won't run, says RESTART

I'm trying to create a python program that pulls up a simple window that displays the text "Hello World?" 我正在尝试创建一个Python程序,该程序会拉出一个简单的窗口,以显示文本“ Hello World?”。 I've imported tkinter and have created a class called MyGUI that should create a simple window. 我已经导入了tkinter并创建了一个名为MyGUI的类,该类应该创建一个简单的窗口。 Then I create an instance of the MyGUI class. 然后,创建MyGUI类的实例。 When I hit "F5" or run the programming after saving it, I get an error: 当我按“ F5”或保存后运行程序时,出现错误:

RESTART: C:....my filepath.....
>>>

Here is the code: 这是代码:

import tkinter

class MyGUI:
    def init (self):
        # Create the main window widget.
        self.main_window = tkinter.tk()


        # Create a Label widget containing the
        # text 'Hello World!'
        self.label = tkinter.Label(self.main_window, text="Hello World!")

        # Call the Label widget's pack method.
        self.label.pack()

        # Enter the tkinter main loop.
        tkinter.mainloop()

# Create an instance of the MyGUI class
my_gui = MyGUI()

What causes the "RESTART" error? 是什么原因导致“重新启动”错误? Does where I save my .py file matter for this program? 我保存.py文件的位置与此程序有关吗?

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks 谢谢

The good news: 好消息:

  • Your code works (in that it doesn't crash in python3, as is)! 您的代码有效(因为它不会在python3中崩溃)!

The bad news: 坏消息:

  1. Your code doesn't do anything :( Your only function would raise an exception if called 您的代码不执行任何操作:(如果调用,您的唯一函数将引发异常
  2. You have a code-unrelated problem 您有与代码无关的问题

To resolve problem #1, change init to __init__ and tkinter.tk to tkinter.Tk() 要解决问题1, tkinter.tk init更改为__init__并将tkinter.tktkinter.Tk()

__init__ is the function called by default on instance construction . __init__实例构造时默认调用的函数 The underscores are important if you want to override it. 如果要覆盖下划线,则下划线很重要。 The other issue is just a typo. 另一个问题只是错字。

You're broader problem is... broader. 您的问题更广泛。 yes it matters where you save your file. 是的 ,保存文件的位置很重要。 If you don't save it in the place you are running python from, you need to supply an absolute path to it, or a relative path from the place you are running from. 如果您没有将其保存在运行python的位置,则需要提供指向它的绝对路径,或者从运行python的位置提供相对路径。 This is a broad topic, but pretty important and not too challenging. 这是一个广泛的主题,但非常重要,并且不太具有挑战性。 Maybe try here , or any python tutorial. 也许尝试这里 ,或任何python教程。

I don't know what type F5 does on your computer. 我不知道您计算机上的F5类型是什么。 I would not in general expect it to run python code. 我一般不会期望它运行python代码。 Are you in an IDE, then maybe it does run python code? 您是否在IDE中,那么也许它确实运行python代码? Are you playing call of duty, because then it's more likely to lob a virtual grenade? 您是否正在玩值班,因为这样更有可能打出虚拟手榴弹? F5 is app-dependent, probably not a universal binding on your machine F5取决于应用程序,可能不是计算机上的通用绑定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM