【问题标题】:Use tkinter as a GUI and use it to run a program使用 tkinter 作为 GUI 并使用它来运行程序
【发布时间】:2016-08-25 09:05:51
【问题描述】:

我最近开始使用 python,现在我正在尝试用 tkinter 制作一个 gui。我正在使用最新版本的 PyCharm 社区版。我需要让它看起来像它在 PyCharm 中的正常显示一样,让它看起来更吸引人,并允许输入文本和点击等。大多数教程都已过时,不再适用于 PyCharm。我花了 10 分钟才找到 tkinter 本身的正确导入语句。我需要制作一个文本框,我可以在其中输入以下代码所需的内容。就像它说按回车圈我需要按回车键让它在文本框中圈。有人可以为其中一个 raw_inputs 证明这一点,然后我可以将其应用于其余部分吗?提前致谢。

代码如下:

import time
laps=[0]

def lap():
    lapping = raw_input("lap? (press enter to lap) to stop type something first then press enter")
    if lapping == "":
        end()

    while lapping == "":
            break
            lap()

def end():
    end = time.time()
    elapsed = end - start
    laps[0]+=1
    print "%s seconds" % (elapsed)
    print "%s lap(s)" % (laps)
    lap()

starting = raw_input("start? (press enter to start)")
if starting == "":
    start = time.time()
    ending = raw_input("end? (press enter to end)")
    if ending == "":
        end()

【问题讨论】:

  • 你忘了包含一个问题
  • 即使在链接中(函数end 的内容),代码看起来也缩进很严重。我已尝试更正它并将其直接添加到您的问题中,请检查它,如果它是您想要的方式,请删除带有链接的最后一句话。
  • @quapka 非常感谢,我直接从 PyCharm 复制了代码。
  • @ArchitSrivastava 当我将代码发布到 soQ 中时,我基本上有两种方式 - 1)(我使用 SublimeText)在 SublimeText 中我缩进整个代码(Ctrl + A, Tab, Ctrl + C)并将其粘贴到 Q ; 2)我将它复制到Q中并在那里全选,然后单击{}进行代码格式化。
  • 对你的问题:我没有使用 Tkinter,但在环顾四周后,我可以用几个按钮实现我的小代码,它可以处理研磨机制并显示单圈时间(不能现在,不过,也许我会在 2 小时后有时间)。与此同时look at this answer.

标签: python user-interface tkinter tkinter-canvas


【解决方案1】:

免责声明:我之前只使用过一次 Tkinter,并且没有更多的经验。但是,我虽然能够将这段代码放在一起。最后它起作用了,虽然我对很多部分不满意。希望它可以作为我的起点。但老实说,搜索谷歌会给你更好和更清晰的起始示例。代码也在我的github上。

import tkinter as tk
import time


class App(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # boolean for checking, whether the stopwatch currently run
        self.running   = False
        # the starting time
        self.startTime = 0
        # StringVar so the text inside self.label is updated on change
        self.timeLabelText = tk.StringVar()
        self.label = tk.Label(textvariable=self.timeLabelText)
        # pack it in the frame
        self.label.pack()
        # similar code for button, added self._runButton when the button is clicked
        self.runButtonText = tk.StringVar()
        self.runButtonText.set("Run")
        self.runButton = tk.Button(textvariable=self.runButtonText,
                                   command=self.__runButton)
        self.runButton.pack()
        # array to hold the laps
        self.laps    = []
        self.lapButton = tk.Button(text="Lap",
                                   command=self.__lapButton)
        self.lapButton.pack()
        # bind Return with __lapButton function
        self.bind("<Return>", self.__lapButton)

    def __timelabel(self):
        # if running change the time each second
        if self.running:
            seconds = time.time() - self.startTime
            self.timeLabelText.set("%d:%02d:%02d" % seconds_to_time(seconds))
            self.after(1000, self.__timelabel)

    def __runButton(self):
        # if "was" running, set running to false and adjust label
        if self.running:
            self.running = False
            self.runButtonText.set("Run")
        # if "was not" running
        else:
            # get the time
            self.startTime = time.time()
            # change running to True
            self.running = True
            # start stopwatch immediately
            self.after(0, self.__timelabel)
            # change the text on the runButton
            self.runButtonText.set("Stop")
            # clear each lap from previous run
            for lap in self.laps:
                lap.pack_forget()
            # and empty it, maybe use while loop and pop
            self.laps = []

    def __lapButton(self, *args):

        if self.running:
            # get the time as str "HH:MM:SS"
            t = self.timeLabelText.get()
            t = time_to_seconds(t)
            # if there are previous laps
            if self.laps:
                # get their sum
                elapsed = sum([time_to_seconds(self.laps[x].cget("text")) for x in range(len(self.laps))])
                # substract that
                t       = t - elapsed
            t = seconds_to_time(t)
            t = ":".join([str(x) for x in t])
            # add new label with text
            self.laps.append(tk.Label(text=t))
            # pack all the label
            for lap in self.laps:
                lap.pack()

# methods for handling time
# probably it would be better to use some precoded method from 
# module time and datetime
def time_to_seconds(time):

    h, m, s = [int(x) for x in time.split(':')]
    return h*3600 + m*60 + s

def seconds_to_time(seconds):

    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return h, m, s

if __name__ == '__main__':

    App().mainloop()

【讨论】:

  • 好的,谢谢,我发现 _tkinter 和 Tkinter 是不同的。我想这就是我搞砸的原因。非常感谢您的帮助。
  • 另外,有没有办法打印他们已经完成的圈数?我环顾了你所做的一切,我了解你所做的大部分工作。只是当你显示时间的时候,有没有办法同时显示已经完成的圈数?
  • @architsrivastava 是的,可以。可能有更好的方法,但我认为只需更改 __lapButton 函数即可。我稍后会添加:)
  • @ArchitSrivastava 我已经更新了 github 上的代码。您还可以在那里浏览文件并查看历史记录,因此您将明确看到添加的内容。
  • 当我尝试你的代码时,这个错误出现在 Tkinter 回调 Traceback 中的异常(最近一次调用最后一次):文件“/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2. 6/lib-tk/Tkinter.py”,第 1410 行,在 call 中返回 self.func(*args) 文件“/Users/mynamewashere/PycharmProjects/projectintro/gui for tihs.py”,行74、在 __lapButton t = "{}.{}".format(len(self.laps)+ 1, t) ValueError: 格式中的零长度字段名称
猜你喜欢
  • 2022-01-15
  • 2018-09-14
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多