Home > Enterprise >  Python Tkinter Problem (with global keyword)
Python Tkinter Problem (with global keyword)

Time:08-10

I have given two files in Python:

file1.py:

from file2 import *

root = None

create_window_middle(400, 400)

label1 = tk.Label(root, text="Label 1")
label1.pack()
label2 = tk.Label(root, text="Label 2")
label2.pack()

root.mainloop()

file2.py:

import tkinter as tk

def create_window_middle(x, y):
    global root
    root = tk.Tk()
    geometry_x = x
    geometry_y = y
    monitor_center_x = root.winfo_screenwidth() / 2 - (geometry_x / 2)
    monitor_center_y = root.winfo_screenheight() / 2 - (geometry_y / 2)
    root.geometry("%dx%d %d %d" % (geometry_x, geometry_y, monitor_center_x, monitor_center_y))

Why does this not work? According to my logic, I define the variable root in File1.

Then I call the function create_window_middle, in which I write global root. Thereby I should be able to change the global root object within the function, which I try to do in the next line by overwriting the None with tk.Tk().

But apparently the global variable root in file1 is not overwritten with the tk object. What is the reason for this?

CodePudding user response:

@jasonharper 's comment gives the answer, but I can expand a little.

The global marker makes a variable referenced inside a function refer to the variable of the same name within the module. The module scope is the highest in python, and there is no truly universal global scope.

Please also read the docs about global and how to share variables between modules

You could, for example, have done the following:

import file2
file2.create_window_middle(400, 400)
label1 = tk.Label(file2.root, text="Label 1")
...

CodePudding user response:

Use eval() function:

root.eval('tk::PlaceWindow . center')
root.mainloop()
  • Related