如何将文本值用于函数?

时间:2019-07-23 14:59:54

标签: python tkinter python-3.7

from tkinter import *
import time
import psutil

master = Tk()
e = Entry(master)
e.pack()
e.focus_set()

def callback():
    print(e.get())  # This is the text you may want to use later

b = Button(master, text="OK", width=10, command=callback)
b.pack()

mainloop()

def count(n):
    while n > 0:
        print(n)
        time.sleep(1)
        n = n - 1

count(e.get())

我正在尝试根据用户在文本字段中输入的数字(文本)设置计时器。但是每次运行代码时,我都会不断收到此错误:

 Traceback (most recent call last):
  File "E:/Internshala_dreambig/src/game.py", line 32, in <module>
    count(e.get())
  File "C:\Users\Abhishek\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2682, in get
    return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".!entry"

我该如何解决?

2 个答案:

答案 0 :(得分:0)

最好使用while每1000毫秒(1s)执行一次root.after(1000, update_timer)函数,而不是update_timer循环和睡眠。此函数将更新值并更新Label

中的文本
import tkinter as tk

# --- functions ---

def start():
    global count

    count = entry.get()

    try:
        count = int(count)
        update_timer()
    except:
        label['text'] = 'wrong value'

def update_timer():
    global count

    if count >= 0:
        label['text'] = str(count)
        count -= 1
        root.after(1000, update_timer)

# --- main ---

root = tk.Tk()

label = tk.Label(root)
label.pack()

entry = tk.Entry(root)
entry.pack()
entry.focus_set()

button = tk.Button(root, text="START", command=start)
button.pack()

root.mainloop()

答案 1 :(得分:0)

谢谢大家的回答,我是使用python进行GUI编程的新手,所以我很抱歉问这些愚蠢的问题。

经过长时间的努力,我终于找到了可行的解决方案。 (虽然很奇怪,但是在像以前一样将输入文本转换为int时,它不会显示任何 ValueError )。

这是重新格式化的代码:

def count(n):
   while n > 0:
     print(n)
     time.sleep(1)
     n = n - 1
   if n == 0:
     #do something


master = Tk()
e = Entry(master)
e.pack()

e.focus_set()


def callback():
    print(e.get())
    count(int(e.get()))


b = Button(master, text="OK", width=10, command=callback)
b.pack()

mainloop()