Python 脚本仅适用于 IDLE [英] Python script only works on IDLE

查看:23
本文介绍了Python 脚本仅适用于 IDLE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本有一段时间了.但是,它仅在我从 IDLE 启动时运行;如果我尝试从桌面运行它,它不会启动.这是一个用 Tkinter 制作的时钟.

I have had this script for some time. However, it only runs if I start it from IDLE; if I try to run it from the desktop it doesn't start. It is a clock made with Tkinter.

import time

from tkinter import *

def showTime():

    canvas.delete('text')
    if True:
        actualTime = time.localtime()

        text = canvas.create_text((100,50,),
                                  text =(actualTime[3],actualTime[4],actualTime[5]),
                                  fill="white",
                                  font=("Verdana",20,"bold"),
                                  tag="text")

    root.after(1000,showTime)

if "__main__" == __name__:

    root = Tk()

    root.resizable(False,False)
    root.title("Clock")

    canvas = Canvas(root, width=200, height=100,bg="black",cursor="target")
    canvas.create_rectangle((20,20),(180,80),outline="ghostwhite")
    canvas.pack()

    showTime()

推荐答案

您需要启动 Tkinter 主循环.只需添加

You need to start the Tkinter mainloop. Just add

root.mainloop()

到你的

showTime()

打电话.

您的脚本在 IDLE 中工作的原因是 IDLE 本身是一个 Tkinter 程序,并且它已经有一个事件循环,如 这个答案.

The reason that your script works in IDLE is that IDLE itself is a Tkinter program, and it already has an event loop going as mentioned in this answer.

顺便说一句,showTime 中的 if True: 语句毫无意义.

BTW, that if True: statement in showTime is pointless.

FWIW,这是添加了 mainloop 调用的程序,以及其他一些小改动.最好避免星形"导入,因为它们会用导入的名称混淆您的命名空间,例如 from tkinter import * 引入了 130 多个名称.这可能会导致与您自己定义的名称发生冲突,除非您非常熟悉 Tkinter 定义的每个名称,但如果您将星型导入与另一个碰巧使用 Tkinter 使用的名称的模块一起使用,则尤其成问题.

FWIW, here is your program with the mainloop call added, and a few other minor changes. It's better to avoid "star" imports because they clutter your namespace with the imported names, eg from tkinter import * brings in over 130 names. This can cause collisions with names you define yourself, unless you're intimately familiar with every name that Tkinter defines, but it's especially problematic if you use a star import with another module that happens to use names that Tkinter uses.

import time
import tkinter as tk

def showTime():
    canvas.delete('text')
    actualTime = time.localtime()

    text = canvas.create_text((100, 50),
        text = actualTime[3:6],
        fill="white",
        font=("Verdana", 20, "bold"),
        tag="text")

    root.after(1000, showTime)

if "__main__" == __name__:
    root = tk.Tk()

    root.resizable(False,False)
    root.title("Clock")

    canvas = tk.Canvas(root, width=200, height=100, bg="black", cursor="target")
    canvas.create_rectangle((20, 20), (180, 80), outline="ghostwhite")
    canvas.pack()

    showTime()
    root.mainloop()

<小时>

正如 Bryan Oakley 在评论中提到的,最好只更新 Canvas Text 项目的文本字符串,而不是丢弃旧的 Text 项目并每秒构建一个新的.所以这是从您的代码派生的新版本.


As Bryan Oakley mentions in the comments, it's better to just update the text string of the Canvas Text item, rather than trashing the old Text item and building a fresh one every second. So here's a new version derived from your code.

我使用 time.strftime 来构建时间字符串,因为它比简单地切片 time.localtime 返回的 struct_time 对象提供更好的输出:它总是使用 2 位数字表示小时、分钟、和秒组件,您可以轻松地将冒号(或其他)添加到格式字符串中.请参阅链接文档,了解 strftime 提供的所有格式选项.

I use time.strftime to build the time string because it gives nicer output than simply slicing the struct_time object returned by time.localtime: it always uses 2 digits for the hours, minutes, and seconds components, and you can easily add colons (or whatever) to the format string. Please see the linked docs for all the format options that strftime provides.

我还把 GUI 放到了一个类中.对于这样一个简单的 GUI 来说,这并不是真正必要的,但这是一个很好的习惯,因为它使代码更加模块化.

I've also put the GUI into a class. That's not really necessary for such a simple GUI, but it's a good habit to get into because it makes the code more modular.

import tkinter as tk
from time import strftime

class Clock:
    def __init__(self):
        root = tk.Tk()
        root.title("Clock")
        root.resizable(False, False)

        self.canvas = canvas = tk.Canvas(root, width=200, height=100, 
            bg="black", cursor="target")
        canvas.create_rectangle((20, 20), (180, 80), outline="ghostwhite")
        canvas.create_text((100, 50), tag = "text",
            fill="white", font=("Verdana", 20, "bold"))
        canvas.pack()

        self.show_time()
        root.mainloop()

    def show_time(self):
        w = self.canvas
        w.itemconfig("text", text=strftime('%H %M %S'))
        w.after(1000, self.show_time)

if "__main__" == __name__:
    Clock()

这篇关于Python 脚本仅适用于 IDLE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆