【问题标题】:How I can stop the printer function?如何停止打印机功能?
【发布时间】:2021-12-05 06:02:09
【问题描述】:
    from tkinter import *
    
    root = Tk()
    
    #This function should stop the function printer
    def button_status(is_clicked):
        return is_clicked
    
    #This function prints integer numbers from 0 to 2
    def printer():
        for i in range(3):
            print(i)
            if(button_status==True):
                break
                
    button = Button(root, text="Stampa",height=2, width=6, command= printer, font=("TkDefaultFont",18),bg='white')
    button.place(x=630, y=680)    
    button3 = Button(root, text="Termina",height=2, width=6, command= lambda: button_status(True), font=("TkDefaultFont",18),bg='white')
    button3.place(x=780, y=680)
    
    print(button_status)
    root.state('zoomed')
    root.mainloop()

【问题讨论】:

  • 关闭Tk()窗口!

标签: python tkinter button


【解决方案1】:

您需要在代码中更改一些内容,以允许一个函数控制另一个函数的行为。

首先需要改变的是printer 不需要使用 Python 循环。如果这样做,tkinter 将没有任何机会运行任何其他代码,因为它将等待printer 函数首先返回。相反,让第一次调用 printer 的按钮传入一个数字,并让函数调度本身在短暂延迟后由 tkinter 主循环再次调用。

def printer(i):
    print(i)                            # Note, this always prints at least once. Move the
    if i < 2 and not button_status:     # print call inside the `if` if you don't want that.
        root.after(1000, printer, i+1)  # Schedule ourselves to be called again in one second

button = Button(root, text="Stampa",height=2, width=6, command=lambda: printer(0),
                font=("TkDefaultFont",18),bg='white')
button.place(x=630, y=680)    

您需要更改的另一件事是在两个函数之间共享状态的某种方式。最简单的方法是使用全局变量,但您可以考虑将两个函数重新设计为类的方法,以便它们可以通过实例变量共享状态。这是全局变量设置的样子(上面的printer 已经可以使用此代码):

button_status = False     # Set an initial value

def stop_counting():
    global button_status  # This tells Python we want to be able to change the global variable
    button_status = True  # Use `button_status = not button_status` if you want it to toggle

button3 = Button(root, text="Termina",height=2, width=6, command=stop_counting,
                 font=("TkDefaultFont",18),bg='white')
button3.place(x=780, y=680)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2012-08-10
    相关资源
    最近更新 更多