2014-03-02 15 views
0

我正在嘗試創建一個按鈕,該按鈕將根據單選按鈕選擇的選項工作。根據下面的代碼,如果選擇'Option1'單選按鈕,當點擊測試按鈕時應打印出'選擇第一選項'。對於'選項2'單選按鈕'選擇第二選項'應該在單擊測試按鈕時打印出來。但我總是選擇'第一選項'。如果有人可以幫忙。如何通過tkinter中的另一個按鈕識別/使用選定的單選按鈕

from Tkinter import * 

class Select: 
    def __init__ (self, root): 
     self.root = root 
     root.title ('Title') 
     root.geometry ('100x100') 

     button1 = Radiobutton (self.root, text = 'Option 1', command = self.option1, value = 1).place (x = 10, y = 10) 
     button2 = Radiobutton (self.root, text = 'Option 2', command = self.option2, value = 2).place (x = 10, y = 30) 

     test = Button (self.root, text = 'Run', command = self.test).place (x = 10, y = 70) 
     self.root.mainloop() 

    def option1 (self): 
     print ' Option 1'   

    def option2 (self): 
     print ' Option 2' 


    def test (self):   
     if self.option1: 
      print ' 1st option selected' 
     elif self.option2: 
      print '2nd option selected' 
     else: 
      print 'No option selected' 

Select(Tk()).test() 

回答

1

if self.option1:永遠是正確的,因爲你所要求的是self.option1只是是否 - 一個方法指針 - 不爲零。你甚至沒有調用該函數(這將需要名稱後面的圓括號),但如果你是,它會返回print聲明的結果,這不是你想要的結果。在option1()(以及在option2())中需要發生的事情是您設置了一個標誌,可以從函數外部訪問,以指示它已經運行。

例如:

from Tkinter import * 

class Select: 
    def __init__ (self, root): 
     self.root = root 
     root.title ('Title') 
     root.geometry ('100x100') 

     button1 = Radiobutton (self.root, text = 'Option 1', command = self.option1, value = 1).place (x = 10, y = 10) 
     button2 = Radiobutton (self.root, text = 'Option 2', command = self.option2, value = 2).place (x = 10, y = 30) 

     test = Button (self.root, text = 'Run', command = self.test).place (x = 10, y = 70) 
     self.flag = 0 
     self.root.mainloop() 

    def option1 (self): 
     print ' Option 1'   
     self.flag = 1 

    def option2 (self): 
     print ' Option 2' 
     self.flag = 2 

    def test (self):   
     if self.flag == 1: 
      print '1st option selected' 
     elif self.flag == 2: 
      print '2nd option selected' 
     else: 
      print 'No option selected' 

Select(Tk()).test() 
相關問題