Home > Software design >  How do I change the tkinter window size using variables?
How do I change the tkinter window size using variables?

Time:08-17

I am a beginner in coding using python. I made a code that will check a .txt file for text, the code will check for the sentence "gui: window> size? (dimension specified by user)", using if statements, the code will set the GUI size to the dimensions which were entered in the .txt file. This code is placed inside a function.

Here is the code

from tkinter import *
try:
    def Lang(Syntax):
        root = Tk()
        if "gui:" in Line:
            if "window>" in Line:
                removed, data = Line.split("> ")
                removed = ""
                if "size?" in Line:
                   remove, raw_dimension = Line.split("?")
                   remove = ""
                   width, height = raw_dimension.split(",")
                   width = int(width)
                   height = int(height)
                   root.geometry(width, height)
                   root.mainloop()
except:
    pass
file = open(r"C:\Users\youss\Desktop\Zoik\\Zoik.txt", "r").readlines()

for Line in file:
    Lang(Line)

This is the error I get

Traceback (most recent call last):
  File "C:\Users\youss\AppData\Local\Temp\tempCodeRunnerFile.python", line 22, in <module>
    Lang(Line)
  File "C:\Users\youss\AppData\Local\Temp\tempCodeRunnerFile.python", line 15, in Lang
    root.geometry(width, height)
TypeError: wm_geometry() takes from 1 to 2 positional arguments but 3 were given

Here is the sentence in the .txt file

gui: window> size? 500 , 400

I want to be able to use the variables to set the GUI geometry

CodePudding user response:

You can use a regular expression to easily accomplish this

import tkinter as tk, re


root = tk.Tk()

#represents your data
data  = 'gui: window> size? 500 , 400'

#regex with the data you want in groups 
parse = re.compile(r'^gui: window> size\? (\d ) , (\d )$')

#format groups to geometry expectations
root.geometry('{}x{}'.format(*parse.match(data).groups()))

root.mainloop()
  • Related