【问题标题】:Convert tuple to int in Python在 Python 中将元组转换为 int
【发布时间】:2017-08-02 15:48:42
【问题描述】:

我是 python 的新手,不明白这个问题的其他答案。为什么当我运行我的代码时,int(weight[0]) 不会将变量“权重”转换为整数。尽量把它弄糊涂,因为我真的很新,仍然不太了解其中的大部分内容。这是我的代码的相关部分

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'

【问题讨论】:

  • 您的问题需要包括您的输出,以及它与您的预期有何不同的描述。如果引发异常,您应该包含完整的回溯。
  • 我将其更改为包含它,尽管我是编码和 stackoverflow 的新手。

标签: python python-3.x tkinter


【解决方案1】:

你要找的是

weight = int(weight[0])

int 是一个返回整数的函数,因此您必须将该返回值分配给一个变量。

如果您正在寻找的是将变量 weight 重新分配为其第一条记录的值,那么该代码应该适合您。

如果该项目已经是一个整数,那么int 调用可能是多余的,你也许可以只用得到它

weight = weight[0]

【讨论】:

  • 只是为了帮助向@Casey Ryan 解释这里发生了什么,weight[0]weight 的一个元素,您将哪个元素插入到 int() 函数中。因此,当您执行weight = int(weight[0]) 时,您将使用weight 的第一个元素覆盖变量weight
【解决方案2】:

我注意到你在这里使用lb.bind("&lt;Double-Button-1&gt;", select)。这确实解决了curselection() 返回最后一个选定列表项的问题,但我想说使用lb.bind('&lt;&lt;ListboxSelect&gt;&gt;', select) 会更好地解决这个问题。绑定到&lt;&lt;ListboxSelect&gt;&gt; 有效,因为此事件在选择更改后触发,当您使用此事件调用curselection() 时,您将获得所需的正确输出。

这里有一段代码提供了&lt;&lt;ListboxSelect&gt;&gt; 事件的示例用法:

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

您会注意到控制台中的打印输出将是单击时当前选择的项目。这样可以避免双击。

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多