2017-08-02 570 views
-2

我是python中的新成員,並且不明白此問題的其他答案。爲什麼當我運行我的代碼時,int(weight[0])沒有將變量「weight」轉換爲整數。儘量減少它,因爲我真的很新,但仍然不太瞭解它。這裏是我的代碼的相關部分在Python中將元組轉換爲int

weight = (lb.curselection()) 
    print ("clicked") 
    int(weight[0]) 
    print (weight) 
    print (type(weight)) 

和繼承人我此腳本代碼

lb = Listbox(win, height=240) 
lb.pack() 
for i in range(60,300): 
    lb.insert(END,(i)) 
def select(event): 
    weight = (lb.curselection()) 
    print ("clicked") 
    int(weight[0]) 
    print (weight) 
    print (type(weight)) 
lb.bind("<Double-Button-1>", select) 

感謝

當我運行的代碼,它與TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' 來了,我希望它而是將「權重」變量轉換爲整數,因此我可以將其用於數學運算。

完全回溯:Traceback (most recent call last): File "C:\Users\Casey\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:/Users/Casey/AppData/Local/Programs/Python/Python36-32/s.py", line 11, in select int(weight) TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

+1

您的問題需要包含您的輸出,並描述它與預期的不同之處。如果發生異常,應該包含完整的回溯。 – skrrgwasme

+0

我改變它包括,謝謝,雖然我是新的編碼和計算器。 –

回答

5

你要找的是什麼

weight = int(weight[0]) 

int是一個函數,返回整數,所以你必須是迴歸到一個變量賦值。

如果你正在尋找的是重新分配變量weight與它的第一個記錄的值,該代碼應該爲你工作。

如果該項目已經是一個整數,則int呼叫可能是多餘的,你也許可以只用

weight = weight[0] 
+0

只是爲了幫助向@Casey Ryan解釋這裏發生了什麼,'weight [0]'是'weight'的元素,你插入'int()'函數的元素。所以當你做'weight = int(weight [0])'時,你只是用'weight'的第一個元素覆蓋變量'weight' –

+0

@DavyM是的,謝謝,這可能會有幫助。 – Stael

0

得到它我注意到你在這裏使用lb.bind("<Double-Button-1>", select)。這確實解決了curselection()返回最後選擇的列表項的問題,但我會說使用lb.bind('<<ListboxSelect>>', select)會更好地工作。綁定到<<ListboxSelect>>的工作原理是因爲此事件在選擇發生變化後觸發,並且當您使用此事件調用curselection()時,您將獲得正在查找的正確輸出。

下面是一些代碼,提供了一個例子使用<<ListboxSelect>>事件:

import tkinter as tk 


class Application(tk.Frame): 

    def __init__(self, parent): 
     tk.Frame.__init__(self, parent) 

     self.parent = parent 
     self.lb = tk.Listbox(self.parent, height=4) 
     self.lb.pack() 
     self.lb.bind('<<ListboxSelect>>', self.print_weight) 
     for item in ["one: Index = 0", "two: Index = 1", "three: Index = 2", "four: Index = 3"]: 
      self.lb.insert("end", item) 

    def print_weight(self, event = None): 
     # [0] gets us the 1st indexed value of the tuple so weight == a number. 
     weight = self.lb.curselection()[0] 
     print(weight) 


if __name__ == "__main__": 
    root = tk.Tk() 
    app = Application(root) 
    root.mainloop() 

你會發現打印出的控制檯將在一個單一的點擊當前選擇的項目。這將防止需要雙擊。