【问题标题】:place objects in canvas where clicked using binding python将对象放置在使用绑定python单击的画布中
【发布时间】:2017-11-27 17:08:44
【问题描述】:

我想让一个对象出现在用户单击的 tkinter 窗口中。 我有这个代码:

from tkinter import *

class Storage:

    def __init__(self):
        x = None
        circle = None
        w=None

class Game:

    def Start():
        #make object appear where clicked

root = Tk()

w = Canvas(root, width=200, height=100)
w.pack()

w.bind("<Button-1>", Start)


start = Button(text="Start!", command=Game.Start)
start.pack()

root.mainloop()

任何帮助将不胜感激。

【问题讨论】:

    标签: python canvas tkinter binding


    【解决方案1】:

    首先你应该将画布对象放在框架上,然后将画布绑定到所需的事件

    from tkinter import *
    
    class Storage:
    
        def __init__(self):
            x = None
            circle = None
            w=None
    
    class Game:
    
        def Start(event):
            print("clicked at", event.x, event.y)
            x = event.x
            y = event.y
            w.create_rectangle(x, y, 100, 100, fill="blue")
    
    root = Tk()
    
    
    
    
    frame = Frame(root, width=200, height=200)
    
    frame.pack()
    w = Canvas(frame, width=200, height=100)
    w.pack()
    w.bind("<Button-1>", Game.Start)
    
    root.mainloop()
    

    【讨论】:

    • 将画布放在框架中不会改变任何东西。为什么说框架是必要的?
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多