[Solved][Python 3] How to center tkinter window?

Hi.
I need to center window on the screen. The window that already has some contents like labels and buttons. Found this code snippet on Stack Overflow:
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
x = w/2 - rootsize[0]/2
y = h/2 - rootsize[1]/2
root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))
but it doesn't work. It gives me centered window with no width or height when it has some size if I don't use this snippet. What is wrong in this code?
Last edited by Mr. Alex (2012-09-27 08:38:18)

I think the main thing wrong with your code is you were asking for the window size before TK had decided what it should be. Your code works in the interactive interpreter if you run it line by line, but not if you run it all at once.
I adapted some code of my own for you:
from tkinter import Tk
from tkinter.ttk import Label
root = Tk()
Label(root, text="Hello world").pack()
# Apparently a common hack to get the window size. Temporarily hide the
# window to avoid update_idletasks() drawing the window in the wrong
# position.
root.withdraw()
root.update_idletasks() # Update "requested size" from geometry manager
x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
root.geometry("+%d+%d" % (x, y))
# This seems to draw the window frame immediately, so only call deiconify()
# after setting correct window position
root.deiconify()
I think it does what you want, although I have two screens side by side so the window is actually split between the two.

Similar Messages

  • How to center  mx:window Component in adobe air

    Hello Friends
                        i am making a simple application in adobe air 2.0 .In this application i made a seprate window on some button click.but every time it open with random positoning i just want to center that window component.if any body having any idea then please guide me.
    Thanks and regards
       Vineet Osho

    This depends on the type of server from which you are downloading the files. For example, if you are downloading the files from an HTTP server, and the server provides "Last-Modified" values in the HTTP response headers, you could use the following ActionScript code to determine those values:
    var urlReq:URLRequest = new URLRequest("http://www.example.com/");
    var urlStream:URLStream = new URLStream();
    urlStream.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, statusListener);
    urlStream.load(urlReq);
    private function statusListener(event:HTTPStatusEvent):void
        for each(var header:URLRequestHeader in event.responseHeaders)
            if(header.name == "Last-Modified")
                trace(header.value);

  • [Solved] Python CGI - how to "include" like in PHP

    Hi.
    When I code PHP I like to use this template system. A short instance would consist of 2 files: "index.php" and "template.php".
    template.php:
    <?php
    echo "<h1>$header</h1>";
    echo "<p>$text</p>";
    ?>
    index.php:
    <?php
    $header = "this is a header";
    $text = "this is a text";
    include "template.php";
    ?>
    So I can use one template for lots of pages - same layout but different vars.
    I cannot find how to do this in Python CGI.
    page.cgi:
    #!/usr/bin/python
    import os, cgi
    x = "This is the page text."
    eval(open('template.cgi').read())
    template.cgi
    print("Content-type: text/html\n")
    print(x)
    This gives me error 500. I am not surprised, this mail.python.org page says:
    > I can't figure out how one would approach this in Python (i'm using
    > mod_python). There's no equivalent to the "include" function from
    > PHP.
    Correct, the concept doesn't exist because you are working
    with vanilla CGI rather than server scripting.
    But maybe there is a way to make something similar?
    Last edited by Mr. Alex (2012-06-05 17:52:42)

    Template (index.html.tpl)
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Main Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style>
    h1 {{
    margin: auto;
    </style>
    </head>
    <body>
    <h1>Admin</h1>
    <ul>
    <li><a href="{}">Monthly Report</a></li>
    <li><a href="{}">Inventory Zip Files</a></li>
    <li><a href="{}">Order Reports</a> -- Last 7 days</li>
    <li><a href="{}">Notes/TODO/Information</a></li>
    <li><a href="{}">EDI Orders</a></li>
    </ul>
    </body>
    </html>
    index.py :
    #!/usr/bin/env python2
    def main():
    template = "index.html.tpl"
    pages = ("monthly", "zips", "reports", "vimwiki", "edi.py")
    sitename = "/"
    pages = ["{}{}".format(sitename, pages) for i in pages]
    tpl = "".join(open(template,'r').readlines())
    print 'Content-type: text/html\n\n' + tpl.format(*pages)
    if __name__ == '__main__':
    main()
    Maybe not the best way...but it works for me Notice the double {{ }} in the template where you want literal brackets, not placeholders.
    Scott

  • Customer Support - Office Jet 6700 (No HP Solution Center Software windows 7/ windows 8)

    Hi,
    I have been a long supported of hp products.  But when you get a problem, the hp customer support are unable to resolve the issue.  This applies to their first level support.  Their support is overseas and they are not trained well enough to understand what the product does or what the problem is.  I believe it could be a language issue.
    But I asked for my problem to be escalated to an engineer to have the issue resolved.  The girl in the Philippines by the name of Regine stated that someone would call me back with in two hours.  Well we spoke on 7/21/2013 and as of this posting, no one has contacted me.
    I do work for a large software company as a second tier support/engineer.  IF I TOLD THE CLIENT SOMEONE WOULD CALL THEM BACK, I WOULD MAKE SURE SOMEONE DID.
    This is very sad and I doubt that hp is going to resolve this.  Since I did not receive any type of survey, I am sure that this ticket has been swept under the table.
    Thanks

    This is NOT official HP Cutomer Support. This is a peer-to-peer user supported forum for HP consumer class products. HP maintains no official presence on this forum. It is unlikely that HP will respond in an official capacity. Any reply from a HP employee represents their own opinion and not that of HP's.
    Please see HP support document "Windows: How to Get HP Solution Center" for information on downloading the HP Solution Center for Windows 7 and Window 8. According to HP;
    "The HP Solution Center program is part of the Full Feature software and driver package, and cannot be downloaded separately."
    The full featured driver for the HP Officejet 6700 can be downloaded from HP's Officejet 6700 All-in-One Printer Drivers & Downloads page. This driver should include the "HP Solution Center" as noted above.
    Please click the white KUDOS star to show your appreciation
    Frank
    {------------ Please click the "White Kudos" Thumbs Up to say THANKS for helping.
    Please click the "Accept As Solution" on my post, if my assistance has solved your issue. ------------V
    This is a user supported forum. I am a volunteer and I don't work for HP.
    HP 15t-j100 (on loan from HP)
    HP 13 Split x2 (on loan from HP)
    HP Slate8 Pro (on loan from HP)
    HP a1632x - Windows 7, 4GB RAM, AMD Radeon HD 6450
    HP p6130y - Windows 7, 8GB RAM, AMD Radeon HD 6450
    HP p6320y - Windows 7, 8GB RAM, NVIDIA GT 240
    HP p7-1026 - Windows 7, 6GB RAM, AMD Radeon HD 6450
    HP p6787c - Windows 7, 8GB RAM, NVIDIA GT 240

  • How to open new window when i press submit button/submit button.

    Hi,
    When i press a button, I need to capture an item value in current from and I need to pass that value to another form. The child form should open in the new form.
    For that Iam using the java script, But when i use the java script my page is not able to re-size, scroll bars address bar and menu bars are missing. if any one did this kind of requirment please share with me how to solve this issue.
    Thanks

    Re: How to show Popup window in OAF on click of a button
    Thanks
    --Anil
    http://oracleanil.blogspot.com/

  • Mobile Device Center and Windows 8.1 (Enterprise) not working

    After a HD crash i've got a new HD. Had to setup all development tools and so on. And because of a new setup why not over to Windows 8.1?
    Now the problem is that Window 8.1 will not activate WMDC !? I keep saying "a  component is missing"  but no more information.
    Does any body has any idea how to make a connection to my Windows Mobile 6.5 device? (Psion/Symbol Workabout Pro G4)
    thanks

    Please check this
    Howto run Windows Mobile Device Center in Windows 8
    and the last reply in this thread:
    http://answers.microsoft.com/en-us/winphone/forum/sync/cannot-install-windows-mobile-device-center-on/698d9763-1a15-4d4a-8cc3-7e8804b78393
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How do I install windows using BootCamp without cd drive fot the new MBP?

    I need some softwares for my work (modelsim, altera, ltspices etc) but some of them only supports windows.
    New MBP doesnt seem to have a cd driver.
    How do I install windows using bootcamp without cd drivers?

    You can use a USB thumbdrive to do this, assuming you have access to a windows machine to format the usb stick.
    I installed Win7 on my MB Air (2011), which of course lacks a DVD drive altogether, using this technique.
    Basically, you download a tool called rEFIt to your macbook. ( http://sourceforge.net/projects/refit/files/rEFIt/0.14/rEFIt-0.14.dmg/download ) When this is installed, it gives you a boot selector menu when you boot the Macbook ('Do you want to boot to MacOS or to the USB drive?')
    Then you download and run an Apple tool called Boot Camp Assistant, which allows you to partition your HD for the two operating systems to share; it also pulls down all the windows drivers you need.
    Then prep the USB thumbdrive on a windows machine to be a Win7 installer disk. You'll want a drive in the 4gb+ range I think. You have to set up the thumbdrive to be bootable (lots of tools for that available), and then copy all the windows installation files over to it.
    Put the thumbdrive in the macbook and boot holding down the option key.
    Choose the rEFIt icon on boot, then choose to boot from the thumbdrive, then format your new windows partition to something Win7 can handle, and install windows.
    On my machine I followed a slightly more involved process and wiped out MacOS entirely. I would have kept it on a small partition if I'd had a bigger hard drive.
    If you need super detailed instructions, CNET has some here:
    http://howto.cnet.com/8301-11310_39-20020513-285/install-win-7-on-macbook-air-fr om-a-usb-drive/
    Tech-Recipes has some similar instructions here:
    http://www.tech-recipes.com/rx/9136/macbook-air-install-windows-7-with-boot-camp -without-an-external-dvd-drive/
    If you have any issues after trying this, ping me and I may have solved them when I went through the same process.

  • How Do I Run Windows 8 On My MBP

    Hi,
    How do I run Windows 8 Pro(64-bit) on my (17-inch mid-2010)MBP?
    The Boot Camp 5.0 will support Windows 7/8 64-bit is wrong.
    I have installed the Windows 8 Pro and Boot Camp 5.0.5033 and still cannot "Update the Windows".
    Any suggestions?
    Thanks in advance.
    Ed

    You are doing something wrong. Continued posting about it does not work or the instructions are wrong will not solve your issue. You must stick to one thread and describe better what you did and how your sytem is configured. Exact and complete error messages will help. In one thread you said you have three OSs. If so, please explain how you did this since Bootcamp will not work with multple partitions.

  • How can I install windows 7 on MBA

    HI ,
    Can some one help me to solve how can I install Windows 7 64 bits on my Macbook air 13" on Max OS X Mavericks
    I tried to follow what they recomend bout bothing happend
    Boot camp assistance does help me anything. I don't know why it is so complicate and verry tricky

    Follow the instructions in the manual >  manuals.info.apple.com/MANUALS/1000/MA1636/en_US/boot_camp_install-setup_10.8.p df

  • Envy dv6 notebook - Hard drive failure - How do I get windows 8 reloaded on my Notebook

    Hard drive failed in the notebook / laptop. How do I get windows 8 back on the new drive? Hp told me they will not send or sell me recovery disks. WHat kind of crap is that?
    Help!

    Once one is out of warranty HP is not obligated to send recocovery media for free. Owners have a responsibility to create the recovery media shortly after removing their notebook during the inital product setup.
    You can purhase the recovery media from HP here.
    The BIOS does hold the product code for Windows 8, so that is a non issue. 
    ****Please click on Accept As Solution if a suggestion solves your problem. It helps others facing the same problem to find a solution easily****
    2015 Microsoft MVP - Windows Experience Consumer

  • How to open a window in full screen mode using lf_fpm_navigation?

    Hi Guys
    For the following applications
    ESS Application: HAP_START_PAGE_POWL_UI_ESS
    MSS Application: HAP_START_PAGE_POWL_UI_MSS
    When the user clicks on the appraisal document name, a seperate window(not full screen) is generated to display the Appraisal docuemnt.
    The code is as follows:
    COMP: HAP_START_PAGE_POWL_UI
    Object : COMPONENTCONTROLLER
    Method: FOLLOWUP_POWL
    Generate the URL to be called.
        CALL METHOD cl_wd_utilities=>construct_wd_url
          EXPORTING
            application_name = 'HAP_MAIN_DOCUMENT'
            in_parameters    = lt_parameters
          IMPORTING
            out_local_url    = l_url.
        wd_this->url = l_url.
        wd_this->display_document( ).
    In Method: DISPLAY_DOCUMENT
    lv_alias = 'EMPLOYEE_DOCUMENT_UI_OBN'.
    use FPM navigation
        ls_nav_key-key1 = 'HAP'.
        ls_nav_key-key2 = 'HAP_GENERIC_UI'.
        lr_fpm_navigation ?= lr_fpm->get_navigation( is_key = ls_nav_key iv_instance_sharing = abap_false ).
        CALL METHOD lr_fpm_navigation->get_key_from_alias
          EXPORTING
            iv_alias = lv_alias
          RECEIVING
            rv_key   = lv_key.
        lr_fpm_navigation->modify_parameters(
             EXPORTING
               id_target_key            = lv_key
               it_application_parameter = lt_appl_param
               it_business_parameter    = lt_business_param    ).
        lr_fpm_navigation->navigate( lv_key ).
    Any idea how to open this window in full screen?
    Highly appreciate your help.
    Thank and Regards
    Pramod

    Hi Pramod,
    This FPM navigation is achieved using settings made in Launchapd Customizing ( LPD_CUST ).
    a) Execute Tran LPD_CUST
    b) Go to Role HAP - Double Click to open it.
    c) Open the second folder on the LHS menu - there you will find 2 entries
    d) Click on second entry - in the entry setting you can see that it is configured for WD Application  - HAP_MAIN_DOCUMENT
    e) Click on button Show Advanced Parameters
    f) There you will find a input box named as Window Features - here you can specify window features like
    height=700,width=1100,position=center,menu=no,status=no,location=no,menubar=no,status=no,toolbar=no
    save the settings come out and test ur app again.
    change the height and width and other features as per ur req.
    Regards
    Manas Dua

  • How to create a window with its own window border other than the local system window border?

    How to create a window with its own window border other than the local system window border?
    For example, a border: a black line with a width 1 and then a transparent line with a width 5. Further inner, it is the content pane.
    In JavaSE, there seems to have the paintComponent() method for the JFrame to realize the effect.

    Not sure why your code is doing that. I usually use an ObjectProperty<Point2D> to hold the initial coordinates of the mouse press, and set it to null on a mouse release. That seems to avoid the dragging being confused by mouse interaction with other nodes.
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.collections.FXCollections;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Point2D;
    import javafx.geometry.Pos;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.ChoiceBox;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.AnchorPane;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBox;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    import javafx.stage.Window;
    public class CustomBorderExample extends Application {
      @Override
      public void start(Stage primaryStage) {
      AnchorPane root = new AnchorPane();
      root.setStyle("-fx-border-color: black; -fx-border-width: 1px; ");
      enableDragging(root);
      StackPane mainContainer = new StackPane();
        AnchorPane.setTopAnchor(mainContainer, 5.0);
        AnchorPane.setLeftAnchor(mainContainer, 5.0);
        AnchorPane.setRightAnchor(mainContainer, 5.0);
        AnchorPane.setBottomAnchor(mainContainer, 5.0);
      mainContainer.setStyle("-fx-background-color: aliceblue;");
      root.getChildren().add(mainContainer);
      primaryStage.initStyle(StageStyle.TRANSPARENT);
      final ChoiceBox<String> choiceBox = new ChoiceBox<>(FXCollections.observableArrayList("Item 1", "Item 2", "Item 3"));
      final Button closeButton = new Button("Close");
      VBox vbox = new VBox(10);
      vbox.setAlignment(Pos.CENTER);
      vbox.getChildren().addAll(choiceBox, closeButton);
      mainContainer.getChildren().add(vbox);
        closeButton.setOnAction(new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            Platform.exit();
      primaryStage.setScene(new Scene(root,  300, 200, Color.TRANSPARENT));
      primaryStage.show();
      private void enableDragging(final Node n) {
       final ObjectProperty<Point2D> mouseAnchor = new SimpleObjectProperty<>(null);
       n.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            mouseAnchor.set(new Point2D(event.getX(), event.getY()));
       n.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            mouseAnchor.set(null);
       n.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            Point2D anchor = mouseAnchor.get();
            Scene scene = n.getScene();
            Window window = null ;
            if (scene != null) {
              window = scene.getWindow();
            if (anchor != null && window != null) {
              double deltaX = event.getX()-anchor.getX();
              double deltaY = event.getY()-anchor.getY();
              window.setX(window.getX()+deltaX);
              window.setY(window.getY()+deltaY);
      public static void main(String[] args) {
      launch(args);

  • Disabling special alerts in the "Change Action Center settings" window

    Hi
    In Windows 8.1 Update, I noticed that, in the "Change Action Center settings" window in the "Control Panel", the "Microsoft Account", "Windows Activate", "Windows Backup" and "Apps launcher" alerts
    can not be disable even with a local account of Administrators type. How come? What is the meaning of these alerts? How do I disable them?
    Thanks
    Bye
    Balubeto

    Hi,
    Please know that these options inform you of any issues with them if you have gotten them setup. If you haven't set up them, the option appeared to be grey.
    Once they are grey, no such alerts will display about them.
    Kate Li
    TechNet Community Support

  • How to check a window is open in another jsp

    Hi everyone,
    i have a tricky question trying to solve this..
    in jsp1,"onClick" of link im opening in a new window
    href="#" onclick="JavaScript:popupOpen('<%=URLString%>','winName1');"><%=strName%></a>
    function popupOpen(winURL,winName) {
    winName1 = window.open(winURL,winName);
    in jsp1or jsp2 or jsp3 i have a logout link at the top of the page,when i click logout link in any jsp it redirects to logout page and i also want the window which is opened to goto logout page with URL.
    how can i do this,
    how to check a window is open or not in another jsp and if that window is open open with logout URL.
    Help needed
    Advance Thanks to all

    vveena123 wrote:
    can u explain what the below code does?Isn't it self-explaining? Geesh. Move on to a Javascript forum. Now.
    where to mention it??At the moment that you want to open the window and at the moment that you want to close the window. Isn't that obvious enough?

  • How to center the content in crystal report viewer?

    open crystal report viewer in winform, default at the left top
    after maxmium the winform window, content become at the center
    another odd thing is that i set window winform size 1208*1024 and crystal report view is fill
    then tried, content is not center any more
    How to center the content in crystal report viewer in code?
    Edited by: Mathew_666 on Oct 6, 2011 5:20 AM

    Since there is no control for center you'll need to do the math on your own. This is just a rough draft, but you'll get the idea.
    One of the things you'll need to figure out is your buffer to help you give a centered feel. We'll say that value is 50 in this case.
    Height
    int buffer = 50;
    int formHeight = 1000; // we'll assume a height of 1000 in this case
    int crystalTop = buffer;
    int crystalViewerHeight = formHeight - (buffer * 2); // buffer is at the top and bottom
    Width
    int formWidth = 1000; // we'll assume a width of 1000 in this case
    int crystalLeft = buffer;
    int crystalViewerWidth = formWidth - (buffer * 2); // buffer is at the top and bottom

Maybe you are looking for

  • Convert rtf, pdf or doc file to xml or html

    I'm using RichTextEditor from Flex, but I need to upload a .doc, .pdf or .rtf file into RichTextEditor. Or maybe a way to convert these files to xml or html.... please can you help me??

  • Cant play tv shows on ipad after downloading just get a black screen

    My first generation ipad will not play tv shows that I have purchased from Itunes. Once they are downloaded on to the ipad I just get a black screen when I try to play them. If I restore the ipad I can SOMETIMES watch them for a short while before it

  • Exchange Activesync, messages replied or forwarded are not marked

    I notice with the iPhone that when I reply or forward a message it is not marked on the server as such. So when returning to the office and browsing my messages it can be sometimes difficult to evaluate my status of inbox emails. Activesync does have

  • Material Posting for Refurbishment order

    Hii MM Gurus, I am going to take external service for making repair of the pump. For repair i am going to send pump & some bearing out for repair of the pump. I am following the process as follows which is out of SAP (Not yet configured). The process

  • Window menu is missing in DW CS5 Mac

    I need to open the behaviors panel and I can't get to it. My window menu is missing. I have no idea how long it has been missing - I never open new panels. But, now I need it! Help! Here is a screenshot, it should be bestween Site and Help. How can i