python 如何在Tkinter中启动一个函数而不使用按钮

qlzsbp2j  于 2023-10-14  发布在  Python
关注(0)|答案(4)|浏览(117)

最近我遇到了一个问题。在这个程序中,我写了一个例子,按钮激活“第一”功能,它增加了1到变量“a”,当它变成3时,它应该改变“b”的值为2。当“B”等于2时,它应该激活另一个名为“second”的函数,该函数应该在1秒后将此变量变为10。但“第二”功能不起作用。我该如何解决此问题?

from tkinter import *
import time

root = Tk()
root.geometry("500x500")
root.resizable(False, False)

a = 0
b = 0

labelA = Label(text=a, font="Arial 32")
labelA.pack()

labelB = Label(text=b, font="Arial 32")
labelB.pack()

def first():
    global a, b
    a+=1
    labelA["text"] = a
    if a==3:
        b+=2
        labelB["text"] = b
    else:
        pass

def second():
    global b
    if b==2:
        time.sleep(1)
        b==10
        labelB["text"] = b
second()

button = Button(command=first, width=30, text="click to do something")
button.pack()

root.mainloop()

我期待功能“第二”被激活,但它没有激活

deyfvvtc

deyfvvtc1#

函数second仅在脚本启动时执行一次。所以它不会将b更改为10。您可以将second函数的内容移动到first

from tkinter import *
import time

def first():
    global a, b
    a += 1
    labelA['text'] = a
    if a == 3:
        b += 2
        labelB['text'] = b

    if b == 2:
        time.sleep(1)
        b = 10
        labelB['text'] = b

root = Tk()
root.geometry('500x500')
root.resizable(False, False)
a = 0
b = 0
labelA = Label(text=a)
labelA.pack()
labelB = Label(text=b)
labelB.pack()
button = Button(command=first, width=30, text='click to do something')
button.pack()
root.mainloop()
w6lpcovy

w6lpcovy2#

因为你只在程序开始时调用函数second一次。也许你可以在函数first的末尾添加second()。并将函数second中的语句b==10更正为b=10

svgewumm

svgewumm3#

如果你想在一段时间后执行函数,你可以在Tkinter中使用root.after。修改后的功能将是:

def first():
    global a, b
    a+=1
    labelA["text"] = a
    if a==3:
        b+=2
        labelB["text"] = b
        #Call the second() function since 'b' is already equal to 2
        #This will call the second function after 1 second
        root.after(1000, second) #1000ms = 1s

    else:
        pass

def second():
    global b
   
    b = 10 #Don't put two equal signs here
    labelB["text"] = b

button = Button(command=first, width=30, text="click to do something")
button.pack()

请注意,我们在second后面不使用括号。

xtupzzrd

xtupzzrd4#

try this one code it working for me proper
import tkinter as tk

def my_function(event):
    print("Function started")

root = tk.Tk()

# Create a widget (e.g., a canvas) where you want to trigger the function.
canvas = tk.Canvas(root, width=200, height=100)
canvas.pack()

# Bind an event to the widget (e.g., <Button-1> for left mouse click).
canvas.bind("<Button-1>", my_function)

root.mainloop()

相关问题