代码之家  ›  专栏  ›  技术社区  ›  Hoseong Jeon

如何设置按钮的像素大小-python[复制]

  •  2
  • Hoseong Jeon  · 技术社区  · 7 年前

    我使用的是Python3,我想设置一个按钮的像素大小。

    我想让它的宽度=100像素,高度=30像素,但没有成功。

    它比我想象的要大得多。

    这是我的代码:

    from tkinter import *
    
    def background():
        root = Tk()
        root.geometry('1160x640')
    
        btn_easy = Button(root, text = 'Easy', width = 100, height = 50)
        btn_easy.place(x = 100, y = 450)
    
        root.mainloop()
    
    background()
    

    我怎样才能做到?

    1 回复  |  直到 7 年前
        1
  •  5
  •   handle    7 年前

    http://effbot.org/tkinterbook/button.htm

    还可以使用“高度”和“宽度”选项显式设置 大小 如果在按钮中显示文本,这些选项将定义大小 按钮的文本单位 。如果改为显示位图或图像, 它们以像素(或其他屏幕单位)定义大小。 你可以 即使对于文本按钮,也要指定以像素为单位的大小,但这需要 一些魔法。有一种方法可以做到这一点(还有其他方法):

    f = Frame(master, height=32, width=32)
    f.pack_propagate(0) # don't shrink
    f.pack()
    
    b = Button(f, text="Sure!")
    b.pack(fill=BOTH, expand=1)
    

    from tkinter import *
    
    def background():
        root = Tk()
        root.geometry('1160x640')
    
        f = Frame(root, height=50, width=50)
        f.pack_propagate(0) # don't shrink
        f.place(x = 100, y = 450)
    
        btn_easy = Button(f, text = 'Easy')
        btn_easy.pack(fill=BOTH, expand=1)
    
        root.mainloop()
    
    background()
    

    奖励:许多按钮(只是为了得到这个想法)

    from tkinter import *
    
    def sizedButton(root, x,y):
    
        f = Frame(root, height=50, width=50)
        f.pack_propagate(0) # don't shrink
        f.place(x = x, y = y)
    
        btn_easy = Button(f, text = 'Easy')
        btn_easy.pack(fill=BOTH, expand=1)
    
    
    def background():
        root = Tk()
        root.geometry('1160x640')
    
        for x in range(50,350,100):
            for y in range(50,350,100):
                sizedButton(root, x,y)
    
    
        root.mainloop()
    
    background()