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()
uj5u.com熱心網友回復:
您需要在代碼中更改一些內容,以允許一個函式控制另一個函式的行為。
需要更改的第一件事是不需要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)
uj5u.com熱心網友回復:
停止列印輸出的另一種方法是使用標志布林值。
此方法將標志存盤在串列中,從而避免在函式中使用全域陳述句。
import tkinter as tk
root = tk.Tk()
# termination flag in list
termina = [ False ]
#This function should stop the function printer
def button_status():
termina[ 0 ] = True
#This function prints integer numbers from 0 to 2999
def printer():
# Setup termination flag for printing
termina[ 0 ] = False
for i in range(3000):
root.update()
if termina[ 0 ]: # test for True status
break
else:
print(i)
buttonA = tk.Button(
root, text="Stampa", command= printer,
font=("TkDefaultFont",18), bg='white')
buttonA.grid(sticky = tk.NSEW)
buttonB = tk.Button(
root, text="Termina", command= button_status,
font=("TkDefaultFont",18), bg='white')
buttonB.grid(sticky = tk.NSEW)
# root.state('zoomed')
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323739.html
