婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > 解決Tkinter中button按鈕未按卻主動執行command函數的問題

解決Tkinter中button按鈕未按卻主動執行command函數的問題

熱門標簽:江西省地圖標注 沈陽人工外呼系統價格 沈陽外呼系統呼叫系統 武漢外呼系統平臺 沈陽防封電銷卡品牌 富錦商家地圖標注 池州外呼調研線路 如何申請400電話費用 外呼系統哪些好辦

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

程序剛運行,尚未按下按鈕,但按鈕的響應函數卻已經運行了

例如下面的程序:

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()

程序剛一運行,就出現下面情況:

六個按鈕都沒有按下,但是command函數卻已經運行了

后來通過網上查找,發現問題原因是command函數帶有參數造成的

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

若要給函數傳遞參數,需要在函數前添加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按鈕組件調用一個傳入參數的函數

這里我們要使用python的lambda函數,lambda是創建一個匿名函數,冒號前是傳入參數,后面是一個處理傳入參數的單行表達式。

調用lambda函數返回表達式的結果。

首先讓我們創建一個函數fun(x):

def fun(x):
    print x

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

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

下面讓我們創建一個變量x=1:

x = 1

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

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • 關于Python Tkinter Button控件command傳參問題的解決方式
  • Python的Tkinter點擊按鈕觸發事件的例子
  • Python 窗體(tkinter)按鈕 位置實例

標簽:株洲 呂梁 通遼 潛江 常德 阿里 黑龍江 銅川

巨人網絡通訊聲明:本文標題《解決Tkinter中button按鈕未按卻主動執行command函數的問題》,本文關鍵詞  解決,Tkinter,中,button,按鈕,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《解決Tkinter中button按鈕未按卻主動執行command函數的問題》相關的同類信息!
  • 本頁收集關于解決Tkinter中button按鈕未按卻主動執行command函數的問題的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 乐山市| 台南县| 安西县| 乃东县| 舒城县| SHOW| 都安| 平湖市| 多伦县| 华蓥市| 瑞金市| 华亭县| 定安县| 奈曼旗| 韩城市| 郸城县| 无锡市| 淅川县| 峡江县| 云林县| 翼城县| 田阳县| 峨山| 叶城县| 红安县| 宁明县| 同心县| 杭锦后旗| 岳阳县| 玉林市| 驻马店市| 贡嘎县| 英山县| 阜阳市| 朔州市| 潮安县| 晋江市| 文化| 云阳县| 杭锦旗| 东乌珠穆沁旗|