【问题标题】:How to make Tkinter button to be placed in particular position?如何使 Tkinter 按钮放置在特定位置?
【发布时间】:2016-07-19 20:50:33
【问题描述】:

我是 python 新手,所以我试图制作一个 GUI,因为我必须在特定位置放置一个按钮。

我尝试使用self.nxt_form.place(x=200,y=100) 而不是self.nxt_form.pack()。

但是按钮消失了,运行时只出现了框架。您能告诉我如何将按钮放置在特定位置吗?

代码如下:

import tkinter as tk

class Main_form:
def __init__(self, root,title="Simulated MTBF"):
self.root = root
    self.frame = tk.Frame(self.root)
    """Button nxt_form which moves to next form"""
    self.nxt_form = tk.Button(self.frame, text = 'Next Form', width = 25,command = self.new_window)
    self.nxt_form.pack()
    self.frame.pack()
     """command to open new window by clicking Button """
def new_window(self):
    self.newWindow = tk.Toplevel(self.root)
    self.app = Demo2(self.newWindow)

 class Demo2:
        def __init__(self, root):
    self.root = root
    self.frame = tk.Frame(self.root)
    self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
    self.quitButton.pack()
    self.frame.pack()
def close_windows(self):
    self.root.destroy()

def main(): 
root = tk.Tk()
app = Main_form(root)
root.mainloop()

if __name__ == '__main__':
main()

【问题讨论】:

  • 需要放在什么“特定位置”? 200,100有什么神奇之处?避免使用place 通常是个好主意,因为它不能很好地处理不同的字体、不同的分辨率或不同的窗口大小(除非你完全了解它的所有选项)。

标签: python eclipse user-interface python-3.x tkinter


【解决方案1】:

当我使用 tkinter 时,我使用列和行来定位对象

self.btn = tk.Button(self, text = "button")
self.btn.grid(row = 1, column = 1)

编辑 - 扩展信息以回应评论(下)

我会制作一个标签并更改它的宽度和高度以制作您需要的间距(注意我也是 python 的初学者,所以这可能是一个不好的方法,但它有效)

from tkinter import *
import tkinter as tk
from tkinter.ttk import Combobox,Treeview,Scrollbar

class MainMenu(Frame):
    def __init__(self, master):
        """ Initialize the frame. """
        super(MainMenu, self).__init__(master)
        self.grid()
        self.create_GUI()

    def create_GUI(self):
        frame1 = tk.LabelFrame(self, text="frame1", width=300, height=130, bd=5)
        frame1.grid(row=0, column=0, columnspan=3, padx=8)
        #the frame is not needed but it is a good thing to use as can group
        #parts of your interface together

        self.text1 = Entry(frame1)
        #note if you were not using frames would just put self here
        self.text1.grid(row = 1, column = 0)

        self.text2 = Label(frame1, text = "",height = 10)
        self.text2.grid(row = 2 , column = 0)

        self.text3 = Entry(frame1)
        self.text3.grid(row = 3, column = 0)



root = Tk()
root.title("hi")
root.geometry("500x500")
root.configure(bg="white")
app = MainMenu(root)
root.mainloop()

另外请注意,您不能同时使用包和网格,您可以将对象分组到不同的框架中,然后在一个框架中使用网格并在不同的框架中打包。我个人更喜欢使用 grid 来打包,因为它可以让您更好地控制您的对象,然后打包

【讨论】:

  • 但是我仍然得到相同的输出,它不是按顺序排列的。所以你能把它做成完整的代码吗。这样我就可以很容易理解了。提前谢谢
  • 我运行它时弹出的错误是什么所以将取决于我如何复制和粘贴它
  • 刚刚检查了代码的复制和粘贴版本,我忘记添加导入,复制和粘贴时忘记缩进,现在已修复
猜你喜欢
  • 1970-01-01
  • 2019-11-28
  • 2015-08-18
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 2013-03-27
  • 2018-05-05
  • 1970-01-01
相关资源
最近更新 更多