首页 > 解决方案 > 为什么我不能在 Python Ktinker 上移动我的下拉列表

问题描述

我希望将下拉菜单移至左上角。但是当我尝试 padx 和 pady 时,什么都没有发生。

我的程序的图像

       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()

标签: pythontkinterbuttonmovepositioning

解决方案


由于默认元素居中,您需要anchor='w'将元素向左移动 ( 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()

在此处输入图像描述

或者您可以使用fill="x"(或fill="both") 将大小调整为全宽

om.pack(fill='x')

在此处输入图像描述

但是还有其他问题-在Text您使用的pady=75情况下,您在 and 之间创建了边距TextOptionMenu并且您需要pady=(75,0)删除下面的边距Text

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

在此处输入图像描述


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()

推荐阅读