【问题标题】:How to create a button inside of a a Tk canvas in python 3.7如何在 python 3.7 中的 Tk 画布内创建一个按钮
【发布时间】:2019-03-21 14:58:28
【问题描述】:

我想知道如何使用 tkinter 模块在画布内放置一个按钮。有人问过这个问题,但这是 5 年前的一个不同版本,所以这对我的情况来说不是很方便,而且我还是一个初学者,所以我只理解了最佳答案中大约 3/4 的代码。这是问题:How to make a Button using the tkinter Canvas widget?

from tkinter import *
root = Tk()
c=Canvas(root,width=200,height=150,bg='blue')
c.pack(side = 'top')

c.create_text(100,50,anchor='c',fill='orange',font='Times 28',text='List')

button = Button(root, text="Quit",command=root.destroy)
button.pack()

mainloop()

当我运行此代码时,它会在我的画布下方而不是在画布上创建按钮。我在 https://docs.python.org/3.7/library/tkinter.html 我正在使用的 IDE 指南上寻求帮助。即使我可能会或可能不会错过某些东西,我也找不到将按钮放在画布上的方法。如果这个问题被认为没有帮助或不必要,我道歉并立即关闭它。

Python 版本: 3.7

级别:初学者

运行代码: IDLE 64 位

操作系统: Windows 10

【问题讨论】:

    标签: python user-interface tkinter tkinter-canvas


    【解决方案1】:

    当您使用pack() 时,tkinter 会将按钮放在它的主(根)上,并且画布绘制的区域已经被占用。

    要将按钮放置在画布上,您应该在画布上使用函数create_window()

    from tkinter import *
    
    root = Tk()
    c = Canvas(root,width=200,height=150,bg='blue')
    c.pack(side = 'top')
    
    c.create_text(100, 50, anchor='c', fill='orange', font='Times 28', text='List')
    
    button = Button(root, text="Quit", command=root.destroy)
    canvas_widget = c.create_window(100, 100, window=button)
    
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      删除 button.pack()

      尝试使用下面的代码

      button = Button(root, text="Quit", command=root.destroy)

      c.create_window(10, 10, anchor=NW, window=button)

      【讨论】:

        猜你喜欢
        • 2012-08-12
        • 2011-10-25
        • 2018-12-17
        • 1970-01-01
        • 1970-01-01
        • 2020-08-29
        • 2023-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多