简体   繁体   中英

Label is resizing incorrectly tkinter

This is my first post so be easy on me :) I have a simple python 2.7 script that creates a window using overrideredirect(1) . That all works well and good, the canvas I add works, but when I add a label and apply its height and width, it is severely elongated on both axes. this occurs for both the title bar and quits labels. I want to get them thinner, but I can't use floats. Any ideas what is happening? Here is my code:

from Tkinter import *
from math import *

class Main():
    def __init__(self):
        # Create a basic tkinter window
        self.root = Tk()
        self.canvas = Canvas(self.root, width=700, height=500)
        self.canvas.pack()
        # Start function that creates labels
        self.initiate()
        # Make the window frameless
        self.root.overrideredirect(1)
        self.root.mainloop()

    def initiate(self):
        # Create a single black bar across the top of the window
        # My issue is here. I apply the height of 1, and it displays in the tkinter window of a height more like 10-20.
        # I think it has somthing to do with overrideredirect, but i dont know what it is, i have never used it before.
        self.titlebar = Label(self.canvas, width=700, height=1,
            bg='black')
        self.titlebar.place(x=0, y=0)
        # This and the other functions make the window move when you drag the titlebar. It is a replacement for the normal title bar i removed with overrideredirect.
        self.titlebar.bind("<ButtonPress-1>", self.StartMove)
        self.titlebar.bind("<ButtonRelease-1>", self.StopMove)
        self.titlebar.bind("<B1-Motion>", self.OnMotion)

        # Create a quit button in top left corner of window
        self.quit = Label(self.canvas, width=1, height=1, bg='grey')
        self.quit.place(x=0, y=0)
        self.quit.bind("<Button-1>", lambda event: self.root.destroy())

    def StartMove(self, event):
        self.x = event.x
        self.y = event.y

    def StopMove(self, event):
        self.x = None
        self.y = None

    def OnMotion(self, event):
        deltax = event.x - self.x
        deltay = event.y - self.y
        x = self.root.winfo_x() + deltax
        y = self.root.winfo_y() + deltay
        self.root.geometry("+%s+%s" % (x, y))


Main()

Unless your label has an image, the width and height represents a number of average sized characters based on the font used by the Label. A width of 700 and a height of 1 will likely result in something 6000-7000 pixels wide, and 15-20 pixels tall.

If you're trying to create a border, I recommend using a frame since its width and height parameters are in pixels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM