首页 > 解决方案 > 将动态 tkinter 变量插入函数参数

问题描述

如何将动态 tkinter 变量插入函数的参数?我是一个刚开始学习python的新手。

假设我有一个带有 tkinter after() 方法的函数,该函数每秒更新一次,并且不断将整数变量值更改为本地时间的第二个值。然后我想将该变量放入一个函数中,该函数在此处执行类似的操作。

import tkinter as tk
import time as tm

wdw = tk.Tk()
wdw.geometry('500x500')
insert = tk.IntVar() #defined the variable that will inserted to function something

def clock():
    scd= int(tm.strftime('%S')) #get the second local time
    insert.set(scd) # set the insert variable with the local time
    wdw.after(1000,clock) #update the variable scd every second

def something(val):
    u=val #set the wanted letter from the text below
    p=0
    q=0
    TXT= 'This is a text that will be rendered to the label below every 3 letter per second'
    while u < val+3:
        label=tk.Label(wdw,text=TXT[u],font="Courier",fg="red") #prints the needed letter
        label.place(x=17+p,y=17+q)
        p+=17 #translate by the x axis
        q+=17 #translate by the y axis
        u+=1 #cycle to the next letter

clock() #run the clock function to refresh the scd variable
something(insert.get()) #run the something function with the updated 'insert' variable
wdw.mainloop()

上面代码的问题是变量insert被卡住并且不会每秒更新,所以我遇到了一个窗口,该窗口只呈现与我运行代码的第二个相关联的文本。

如何使变量insert动态化,因此它会根据我当地时间的第二个呈现不同的文本。就像它会在第一秒渲染“Thi”,然后在第二秒渲染“his”,在第三秒渲染“is”,在第四秒渲染“s a”,在第五秒渲染“a”等等。

tkinter 中是否有一个我不知道的函数可以解决问题,还是 python 无法动态更新变量的方式?任何帮助将不胜感激

标签: pythontkinter

解决方案


只需从时钟功能触发某事功能。然后它将每秒运行一次。像这样:

import tkinter as tk
import time as tm

wdw = tk.Tk()
wdw.geometry('500x500')
insert = tk.IntVar() #defined the variable that will inserted to function something

def clock():
    scd= int(tm.strftime('%S')) #get the second local time
    insert.set(scd) # set the insert variable with the local time
    wdw.after(1000,clock) #update the variable scd every second
    something() #run the something function with the updated 'insert' variable

def something():
    val=insert.get() #set the wanted letter from the text below
    u=val #set the wanted letter from the text below
    p=0
    q=0
    TXT= 'This is a text that will be rendered to the label below every 3 letter per second'
    while u < val+3:
        label=tk.Label(wdw,text=TXT[u],font="Courier",fg="red") #prints the needed letter
        label.place(x=17+p,y=17+q)
        p+=17 #translate by the x axis
        q+=17 #translate by the y axis
        u+=1 #cycle to the next letter

clock() #run the clock function to refresh the scd variable
wdw.mainloop()

推荐阅读