【问题标题】:i want my code to not work while i click on w,a,s,d keys我希望我的代码在我单击 w、a、s、d 键时不起作用
【发布时间】:2022-01-22 14:16:37
【问题描述】:

我需要我的 python 代码,除非我点击“W,A,S,D”键

我不知道如何使用案例的东西

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, width=400,  height=400)

        self.label = tk.Label(self, text="last key pressed:  ", width=20)
        self.label.pack(fill="both", padx=100, pady=100)

        self.label.bind
        self.label.bind
        self.label.bind
        self.label.bind

        # give keyboard focus to the label by default, and whenever
        # the user clicks on it
        self.label.focus_set()
        self.label.bind("<1>", lambda event: self.label.focus_set())

【问题讨论】:

  • 现在怎么了?
  • “不工作”是什么意思?已经发生了什么,应该如何停止?
  • 我的代码没有问题假设有一个代码运行正常,但我想添加一个结构,使我的代码在我停止按“w”或“a”或“s”之前无法工作" 或 "d" 键
  • 您能否重新表述您的问题以便更好地理解?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python tkinter


【解决方案1】:
import Tkinter as tk
stops = ["W","S","D","A"]
class Example(tk.Frame):
    def __init__(self, parent,stops):
        tk.Frame.__init__(self, parent, width=400,  height=400)

        self.label = tk.Label(self, text="last key pressed:  ", width=20)
        self.label.pack(fill="both", padx=100, pady=100)
 
    #   something like that you need
        for stop in stops:
            if stop == (self.label,parent):
                return
            

        self.label.bind
        self.label.bind
        self.label.bind
        self.label.bind

        # give keyboard focus to the label by default, and whenever
        # the user clicks on it
        self.label.focus_set()
        self.label.bind("<1>", lambda event: self.label.focus_set())
        

【讨论】:

  • __init__() 方法中使用return 将立即结束该方法的执行,它不会等待。此外,return 语句永远不会在此处实际运行:当使用 for stop in stops: 时,stop 将是一个字符串; "W""S""D""A"。因此,if stop == (self.label, parent) 永远不会是 True。另一件事:你只在类初始化时检查按键,所以这段代码只会检查一次按键:在启动时。所以基本上,这段代码并不比 OP 的好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多