Search code examples
pythontkinterbuttonmovepositioning

Why cant i move my drop-down list on Python Ktinker


I wish to move my drop down menu to the upper left. But when i try to padx and pady nothing is happening.

image of my program

       global text
       self.text = tk.Text(root, bg='black', foreground="white", height="15")
       self.text.pack(padx=0, pady=75)
       self.text.delete('1.0', tk.END)
       self.text.insert(tk.END, "Opps, not yet connect OR no files to be read....")

       self.variable = StringVar(root)
       self.variable.set("Temperature")  # default value
       self.w = OptionMenu(root, self.variable, "Temperature", "Mazda", "three")
       self.w.pack()

Solution

  • As default elements are centered and you need anchor='w' to move element to the left (west)

    import tkinter as tk
    
    root = tk.Tk()
    
    txt = tk.Text(root, bg='black')
    txt.pack(pady=75)
    
    om_var = tk.StringVar(root, value='Hello')
    om = tk.OptionMenu(root, om_var, 'Hello', 'World')
    om.pack(anchor='nw')   # north, west - top, left
    
    root.mainloop()
    

    enter image description here

    Or you can use fill="x" (or fill="both") to resize to full width

    om.pack(fill='x')
    

    enter image description here

    But there is also other problem - in Text you used pady=75 so you created margin between Text and OptionMenu and you would need pady=(75,0) to remove margin below Text

    txt.pack(pady=(75,0))
    

    enter image description here


    import tkinter as tk
    
    root = tk.Tk()
    
    txt = tk.Text(root, bg='black')
    txt.pack(pady=(75,0))
    
    om_var = tk.StringVar(root, value='Hello')
    om = tk.OptionMenu(root, om_var, 'Hello', 'World')
    om.pack(fill='x')
    
    root.mainloop()