App下載

如何解決Tkinter中button按鈕未按卻主動執(zhí)行command函數(shù)

猿友 2021-07-19 13:48:25 瀏覽數(shù) (4140)
反饋

在學習pythonGUI編程的時候,不可避免的會遇到按鈕功能。一般來說一個按鈕都會有一個點擊事件,點擊后就會執(zhí)行一項功能。在學習了一定的GUI知識后就會知道點擊后執(zhí)行的功能是由一個函數(shù)實現(xiàn)的,這個函數(shù)又被稱為command函數(shù)。以tkinter為例,那么python怎么使用button按鈕呢?tkinter的botton執(zhí)行command函數(shù)需要怎么設(shè)置呢?接下來這篇文章告訴你。

前言

在使用Tkinter做界面時,遇到這樣一個問題:

程序剛運行,尚未按下按鈕,但按鈕的響應函數(shù)卻已經(jīng)運行了

例如下面的程序:

from Tkinter import *
class App:
 def __init__(self,master):
  frame = Frame(master)
  frame.pack()
  Button(frame,text='1', command = self.click_button(1)).grid(row=0,column=0)
  Button(frame,text='2', command = self.click_button(2)).grid(row=0,column=1)
  Button(frame,text='3', command = self.click_button(1)).grid(row=0,column=2)
  Button(frame,text='4', command = self.click_button(2)).grid(row=1,column=0)
  Button(frame,text='5', command = self.click_button(1)).grid(row=1,column=1)
  Button(frame,text='6', command = self.click_button(2)).grid(row=1,column=2)
 def click_button(self,n):
  print 'you clicked :',n
  
root=Tk()
app=App(root)
root.mainloop()

程序剛一運行,就出現(xiàn)下面情況:

運行結(jié)果

六個按鈕都沒有按下,但是command函數(shù)卻已經(jīng)運行了

后來通過網(wǎng)上查找,發(fā)現(xiàn)問題原因是command函數(shù)帶有參數(shù)造成的

tkinter要求由按鈕(或者其它的插件)觸發(fā)的控制器函數(shù)不能含有參數(shù)

若要給函數(shù)傳遞參數(shù),需要在函數(shù)前添加lambda。

原程序可改為:

from Tkinter import *
class App:
 def __init__(self,master):
  frame = Frame(master)
  frame.pack()
  Button(frame,text='1', command = lambda: self.click_button(1)).grid(row=0,column=0)
  Button(frame,text='2', command = lambda: self.click_button(2)).grid(row=0,column=1)
  Button(frame,text='3', command = lambda: self.click_button(1)).grid(row=0,column=2)
  Button(frame,text='4', command = lambda: self.click_button(2)).grid(row=1,column=0)
  Button(frame,text='5', command = lambda: self.click_button(1)).grid(row=1,column=1)
  Button(frame,text='6', command = lambda: self.click_button(2)).grid(row=1,column=2)
 def click_button(self,n):
  print 'you clicked :',n  
root=Tk()
app=App(root)
root.mainloop()

補充:Tkinter Button按鈕組件調(diào)用一個傳入?yún)?shù)的函數(shù)

這里我們要使用python的lambda函數(shù),lambda是創(chuàng)建一個匿名函數(shù),冒號前是傳入?yún)?shù),后面是一個處理傳入?yún)?shù)的單行表達式。

調(diào)用lambda函數(shù)返回表達式的結(jié)果。

首先讓我們創(chuàng)建一個函數(shù)fun(x):

def fun(x):
    print x

隨后讓我們創(chuàng)建一個Button:(這里省略了調(diào)用Tkinter的一系列代碼,只寫重要部分)

Button(root, text='Button', command=lambda :fun(x))

下面讓我們創(chuàng)建一個變量x=1:

x = 1

最后點擊這個Button,就會打印出 1了。

小結(jié)

以上就是tkinter怎么使用button按鈕的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持W3Cschool


0 人點贊