【问题标题】:/ operand not working as expected in python 3/ 操作数在 python 3 中没有按预期工作
【发布时间】:2014-10-10 19:04:04
【问题描述】:

我正在阅读基于 python 2 的书 Tkinter GUI Application Development Hotshot,我有这个代码:

from tkinter import *

rows = 5
un = 2
bp = 2
columns = un * bp
root = Tk()
right_frame = Frame(root)
right_frame.pack()
button = [[0 for x in range(columns)] for x in range(rows)]
for i in range(rows):
    for j in range(columns):
        active = False
        color = '#f3f3f3' if (j / bp) % 2 else '#9a72a9'
        button[i][j] = Button(right_frame, bg=color, relief='flat', width=1)
        button[i][j].grid(row=i, column=j)
root.mainloop()

我得到了这个结果: 但我需要这个: .

当我使用 Tkinter 和 python 2 运行它时,Tkinter 可以工作,但是在 python 3 和 tkinter 中运行它时,我得到了意想不到的结果,什么可能导致这种行为?

【问题讨论】:

  • 标题太宽泛了,顺便说一句。
  • 你建议我应该放什么

标签: python python-3.x tkinter python-2.x


【解决方案1】:

差异可能是由于 python 2.x 和 python 3.x 如何处理除法运算符。可以在此处找到冗长的描述:

http://legacy.python.org/dev/peps/pep-0238/

【讨论】:

  • 哇,谢谢这解决了我的问题,我刚刚将 (j / bp) 更改为 (j // bp),现在它可以工作了
【解决方案2】:

对于范围内的 j(列) 将生成 0, 1, 2, 3

j/bp 给出一个真实的结果:0、0.5、1.0、1.5(AFAICT,这是 Python 3.0 中的新功能)

所以 (j/bp) % 2 给出:0, 0.5, 1.0, 1.5

在 Python 2.x 下,我认为整数除法会产生整数结果:

j/bp 给出 0, 0, 1, 1

(j/bp) % 2 给出 0,0,1,1

0 被解释为 False,任何其他数字都被解释为 True

因此您看到的颜色分配以及 Python 2.x 和 Python 3.x 之间的差异

尝试使用 j//bp,它会在 Python 3.x 中给出旧的(整数结果)“地板除法”。

【讨论】:

  • 顺便说一句,与 TKinter 无关!
猜你喜欢
  • 1970-01-01
  • 2012-05-09
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
相关资源
最近更新 更多