im having some trouble to create new GUI using python Tkinter module.

from Tkinter import *
import Tkinter as tk
import tkMessageBox
import tkFont

class GUIFramework(Frame):
    """This is the GUI"""
    def __init__(self,master=None):
        self.master.title("Lab Management Hosts")

        self.costumFont = tkFont.Font( family = "Helvetica", size=30, weight="bold")
        label = tk.Label(master, text = "Lab Mangement Application", font = self.costumFont)
        label.pack(padx=0, pady=0)
        #self.app_name = Label(self,text="Lab Management", font= ("Helvetica",20))

    def CreateWidgets(self):
           self.check_hosts = Button(self, text="Check Ping to hosts", font = ("Helvetica",10))
if __name__ == "__main__":
    guiFrame = GUIFramework()

im new to python Tkinter and all i've used in this code is from google.
the main problem is that im not able to move the text where i want.
the text is always on the center of the screen.

i've tried to use Label, tried to use other options as anchor,side, etc.
nothing is worked for me.

im not quite sure what is the difference between the locations parameters in pack() or grid() but i've tried both of them and still cant do that.

in this code, currently im getting
first line "first_command" on the center of the row
and under it another line of the "application name" once again on center.

how do i choose the location of the texts, buttons, pictures im using?
why does padx,pady (i'ev also tried row,column,ipadx,ipady) doesnt work?
the lable text defined as (0,0), why he is located in the center of the screen?

any help will be appriciated.


Recommended Answers

All 5 Replies

I would suggest you start with grid which allows you to specify a row and column. This is a tic-tac-toe program that uses a 3X3 grid to place the buttons.

rom Tkinter import *
from functools import partial

class TicTacToe:
   def __init__(self, top):
      self.top = top
      self.button_dic = {}     ## pointer to buttons and StringVar()
      self.X_O_dict = {"X":[], "O":[]}  ## list of "X" and "O" moves
      self.top.title('Buttons TicTacToe Test')
      self.top_frame = Frame(self.top, width =500, height=500)
      self.top_frame.grid(row=0, column=1)

      exit = Button(self.top_frame, text='Exit', \
             command=self.top.quit).grid(row=10,column=0, columnspan=5)

      self.player = True   ## True = "X", False = "O"

   def buttons(self):
      """ create 9 buttons, a 3x3 grid
      for j in range(1, 10):
         self.button_dic[j] = StringVar()
         b = Button(self.top_frame, textvariable = self.button_dic[j], \
                    command=partial(self.cb_handler, j))
         b.grid(row=b_row, column=b_col)

         b_col += 1
         if b_col > 2:
            b_col = 0
            b_row += 1

   def cb_handler( self, square_number ):
      print "cb_handler", square_number
      if self.player:                       ## True = "X", False = "O"
         player = "X"
         player = "O"

      ##--- square not already occupied
      if square_number not in self.X_O_dict["X"] and \
         square_number not in self.X_O_dict["O"]:

         print player, 
         self.player = not self.player
         print "Occupied, pick another"

   def check_for_winner( self, list_in ):

      winner_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], \
                     [1, 4, 7], [2, 5, 8], [3, 6, 9], \
                     [1, 5, 9], [3, 5, 7]]
      for winner in winner_list:
         if set(winner).issubset(set(list_in)):
            print 'Is A Winner *****'

root = Tk()
print BT.X_O_dict

Nice work wooeee!

Few nit pits though:
The [] has automatic line continuation and so the ugly \ are not needed at line 60-61 and you have accidentaly dropped first letter of your code ( from became rom ).

Maybe also to name BT as bt as it is an instance variable...

Lastly for my taste those ##------- comments are bit on excessive side.

Hope you do not mind these small points of mine.


thanks for the reply!

i've tried to use the grid, but its seems that there is a basic things over there which i dont understand.

i've tried this little code, which supposed only to print big headline on the first line at the center of the screen.

from Tkinter import *
import Tkinter as tk
import tkMessageBox
import tkFont

class GUIFramework(Frame):
    def __init__(self,master=None):
        self.master.title("Lab Management Hosts")

        #"Big Title on the first rot at the center)
        costumFont = tkFont.Font( family = "Helvetica", size=30, weight="bold")
        label = tk.Label(self, text = "Lab Mangement Application", font = costumFont)
if __name__ == "__main__":
    guiFrame = GUIFramework()

using the "self.grid(row,column)" i wanted to define the size of the application screen.
and than i've wrote some message and using the "label.grid(row,column) i wanted to defined where do i put this message on the screen.

what im getting is a small screen with the line on the upper left corner.
actually after i've erased all the pack() phrases no metter which size im writing on the grid nothing is changed.

im trying to write it using OOP so it will be used for further issues.

do you have what am i doing wrong?

thanks a lot


To start with you have to have a root or main or whatever window, and pass it to the class if the Tk() class is called outside of your class, where is will be named "master" because that is what __init__() receives.
root = Tk()

Note that "center of the screen" depends on the size of the screen so you will have to place that yourself. Tkinter makes some assumptions of course, which affects the final layout, so to be really precise you will have to use one container for each line of widgets and place them in the container how you want. I doubt anyone here has the time to be anyone's intro tutor so you will have to find some resources on the web. In addition to the link above there is http://www.ferg.org/thinking_in_tkinter/index.html and http://www.cs.mcgill.ca/~hv/classes/MS/TkinterPres/ You might also want to install the PMW extension to Tkinter as it allows you to align labels and easily create buttons among many other things. A simple example follows

from Tkinter import *

class GUIFramework():
    def __init__(self,master=None):

      ## set the title of the main window
      master.title("Lab Management Hosts")

      ## set the size of the master window

      ## add a frame as a container
      top_frame = Frame(master)

      ## add label to the frame

      label1 = Label(master, text = " ")   ## spacer

      label = Label(master, text = "Lab Mangement Application")
      label.grid(row=1,column=2, columnspan=5)

if __name__ == "__main__":
    guiFrame = GUIFramework(root)

Here is the classy way I prefer ...

# Tkinter with class (preferred template syntax)
# create a label with font and color

    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

class MyApp(tk.Tk):
    def __init__(self):
        # the root will be self
        self.title("Lab Management Hosts")
        # use width x height + x_offset + y_offset (no spaces!)
        # or set x, y position only

    def createWidgets(self):
        mytext = "Lab Mangement Application"
        myfont = ('times', 36, 'bold')
        # create a label showing mytext using myfont
        # red characters on yellow background
        label = tk.Label(self, text=mytext, font=myfont, 
            fg='red', bg='yellow')
        label.grid(row=0, column=0, padx=10, pady=10)
        # optional quit button using destroy (does not bother IDLE)
        self.bt_quit = tk.Button(self, text="quit", command=self.destroy)
        self.bt_quit.grid(row=1, column=0, padx=10, sticky='e')

app = MyApp()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.