【问题标题】:Can anyone help me make this code more simple and not so lengthy?谁能帮我让这段代码更简单而不那么冗长?
【发布时间】:2019-03-19 03:59:05
【问题描述】:

**我正在尝试制作一个刽子手游戏,但我觉得这可以更简单地编写任何建议?

buttonb = tkinter.Button(bg="blue", text = "B", width=2,command=ex)
buttonb.pack(side="left")
buttonc = tkinter.Button(bg="blue", text = "C",width=2, command=ex)
buttonc.pack(side="left")
buttond = tkinter.Button(bg="blue", text = "D", width=2,command=ex)
buttond.pack(side="left")

【问题讨论】:

  • 遍历字母列表并将按钮存储在列表/字典中。如有必要,使用ordchr 创建字母表。

标签: python tkinter


【解决方案1】:

正如@meowgoesthedog 建议的那样,一个简单的循环就是你的答案。

import string
buttons = {}

for letter in string.ascii_uppercase:
    buttonb = tkinter.Button(bg = "blue", text = letter, width = 2,command = ex)
    buttonb.pack(side = "left")
    buttons[letter] = buttonb

【讨论】:

    【解决方案2】:

    您可以使用循环来迭代字母,并且由于按钮属于一起,它们可以存储在像列表这样的数据结构中。

    buttons = []
    for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
        button = tkinter.Button(bg="blue", text = letter, width=2,command=ex)
        button.pack(side="left")
        buttons.append(button)
    

    如果您愿意,请随意使用列表推导式。

    【讨论】:

      猜你喜欢
      • 2011-05-03
      • 2019-08-28
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2017-02-23
      • 2022-12-06
      • 2020-08-13
      相关资源
      最近更新 更多