首页 > 解决方案 > Python 程序只能从 IDLE 运行

问题描述

这是我第一次在 python 上运行,我绝不是代码编写者。我有一个项目,我需要编写一个 GUI 来命令 arduino,经过大量的谷歌搜索和拼凑代码后,我制作了这个程序,它在从 IDLE 运行时可以完美运行。当我从 Windows(双击它)或从 linux(通过命令行 python3filler.py)启动它时,它会像出现错误一样打开和关闭。我可以通过相同的方法启动其他 python 程序而没有问题。因为从 IDLE 中启动它以使硬件运行不是问题,所以我不能放弃,因为我想为未来的项目获得更多关于 python 的知识。任何帮助将不胜感激。

import tkinter as tk
import serial as s
import time as t
from tkinter import *



class Action:
    def __init__(self):


        def on():
            ser.write(b'7')

        def exit():
            ser.close() # close serial port
            quit()

        self.window = Tk()
        self.window.title("Moore Speciality Brewing")
        self.window.geometry('640x480')
        self.lbl = Label(self.window, text="Can Filler",fg='black',font=(None, 15))
        self.lbl.place(relx=0.24, rely=0.10, height=50, width=350)
        bo = Button(self.window, text="Fill Can", width=10 ,bg='red' ,command=on)
        bo.place(relx=0.34, rely=0.30, height=40, width=200)
        ext = Button(self.window, text="Exit", width=10, bg='white', command=exit)
        ext.place(relx=0.34, rely=0.50, height=40, width=200)

class Prompt(tk.Tk):
    def __init__(self):
        global comm
        comm = None               
        tk.Tk.__init__(self)
        self.geometry('640x480')
        self.label = tk.Label(self, text="Comm Port",fg='black',font=(None, 15))
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)

        self.entry.place(relx=.5, rely=.5,anchor="center" )
        self.label.place(relx=.5, rely=.44,anchor="center")
        self.button.place(relx=.5, rely=.56,anchor="center")

    def on_button(self):
        comm = self.entry.get()
        global ser
        ser = s.Serial(comm, 9600, timeout=0)   # check your com port
        t.sleep(2)
        Action()
        self.destroy()

Prompt()

标签: python

解决方案


您已经在代码中导入了时间。只需t.sleep(60)在代码末尾使用,让 cli 等待您查看是否有错误并让您调试。

最后Prompt()是不正确的。使用这样的东西:

myPrompt = Prompt()
myPrompt.mainloop() 

这部分实际上称为 tkinter gui。


推荐阅读