如何设置tkinter窗口的位置而不设置尺寸

时间:2017-10-01 07:51:12

标签: python tkinter

我知道在中间放一个tkinter窗口的方法

from tkinter import *
root=Tk()
w=350
h=285
ws=root.winfo_screenwidth()
hs=root.winfo_screenheight()
x=(ws/2)-(w/2)
y=(hs/2)-(h/2)
root.geometry('%dx%d+%d+%d'%(w,h,x,y))   

在上面的代码中,tkinter窗口将在中间弹出,高度为285,宽度为350.但如果我添加了太多小部件,则高度285可能不够。例如,让我们说我们添加了这段代码

for x in range(50):
    Label(root,text=x).pack()

因为我将高度设置为固定数字285,所以前窗口中只有前13个数字。

所以我的问题是有没有办法在屏幕中间放置一个tkinter窗口而不设置高度和宽度,我的意思是如果高度和宽度没有设置为固定数字,窗口将继续自动展开。例如,在下面的代码中,它会自动展开,但窗口不在中间。

from tkinter import *
win=Tk()
for x in range(50):
    Label(win,text=x).pack()

1 个答案:

答案 0 :(得分:5)

您可以从几何规范中省略宽度和高度。例如:

import java.awt.*;
import javax.swing.*;

public class Sorting extends JFrame{

    public Sorting() {

        GridBagConstraints c = new GridBagConstraints();

        //for panel 4
        JPanel results = new JPanel(new GridBagLayout());
        JLabel resultsTitle = new JLabel("Experimental Results");
        JLabel n = new JLabel("N:");
        JLabel dataType = new JLabel("Data Type:");
        JLabel sort = new JLabel("Sort:");
        JLabel comparisons = new JLabel("Comparisons:");
        JLabel movements = new JLabel("Movements:");
        JLabel totalTime = new JLabel("Total Time:");
        JTextField nField = new JTextField(10);
        JTextField dataTypeField = new JTextField(10);
        JTextField sortField = new JTextField(10);
        JTextField comparisonsField = new JTextField(10);
        JTextField movementsField = new JTextField(10);
        JTextField totalTimeField = new JTextField(10);

        c.gridx = 1;
        c.gridy = 6;
        results.add(resultsTitle, c);
        c.gridx = 1;
        c.gridy = 7;
        results.add(n, c);
        c.gridx = 1;
        c.gridy = 8;
        results.add(dataType, c);
        c.gridx = 1;
        c.gridy = 9;
        results.add(sort, c);
        c.gridx = 1;
        c.gridy = 10;
        results.add(comparisons, c);
        c.gridx = 1;
        c.gridy = 11;
        results.add(movements, c);
        c.gridx = 1;
        c.gridy = 12;
        results.add(totalTime, c);

        c.gridx = 2;
        c.gridy = 7;
        results.add(nField, c);
        c.gridx = 2;
        c.gridy = 8;
        results.add(dataTypeField, c);
        c.gridx = 2;
        c.gridy = 9;
        results.add(sortField, c);
        c.gridx = 2;
        c.gridy = 10;
        results.add(comparisonsField, c);
        c.gridx = 2;
        c.gridy = 11;
        results.add(movementsField, c);
        c.gridx = 2;
        c.gridy = 12;
        results.add(totalTimeField, c);
        add(results);
    }

    public static void main(String args[]) {
        Sorting program = new Sorting();
        program.setVisible(true);
        program.setTitle("Sorting Techniques");
        program.setSize(500, 500);
        program.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}