TKinter - AttributeError when trying to destroy a button - python

Greetings Stack Overflowers!
Please note that I'm a novice and I'm just learning.
I'm having the following error : AttributeError: '_tkinter.tkapp' object has no attribute 'button_draw'
The main logic where the issue seems to be is located in start_game_event. Basically if the game_type is with draw, then the button must be created. However, if a new game is made based on the current windows and the button still exists, I want it to be removed. I'm not sure if there's another way to go about it, for instance regenerating the main frame completely but that's where I'm standing.
Here's the code :
from tkinter import Button, E, Frame, IntVar, Label, LEFT, messagebox, N, NE, Radiobutton, RIGHT, S, SW, StringVar, Tk, Toplevel, W
class DominoWindow(Tk):
def __init__(self):
super().__init__()
self.nb_players_var = None
self.type_partie = None
self.title('Jeu de Pydomino!')
self.resizable(width=False, height=False)
self.frame_player_north = Frame(self)
self.frame_player_west = Frame(self)
self.frame_table = Frame(self, borderwidth=2)
self.frame_player_est = Frame(self)
self.frame_current_player = Frame(self)
self.frame_player_north.grid(row=0, column=1)
self.frame_player_west.grid(row=1, column=0)
self.frame_table.grid(row=1, column=1)
self.frame_player_est.grid(row=1, column=2)
self.frame_current_player.grid(row=2, column=1)
self.label_name_player_north = Label(self.frame_player_north)
self.label_name_player_north.grid(row=0)
self.label_hand_player_north = Label(self.frame_player_north)
self.label_hand_player_north.grid(row=1)
self.label_name_player_west = Label(self.frame_player_west)
self.label_name_player_west.grid(row=0)
self.label_hand_player_west = Label(self.frame_player_west)
self.label_hand_player_west.grid(row=1)
self.label_table = Label(self.frame_table, height=8, width=100)
self.label_table.grid(row=0, column=0)
self.label_name_player_east = Label(self.frame_player_est)
self.label_name_player_east.grid(row=0)
self.label_hand_player_east = Label(self.frame_player_est)
self.label_hand_player_east.grid(row=1)
self.label_name_current_player = Label(self.frame_current_player)
self.label_name_current_player.grid(row=1)
self.frame_hand_current_player = Frame(self.frame_current_player)
self.button_quit = Button(self, text="Quitter", command=self.quit_party_event)
self.button_quit.grid(row=3, column=2)
self.button_new_game = Button(self, text="Nouvelle partie", command=self.introduction_game)
self.button_new_game.grid(row=2, column=2)
self.introduction_game()
def show(self):
if self.nb_players_var.get() == 2:
self.label_name_player_north.config(text="Player 0")
self.label_hand_player_north.config(text="[|]" * 6) #len(self.partie.donnes[self.partie.tour+1]))
self.label_table.config(text="VARIABLE_TABLE")
self.label_name_current_player.config(text="Player Current")
self.label_name_player_east.config(text="")
self.label_hand_player_east.config(text="")
self.label_name_player_west.config(text="")
self.label_hand_player_west.config(text="")
elif self.nb_players_var.get() == 3:
self.label_name_player_north.config(text="Player 0")
self.label_hand_player_north.config(text="[|]" * 6) #len(partie.Partie.donnes[partie.tour+1]))
self.label_name_player_east.config(text="Player 1")
self.label_hand_player_east.config(text="[|]\n" * 6) #len(self.partie.donnes[self.partie.tour+2]))
self.label_table.config(text="VARIABLE DU PLATEAU")
self.label_name_current_player.config(text="Player Current")
self.label_name_player_west.config(text="")
self.label_hand_player_west.config(text="")
elif self.nb_players_var.get() == 4:
self.label_name_player_north.config(text="Player 0")
self.label_hand_player_north.config(text="[|]" * 6) #len(self.partie.donnes[self.partie.tour+1]))
self.label_name_player_east.config(text="Player 1")
self.label_hand_player_east.config(text="[|]\n" * 6) #len(self.partie.donnes[self.partie.tour+2]))
self.label_name_player_west.config(text="Player 3")
self.label_hand_player_west.config(text="[|]\n" * 6) #len(self.partie.donnes[self.partir.tour+3]))
self.label_table.config(text="VARIABLE_DU_PLATEAU")
self.label_name_current_player.config(text="Player Current")
def introduction_game(self):
self.introduction_window_game = Toplevel(self, height=200, width=500)
self.introduction_window_game.title("Choose your game settings!")
self.introduction_window_game._root().lift()
self.nb_players_var = IntVar()
self.type_partie = StringVar()
# Label(self.introduction_window_game, text="Choose your game settings!").pack()
Label(self.introduction_window_game, text="\nWhat kind of game do you want?").pack()
Radiobutton(self.introduction_window_game, text="Game without draw",
variable=self.type_partie, value="without draw").pack(anchor=W)
Radiobutton(self.introduction_window_game, text="Game with draw",
variable=self.type_partie, value="with draw").pack(anchor=W)
Label(self.introduction_window_game, text="\nCombien de Players voulez-vous?").pack()
Radiobutton(self.introduction_window_game, text="2 Players",
variable=self.nb_players_var, value=2).pack(anchor=W)
Radiobutton(self.introduction_window_game, text="3 Players",
variable=self.nb_players_var, value=3).pack(anchor=W)
Radiobutton(self.introduction_window_game, text="4 Players",
variable=self.nb_players_var, value=4).pack(anchor=W)
Button(self.introduction_window_game, text="Quit",
command=self.quit_party_event).pack(side=RIGHT)
Button(self.introduction_window_game, text="Ok",
command=self.start_game_event).pack(side=RIGHT)
def start_game_event(self):
result = messagebox.askokcancel("Paramètres de partie",
f"Vous avez choisi {self.nb_players_var.get()} Players et "
f"le type de partie {self.type_partie.get()}."
f"\nEst-ce exact?", icon='warning')
if result == True:
self.start_game()
self.show()
self.introduction_window_game.destroy()
if self.type_partie.get() == "with draw":
self.button_draw = Button(self, text="Draw", command=self.button_to_draw)
self.button_draw.grid(row=3, column=0)
else:
self.button_draw.grid_remove()
self.destroy
def quit_party_event(self):
result = messagebox.askokcancel("Quit the game.", "Are you sur?", icon='warning')
if result == True:
self.destroy()
def button_to_draw(self):
print("Function test. You drew a domino!")
def message_fin_de_partie(self):
pass
if __name__ == '__main__':
DominoWindow().mainloop()
The error is located here : self.button_draw.grid_remove()
Thank you and I hope it is all clear.
Edited : Removed dependency and adjusted the variable name. Mistype.

I'll start by saying I commented out the line self.start_game() as the start_game method doesn't exist. I'll also add that to reproduce the problem I started the app and then chose to start a game without draw with any number of players.
Ultimately it's possible to do what you appear to want: i.e. not always have the 'Draw' button. What I would do would be to add the line self.button_draw = None somewhere within __init__(). This ensures that your window always has a button_draw attribute, and hence gets rid of the AttributeError about this attribute.
Next, you will need to adjust the lower if statement within start_game_event() to remove the 'Draw' button from the grid if it has been created:
if self.type_partie.get() == "with draw":
self.button_draw = Button(self, text="Draw", command=self.button_to_draw)
self.button_draw.grid(row=3, column=0)
elif self.button_draw is not None:
self.button_draw.grid_remove()
self.button_draw.destroy()
self.button_draw = None
I've replaced the else with elif and the condition that self.button_draw isn't None: we can't remove the 'Draw' button if there's no button to remove.
Note also that I replaced the line self.destroy with self.button_draw.destroy(): the former would have closed your app had you called the method but as you didn't call self.desroy it did nothing. Also, once the button has been destroyed we can set self.button_draw back to None to signify we have no 'Draw' button.
In a similar vein, if the 'Draw' button exists and you start another game with draw, you'll have two buttons in your window. You'll only see one because one will be on top of the other. However, as you only keep a reference to one button, you'll only be able to delete one of these two buttons. I'll leave it up to you to make a similar modification to your code to only add the button if it doesn't already exist.

Related

Is there a way to create a second window that connects to the parent window like a dropdown menu

I'm trying to make it so that new information shows in in a new window, but I want the new window to be connected to the parent window, even when the parent window is clicked the new window should still show up similar to how a dropdown menu works. I'm also planning on having some of the new windows have treeviews later on.
from tkinter import *
win = Tk()
win.geometry("500x500+0+0")
def button_function ():
win2 = Toplevel()
label = Label(win2,text='dropdown', width=7)
label.pack()
win2.geometry(f"+{win.winfo_x()}+{win.winfo_y()+30}")
button = Button(win, command=lambda: button_function (), width=12)
button.pack()
win.mainloop()
Ok so with a little bit of googling I came across this post: tkinter-detecting-a-window-drag-event
In that post they show how you can keep track of when the window has moved.
By taking that code and making some small changes we can use the dragging() and stop_drag() functions to move the top level window back to where it was set to relative to the main window.
That said this will only work in this case. You will need to write something more dynamic to track any new windows you want so they are placed properly and on top of that you will probably want to build this in a class so you do not have to manage global variables.
With a combination of this tracking function and using lift() to bring the window up we get closer to what you are asking to do.
That said you will probably want remove the tool bar at the top of the root window to be more clean. I would also focus on using a dictionary or list to keep track of open and closed windows and their locations to make the dynamic part of this easier.
import tkinter as tk
win = tk.Tk()
win.geometry("500x500+0+0")
win2 = None
drag_id = ''
def dragging(event):
global drag_id
if event.widget is win:
if drag_id == '':
print('start drag')
else:
win.after_cancel(drag_id)
print('dragging')
drag_id = win.after(100, stop_drag)
if win2 is not None:
win2.lift()
win2.geometry(f"+{win.winfo_x()}+{win.winfo_y() + 30}")
def stop_drag():
global drag_id, win2, win
print('stop drag')
drag_id = ''
if win2 is not None:
win2.lift()
win2.geometry(f"+{win.winfo_x()}+{win.winfo_y() + 30}")
win.bind('<Configure>', dragging)
def button_function():
global win2
win2 = tk.Toplevel()
label = tk.Label(win2, text='drop down', width=7)
label.pack()
win2.geometry(f"+{win.winfo_x()}+{win.winfo_y()+30}")
tk.Button(win, command=button_function, width=12).pack()
win.mainloop()
EDIT:
Ok so I took some time to write this up in a class so you could see how it could be done. I have also added some level of dynamic building of the buttons and pop up windows.
We use a combination of lists and lambdas to perform a little bit of tracking and in the end we pull off exactly what you were asking for.
let me know if you have any questions.
import tkinter as tk
class Main(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('500x500')
self.pop_up_list = []
self.drag_id = ''
self.button_notes = ['Some notes for new window', 'some other notes for new window', 'bacon that is all!']
self.bind('<Configure>', self.dragging)
for ndex, value in enumerate(self.button_notes):
print(ndex)
btn = tk.Button(self, text=f'Button {ndex+1}')
btn.config(command=lambda b=btn, i=ndex: self.toggle_button_pop_ups(i, b))
btn.grid(row=ndex, column=0, padx=5, pady=5)
self.pop_up_list.append([value, 0, None, btn])
def dragging(self, event):
if event.widget is self:
if self.drag_id == '':
pass
else:
self.after_cancel(self.drag_id)
self.drag_id = self.after(100, self.stop_drag)
for p in self.pop_up_list:
if p[1] == 1:
p[2].lift()
p[2].geometry(f"+{p[3].winfo_rootx() + 65}+{p[3].winfo_rooty()}")
def stop_drag(self):
self.drag_id = ''
for p in self.pop_up_list:
if p[1] == 1:
p[2].lift()
p[2].geometry(f"+{p[3].winfo_rootx() + 65}+{p[3].winfo_rooty()}")
def toggle_button_pop_ups(self, ndex, btn):
p = self.pop_up_list
if p[ndex][1] == 0:
p[ndex][1] = 1
p[ndex][2] = tk.Toplevel(self)
p[ndex][2].overrideredirect(1)
tk.Label(p[ndex][2], text=self.pop_up_list[ndex][0]).pack()
p[ndex][2].geometry(f"+{btn.winfo_rootx() + 65}+{btn.winfo_rooty()}")
else:
p[ndex][1] = 0
p[ndex][2].destroy()
p[ndex][2] = None
if __name__ == '__main__':
Main().mainloop()

How to see which button is activated / determine right buttons are activated on python tkinter

I'm making a game that finding seven right buttons(It has a fixed answer) among 12 buttons by using tkinter. There are a total of 12 buttons, and only if all seven of them are clicked will win the game.
I'm curious about how to make the window to see which button is activated or inactivated, and how to make a function to determine whether one wins or loses. (when seven specific buttons are activated, it wins.)
++
game1=tkinter.Tk()
game1.title("Test")
game1.geometry("600x450")
button1 = Button(game1, text=' 1 ', fg='black', bg='red',
height=3, width=10)
button1.place(x=0,y=300)
button2 = Button(game1, text=' 2 ', fg='black', bg='red',
height=3, width=10)
button2.place(x=100,y=300)
game1.mainloop()
This is the first time using tkinter on python so actually I stopped after writing this really basic code.
The player can choose seven buttons until player itself clicks the "finish" button. (after click that button, player cannot modify anything.)
At first, I thought if I declare "num" and +=1 on that when the right buttons are clicked, but this trial failed because the player can choose whether one activates or inactivates until until player itself clicks the "finish" button. So I thought that this code needs the way to check the final statements of the buttons.
Is there any ways to use something like "if" statements on tkinter? (if players choose right seven buttons, so it is found that they're activated --> then player wins.)
EDIT - I've updated the code:
import tkinter as tk
import tkinter.ttk as ttk
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
from random import sample
tk.Tk.__init__(self, *args, **kwargs)
self.title("Buttons")
self.resizable(width=False, height=False)
row_count = 3
column_count = 4
self.winning_buttons_count = 7
assert 0 < self.winning_buttons_count <= row_count * column_count
winning_buttons_numbers = sample(range(0, row_count * column_count), k=self.winning_buttons_count)
self.selected_buttons_count = 0
self.selected_button_color = "gray"
self.correct_button_color = "green"
self.incorrect_button_color = "red"
self.missed_button_color = "orange"
self.default_button_color = tk.Button().cget("bg")
def on_press(button):
color = button.cget("bg")
if color == self.default_button_color and self.selected_buttons_count < self.winning_buttons_count:
button.configure(bg=self.selected_button_color)
button.configure(relief=tk.SUNKEN)
self.selected_buttons_count += 1
elif color == self.selected_button_color:
button.configure(bg=self.default_button_color)
button.configure(relief=tk.RAISED)
self.selected_buttons_count -= 1
def check_win():
selected_winning_count = 0
for button in self.buttons:
is_selected = button.cget("bg") == self.selected_button_color and \
button.cget("relief") == tk.SUNKEN
is_winning = button.number in winning_buttons_numbers
if is_selected:
if is_winning:
button.configure(bg=self.correct_button_color)
selected_winning_count += 1
else:
button.configure(bg=self.incorrect_button_color)
else:
if is_winning:
button.configure(bg=self.missed_button_color)
if selected_winning_count == self.winning_buttons_count:
self.finish_button.configure(text="You won!")
else:
self.finish_button.configure(text="Incorrect.")
self.buttons = []
for row in range(row_count):
for column in range(column_count):
button = tk.Button(self, text=" " * 8)
button.grid(row=row, column=column)
button.number = (row * column_count) + column
button.configure(command=lambda b=button: on_press(b))
self.buttons.append(button)
vertical_line = ttk.Separator(self, orient=tk.VERTICAL)
vertical_line.grid(row=0, column=column_count+1, rowspan=row_count, sticky="ns", padx=(8, 8))
self.finish_button = tk.Button(self, text="Did I win?", command=check_win)
self.finish_button.grid(row=row_count//2, column=column_count+2)
def main():
application = Application()
application.mainloop()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())

Switch between multiple windows in Tkinter

I have created few windows using Tkinter. I need help in the implementation of switching from one window to another when the button has been clicked.
All windows that are created should have the same size.
And also I want to clear existing window data and show next window data.
If you want to have multiple windows opened and want to switch between each window with all of their widgets intact then I don't think destroying a window each time you switch is a good idea instead you can try to withdraw and deiconify the windows.
I've created something like this which can switch between windows and maintain the same geometry of the previous window as you said.
import tkinter as tk
class Window(tk.Toplevel):
# List to keep the reference of all the toplevel windows
_info_pages = []
def __init__(self, master=None, cnf={}, **kw):
kw = tk._cnfmerge( (cnf,kw) )
width = kw.pop('width', master.winfo_width()) # 250x250 will be the standard size of the window
height = kw.pop('height', master.winfo_height())
title = kw.pop('title', 'Win %s' %(len(self._info_pages)+1) )
super(Window, self).__init__(master=master, cnf=cnf, **kw)
for i in self._info_pages: i.wm_withdraw() # Hide the previous windows
if self._info_pages and width == master.winfo_width():
self.wm_geometry(self._info_pages[-1].winfo_geometry())
else:
self.wm_geometry("%dx%d+%d+%d" % (width, height,
master.winfo_rootx()+master.winfo_width(), master.winfo_rooty()))
self._info_pages.append(self)
self.title(title)
self.B1 = tk.Button(self, text='◀ Prev', padx=5, command=self.switch_to_prev)
self.B1.place(relx=0, rely=1, anchor='sw')
self.B2 = tk.Button(self, text='Next ▶', padx=5, command=self.switch_to_next)
self.B2.place(relx=1, rely=1, anchor='se')
self.enable_disable_button()
def enable_disable_button(self):
"""Enable and disable the buttons accordingly if there is no window."""
for i in self._info_pages:
if i == self._info_pages[0]: i.B1['state'] = 'disabled'
else: i.B1['state'] = 'normal'
if i == self._info_pages[-1]: i.B2['state'] = 'disabled'
else: i.B2['state'] = 'normal'
def switch_to_prev(self):
"""Switch to the previous window"""
index = self._info_pages.index(self)
if index != 0:
for i in self._info_pages:
i.wm_withdraw()
self._info_pages[index-1].geometry(self.winfo_geometry())
self._info_pages[index-1].wm_deiconify()
def switch_to_next(self):
"""Switch to the next window"""
index = self._info_pages.index(self)
if index+1 != len(self._info_pages):
for i in self._info_pages:
i.wm_withdraw()
self._info_pages[index+1].geometry(self.winfo_geometry())
self._info_pages[index+1].wm_deiconify()
def destroy(self):
"""if a window is destroyed this will open the last window in the list"""
self._info_pages.remove(self)
if self._info_pages:
self._info_pages[-1].geometry(self.winfo_geometry())
self._info_pages[-1].wm_deiconify()
self.enable_disable_button()
return super().destroy()
# This is just a demo
if __name__ == '__main__':
import random as rnd
root = tk.Tk()
root.geometry('250x250')
root.title("I'm the main window")
colorlist = ['beige','bisque','black','blanchedalmond','blue','blueviolet',
'burlywood', 'cadetblue','chartreuse','chocolate' ]
def create_window():
Window(root, bg=rnd.choice(colorlist))
tk.Button(root, text='Create Window', command=create_window).pack()
root.mainloop()

How to call a function on Tkinter class?(not inside label)

I'm trying to use a function which a placed inside the class of Tkinder but the function(aktodec) can't be found and a get an error. I don't wanna call the def as a command of a button but as a function that will give value to one of my variables
from Tkinter import *
class ADialog:
def __init__(self, parent):
top = self.top = Toplevel(parent)
Label(top, text="Number to convert").pack()
self.numb = Entry(top)
self.numb.pack(padx=15)
Label(top, text="Base of incered number").pack()
self.base = Entry(top)
self.base.pack(padx=15)
Label(top, text="Base you want to be converted").pack()
self.basemet=Entry(top)
self.basemet.pack(padx=15)
b = Button(top, text="OK", command=self.met)
b.pack(pady=5)
def aktodec(self,num,base): #####commands
dec=0
num=num[::-1]
for i in range(len(num)):
s=int(num1[i])*(int(base)**i)
dec=dec+s
def met(self):
num=self.numb=str(self.numb.get())
base=self.base =int(self.base.get())
basemet=self.basemet=int(self.basemet.get())
if base==basemet:
Label(root,text="The number "+self.numb+"is converted to"+self.numb) ##why can't be print??
if base==10:
new=num
else:
new1=self.aktodec(num,base) ####why aktodec doesn't give value to "new"??
Label(root,text="Number is"+str(new))
self.top.destroy()
root = Tk()
def open_dialog():
dial = ADialog(root)
root.wait_window(dial.top)
root.wm_geometry("400x300+20+40")
message=StringVar()
message.set("Complete the form")
Label(root, textvariable=message).pack(padx=30)
root.update()
message.set("Form completed")
Button(root, text="Done", command=root.destroy).pack()
Button(root, text="new", command=open_dialog).pack()
root.update()
root.mainloop()
And also I have a problem whith the label
Label(root,text="The number "+self.numb+"is converted to"+self.numb
which (i don't know why) won't appear to the root even the base=basemet. Help please(it's for a project in this week)!
In Python, a function can't modify some arguments(integers, strings) as perceived by the caller, they are immutable. However, some objects like lists are mutable.
def aktodec(self,num,base):
dec=0
num=num[::-1]
for i in range(len(num)):
s=int(num1[i])*(int(base)**i)
dec=dec+s
return dec
def met(self):
num=self.numb=str(self.numb.get())
base=self.base =int(self.base.get())
basemet=self.basemet=int(self.basemet.get())
new = num
if base==basemet:
Label(root,text="The number "+self.numb+"is converted to"+self.numb).pack()
if base==10:
new=num
else:
new=self.aktodec(num,base)
Label(root,text="Number is"+str(new)).pack()
self.top.destroy()

Python: Waiting for the enter key OR button press (Text Based Adventure with GUI)

Hi I am making a text based adventure in python and am having trouble with taking the user input, the text the user reads is in one text box and the input goes in an entry box.
I don't know how to get it to wait for the user to press enter or for a button to be pressed on the actual GUI.
I have tried:
textin.bind('<Return>', get_input)
but that didn't work for some reason I couldn't work out.
I have also tried:
import msvcrt as m
def wait():
m.getch()
but that made the GUI not show up or I wasn't using it properly.
Another thing I have tired is:
import time
time.sleep(5.0)
but that had the same problem of the GUI not showing up until after the countdown.
I cannot use
input()
as I am using a GUI and if I use that then the GUI won't show up until after or some other problem (I may be wrong, I'm still new to some of this)
I need to know how I can get it to take the text in the entry when the user presses enter OR a button on the GUI, and all that needs to be in a function so that the main game can wait for them to enter a command.
The code so far:
import tkinter as tk
def get_input(): #the button I put in had problems
player_command = textin.get() #if this function wasn't before it
root = tk.Tk()
frame = tk.Frame(root)
frame.grid(row = 0, column = 0)
textout = tk.Text(frame, width = 50, height = 23)
scroll = tk.Scrollbar(frame)
textin = tk.Entry(frame, width = 50)
button = tk.Button(frame, text = 'Submit', command = get_input)
textout.grid(row = 0, columnspan = 2, sticky = tk.W + tk.E)
textin.grid(row = 1, column = 0, sticky = tk.W + tk.E)
button.grid(row = 1, column = 1, sticky = tk.W + tk.E)
scroll.grid(row = 0, column = 1, sticky = tk.N + tk.S + tk.E)
scroll.config(command = textout.yview)
def main_menu():
textout.configure(state = 'normal')
textout.insert(tk.END, "Welcome to The Adventure\n")
textout.insert(tk.END, "What would you like to do?\n")
textout.insert(tk.END, "Continue\n")
textout.insert(tk.END, "New Game\n")
textout.insert(tk.END, "Help\n")
textout.configure(state = 'disabled')
while True:
if player_command == 'continue':
load_game() #other function
elif player_command == 'new game':
character_creation() #other function
elif player_command == 'help':
help_info() #other function
else:
textout.configure(state = 'normal')
textout.insert(tk.END, "Unknown command, type 'help' for hints")
textout.configure(state = 'disabled')
main_menu()
root.mainloop()
Thanks in advance.
Here Is an example of taking user input from text box.
Note that in this example Enter key is used to get the string on current line and submit button is used to print the currently held data.
import Tkinter as tk
class Test(object):
def __init__(self, root):
self.laststat=0#just to check multiple <Enter key> press do not delete the data
self.currString=""
self.tempString=""
self.text = tk.Text(root)
self.text.bind('<Key>', self.stripLine)
self.text.pack(side=tk.LEFT)
self.text.focus()
self.button = tk.Button(root, text = 'Submit', command = self.printData)
self.button.pack(side=tk.LEFT)
def stripLine(self, event):
val=('{k!r}'.format(k = event.char))[1:-1]
if val=='\\r' and self.laststat==0:
self.currString=self.tempString
self.tempString=""
self.laststat=1
elif val!='\\r':
self.tempString+=val
self.laststat=0
def printData(self):
print 'Current String is :'+self.currString
#print 'temp String is :'+self.tempString
root = tk.Tk()
A = Test(root)
root.mainloop()
Also note that you can add similar functions (similar to stripLine) to handle backspace and similar other key presses

Categories

Resources