How to store tkinter button widgets in a dictionary?












1














The two goals of my program: #1 copy notes to the clipboard after clicking a button; and #2 make the button widgets persist through restart of the program. (This post will focus solely on goal number 1) The buttons are populated as expected, but the command does not work properly (No Errors though). I've tried other clipboard modules such as pyperclip with no luck. Apologies if this was hard to follow, I just started to learn python as my first programming language last week.



I would like to know how I would go about making the buttons copy their corresponding notes to the clipboard.



from tkinter import *
import json

root = Tk()
root.title("CopyNotes")
root.geometry()

json_file = open("dictionary.json", encoding="utf-8")
mynotes = json.load(json_file)

for keys in mynotes:
btnz = Button(root, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver", command=root.clipboard_append(mynotes[keys][1]), height=2, width=13).pack(side=TOP, fill=BOTH, expand=YES)

root.mainloop()


So just to be clear, the issue I'm trying to solve is the button command not working properly. First time any buttons are pressed it copies 'button1notebutton2notebutton3note'and stops working at all after that.
The effect I want the first button to achieve: root.clipboard_append(button1note)
and so on for the rest..



After I figure out how to do this, I plan on accepting user input to add their own buttons by adding to the dictionary.
Edit: Fixed the clipboard issue -



    mynotes = pickle.load(open("note.p", "rb"))
print(mynotes)
for keys in mynotes:
thenotes = mynotes[keys][1]
mybtnz = Button(ctowin, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver",
command=lambda thenotes=thenotes: pyperclip.copy(thenotes), height=2, width=13)
.pack(side=TOP, fill=BOTH, expand=YES)


Button example










share|improve this question





























    1














    The two goals of my program: #1 copy notes to the clipboard after clicking a button; and #2 make the button widgets persist through restart of the program. (This post will focus solely on goal number 1) The buttons are populated as expected, but the command does not work properly (No Errors though). I've tried other clipboard modules such as pyperclip with no luck. Apologies if this was hard to follow, I just started to learn python as my first programming language last week.



    I would like to know how I would go about making the buttons copy their corresponding notes to the clipboard.



    from tkinter import *
    import json

    root = Tk()
    root.title("CopyNotes")
    root.geometry()

    json_file = open("dictionary.json", encoding="utf-8")
    mynotes = json.load(json_file)

    for keys in mynotes:
    btnz = Button(root, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver", command=root.clipboard_append(mynotes[keys][1]), height=2, width=13).pack(side=TOP, fill=BOTH, expand=YES)

    root.mainloop()


    So just to be clear, the issue I'm trying to solve is the button command not working properly. First time any buttons are pressed it copies 'button1notebutton2notebutton3note'and stops working at all after that.
    The effect I want the first button to achieve: root.clipboard_append(button1note)
    and so on for the rest..



    After I figure out how to do this, I plan on accepting user input to add their own buttons by adding to the dictionary.
    Edit: Fixed the clipboard issue -



        mynotes = pickle.load(open("note.p", "rb"))
    print(mynotes)
    for keys in mynotes:
    thenotes = mynotes[keys][1]
    mybtnz = Button(ctowin, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver",
    command=lambda thenotes=thenotes: pyperclip.copy(thenotes), height=2, width=13)
    .pack(side=TOP, fill=BOTH, expand=YES)


    Button example










    share|improve this question



























      1












      1








      1







      The two goals of my program: #1 copy notes to the clipboard after clicking a button; and #2 make the button widgets persist through restart of the program. (This post will focus solely on goal number 1) The buttons are populated as expected, but the command does not work properly (No Errors though). I've tried other clipboard modules such as pyperclip with no luck. Apologies if this was hard to follow, I just started to learn python as my first programming language last week.



      I would like to know how I would go about making the buttons copy their corresponding notes to the clipboard.



      from tkinter import *
      import json

      root = Tk()
      root.title("CopyNotes")
      root.geometry()

      json_file = open("dictionary.json", encoding="utf-8")
      mynotes = json.load(json_file)

      for keys in mynotes:
      btnz = Button(root, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver", command=root.clipboard_append(mynotes[keys][1]), height=2, width=13).pack(side=TOP, fill=BOTH, expand=YES)

      root.mainloop()


      So just to be clear, the issue I'm trying to solve is the button command not working properly. First time any buttons are pressed it copies 'button1notebutton2notebutton3note'and stops working at all after that.
      The effect I want the first button to achieve: root.clipboard_append(button1note)
      and so on for the rest..



      After I figure out how to do this, I plan on accepting user input to add their own buttons by adding to the dictionary.
      Edit: Fixed the clipboard issue -



          mynotes = pickle.load(open("note.p", "rb"))
      print(mynotes)
      for keys in mynotes:
      thenotes = mynotes[keys][1]
      mybtnz = Button(ctowin, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver",
      command=lambda thenotes=thenotes: pyperclip.copy(thenotes), height=2, width=13)
      .pack(side=TOP, fill=BOTH, expand=YES)


      Button example










      share|improve this question















      The two goals of my program: #1 copy notes to the clipboard after clicking a button; and #2 make the button widgets persist through restart of the program. (This post will focus solely on goal number 1) The buttons are populated as expected, but the command does not work properly (No Errors though). I've tried other clipboard modules such as pyperclip with no luck. Apologies if this was hard to follow, I just started to learn python as my first programming language last week.



      I would like to know how I would go about making the buttons copy their corresponding notes to the clipboard.



      from tkinter import *
      import json

      root = Tk()
      root.title("CopyNotes")
      root.geometry()

      json_file = open("dictionary.json", encoding="utf-8")
      mynotes = json.load(json_file)

      for keys in mynotes:
      btnz = Button(root, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver", command=root.clipboard_append(mynotes[keys][1]), height=2, width=13).pack(side=TOP, fill=BOTH, expand=YES)

      root.mainloop()


      So just to be clear, the issue I'm trying to solve is the button command not working properly. First time any buttons are pressed it copies 'button1notebutton2notebutton3note'and stops working at all after that.
      The effect I want the first button to achieve: root.clipboard_append(button1note)
      and so on for the rest..



      After I figure out how to do this, I plan on accepting user input to add their own buttons by adding to the dictionary.
      Edit: Fixed the clipboard issue -



          mynotes = pickle.load(open("note.p", "rb"))
      print(mynotes)
      for keys in mynotes:
      thenotes = mynotes[keys][1]
      mybtnz = Button(ctowin, text=mynotes[keys][0], font="Helvetica 10 bold", bg="silver",
      command=lambda thenotes=thenotes: pyperclip.copy(thenotes), height=2, width=13)
      .pack(side=TOP, fill=BOTH, expand=YES)


      Button example







      python python-3.x dictionary tkinter widget






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 1:25

























      asked Nov 11 at 18:21









      cois

      84




      84
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You don't need to use json as you are not working with a JSON object but a python dictionary.



          Here is your code refactored to populate the app with 3 buttons;



          [UPDATED] Although you will need to completely refactor your code because your for loop is populating the clipboard with everything in your dictionary immediately.



          from tkinter import *
          from tinydb import TinyDB, Query

          db = TinyDB('clipboard.json')

          root = Tk()
          root.title("CopyNotes")
          root.geometry()

          mynotes = {
          "B1": ["button1label","button1note"],
          "B2":["button2label","button2note"],
          "B3":["button3label","button3note"]
          }

          def cp_to_cb_and_db(note, key):
          root.clipboard_append(note[key][1])
          print('[+] Adding note: {} to clipboard.'.format(note))
          db.insert({key: note})


          for key in mynotes:
          btnz = Button(
          root,
          text=mynotes[key][0],
          font="Helvetica 10 bold",
          bg="silver",
          command=cp_to_cb_and_db(mynotes, key),
          height=2,
          width=13).pack(side=TOP, fill=BOTH, expand=YES)

          root.mainloop()





          share|improve this answer























          • Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
            – cois
            Nov 11 at 18:56










          • you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
            – Jack Herer
            Nov 11 at 19:00












          • you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
            – Jack Herer
            Nov 11 at 19:03










          • I will update my answer shortly with an example of how you can do that..
            – Jack Herer
            Nov 11 at 19:05










          • updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
            – Jack Herer
            Nov 11 at 19:30











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251800%2fhow-to-store-tkinter-button-widgets-in-a-dictionary%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You don't need to use json as you are not working with a JSON object but a python dictionary.



          Here is your code refactored to populate the app with 3 buttons;



          [UPDATED] Although you will need to completely refactor your code because your for loop is populating the clipboard with everything in your dictionary immediately.



          from tkinter import *
          from tinydb import TinyDB, Query

          db = TinyDB('clipboard.json')

          root = Tk()
          root.title("CopyNotes")
          root.geometry()

          mynotes = {
          "B1": ["button1label","button1note"],
          "B2":["button2label","button2note"],
          "B3":["button3label","button3note"]
          }

          def cp_to_cb_and_db(note, key):
          root.clipboard_append(note[key][1])
          print('[+] Adding note: {} to clipboard.'.format(note))
          db.insert({key: note})


          for key in mynotes:
          btnz = Button(
          root,
          text=mynotes[key][0],
          font="Helvetica 10 bold",
          bg="silver",
          command=cp_to_cb_and_db(mynotes, key),
          height=2,
          width=13).pack(side=TOP, fill=BOTH, expand=YES)

          root.mainloop()





          share|improve this answer























          • Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
            – cois
            Nov 11 at 18:56










          • you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
            – Jack Herer
            Nov 11 at 19:00












          • you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
            – Jack Herer
            Nov 11 at 19:03










          • I will update my answer shortly with an example of how you can do that..
            – Jack Herer
            Nov 11 at 19:05










          • updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
            – Jack Herer
            Nov 11 at 19:30
















          1














          You don't need to use json as you are not working with a JSON object but a python dictionary.



          Here is your code refactored to populate the app with 3 buttons;



          [UPDATED] Although you will need to completely refactor your code because your for loop is populating the clipboard with everything in your dictionary immediately.



          from tkinter import *
          from tinydb import TinyDB, Query

          db = TinyDB('clipboard.json')

          root = Tk()
          root.title("CopyNotes")
          root.geometry()

          mynotes = {
          "B1": ["button1label","button1note"],
          "B2":["button2label","button2note"],
          "B3":["button3label","button3note"]
          }

          def cp_to_cb_and_db(note, key):
          root.clipboard_append(note[key][1])
          print('[+] Adding note: {} to clipboard.'.format(note))
          db.insert({key: note})


          for key in mynotes:
          btnz = Button(
          root,
          text=mynotes[key][0],
          font="Helvetica 10 bold",
          bg="silver",
          command=cp_to_cb_and_db(mynotes, key),
          height=2,
          width=13).pack(side=TOP, fill=BOTH, expand=YES)

          root.mainloop()





          share|improve this answer























          • Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
            – cois
            Nov 11 at 18:56










          • you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
            – Jack Herer
            Nov 11 at 19:00












          • you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
            – Jack Herer
            Nov 11 at 19:03










          • I will update my answer shortly with an example of how you can do that..
            – Jack Herer
            Nov 11 at 19:05










          • updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
            – Jack Herer
            Nov 11 at 19:30














          1












          1








          1






          You don't need to use json as you are not working with a JSON object but a python dictionary.



          Here is your code refactored to populate the app with 3 buttons;



          [UPDATED] Although you will need to completely refactor your code because your for loop is populating the clipboard with everything in your dictionary immediately.



          from tkinter import *
          from tinydb import TinyDB, Query

          db = TinyDB('clipboard.json')

          root = Tk()
          root.title("CopyNotes")
          root.geometry()

          mynotes = {
          "B1": ["button1label","button1note"],
          "B2":["button2label","button2note"],
          "B3":["button3label","button3note"]
          }

          def cp_to_cb_and_db(note, key):
          root.clipboard_append(note[key][1])
          print('[+] Adding note: {} to clipboard.'.format(note))
          db.insert({key: note})


          for key in mynotes:
          btnz = Button(
          root,
          text=mynotes[key][0],
          font="Helvetica 10 bold",
          bg="silver",
          command=cp_to_cb_and_db(mynotes, key),
          height=2,
          width=13).pack(side=TOP, fill=BOTH, expand=YES)

          root.mainloop()





          share|improve this answer














          You don't need to use json as you are not working with a JSON object but a python dictionary.



          Here is your code refactored to populate the app with 3 buttons;



          [UPDATED] Although you will need to completely refactor your code because your for loop is populating the clipboard with everything in your dictionary immediately.



          from tkinter import *
          from tinydb import TinyDB, Query

          db = TinyDB('clipboard.json')

          root = Tk()
          root.title("CopyNotes")
          root.geometry()

          mynotes = {
          "B1": ["button1label","button1note"],
          "B2":["button2label","button2note"],
          "B3":["button3label","button3note"]
          }

          def cp_to_cb_and_db(note, key):
          root.clipboard_append(note[key][1])
          print('[+] Adding note: {} to clipboard.'.format(note))
          db.insert({key: note})


          for key in mynotes:
          btnz = Button(
          root,
          text=mynotes[key][0],
          font="Helvetica 10 bold",
          bg="silver",
          command=cp_to_cb_and_db(mynotes, key),
          height=2,
          width=13).pack(side=TOP, fill=BOTH, expand=YES)

          root.mainloop()






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 19:28

























          answered Nov 11 at 18:42









          Jack Herer

          338112




          338112












          • Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
            – cois
            Nov 11 at 18:56










          • you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
            – Jack Herer
            Nov 11 at 19:00












          • you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
            – Jack Herer
            Nov 11 at 19:03










          • I will update my answer shortly with an example of how you can do that..
            – Jack Herer
            Nov 11 at 19:05










          • updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
            – Jack Herer
            Nov 11 at 19:30


















          • Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
            – cois
            Nov 11 at 18:56










          • you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
            – Jack Herer
            Nov 11 at 19:00












          • you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
            – Jack Herer
            Nov 11 at 19:03










          • I will update my answer shortly with an example of how you can do that..
            – Jack Herer
            Nov 11 at 19:05










          • updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
            – Jack Herer
            Nov 11 at 19:30
















          Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
          – cois
          Nov 11 at 18:56




          Thank you Jack I'll keep that in mind! I've updated my code on here to reflect those changes and make it easier for people to see. I'll still have to use an external file but for the purposes of this post that's irrelevant. Anyway, the problem that lies in command=root.clipboard_append(mynotes[keys][1]) still persists. Have any ideas or workaround for that? Thanks.
          – cois
          Nov 11 at 18:56












          you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
          – Jack Herer
          Nov 11 at 19:00






          you shouldn't really change your question because now it works and your asking why it doesn't work.. others will go to the accepted answer to see the correct way to do it. It would be more helpful to others to see your wrong code and then see the correct code in an accepted answer, please accept my answer if it helped and you think it will help others
          – Jack Herer
          Nov 11 at 19:00














          you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
          – Jack Herer
          Nov 11 at 19:03




          you are only storing the values of mynotes in the clipboard in memory (ram) so when the code finishes the values are lost, will need a way to persist the data, maybe in a flat file database or even a text file
          – Jack Herer
          Nov 11 at 19:03












          I will update my answer shortly with an example of how you can do that..
          – Jack Herer
          Nov 11 at 19:05




          I will update my answer shortly with an example of how you can do that..
          – Jack Herer
          Nov 11 at 19:05












          updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
          – Jack Herer
          Nov 11 at 19:30




          updated... it will now store data in a flat database file in a json format but you access the data with Query() class. try the docs - tinydb.readthedocs.io/en/latest - TinyDB is actually quite powerful and easy to use
          – Jack Herer
          Nov 11 at 19:30


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53251800%2fhow-to-store-tkinter-button-widgets-in-a-dictionary%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Full-time equivalent

          Bicuculline

          What is this shape that looks like a rectangle with rounded ends called?