반응형
JSON / XML 응답

이 섹션에서는 요청 헤더에 따라 애플리케이션이 HTML, JSON 또는 XML 형식으로 응답 할 수 있도록 애플리케이션을 약간 리팩터링합니다.

1. 재사용 가능한 함수 만들기

Route Handler에서 지금까지는 Gin의 컨텍스트 중 HTML을 사용했습니다. 항상 HTML페이지를 보여줄 때는 괜찮지만, 요청에 따라 응답 형식을 변경하고 싶을 때에는 렌더링을 처리하는 단일 함수로 리팩토링해야합니다(?). 이렇게 함으로써 Route Handler는 유효성 검사(validation) 및 데이터 추출(data fetching)에 집중하도록 할 수 있습니다.

 

Route Handler는 응답 형식에 관계없이 동일한 유효성 검사, 데이터 추출 및 처리를 수행해야합니다. 이 부분이 완료되면 데이터를 사용하여 원하는 형식의 응답을 생성 할 수 있습니다. HTML 응답이 필요한 경우 데이터를 HTML 템플릿에 전달하고, JSON 응답이 필요한 경우이 데이터를 JSON으로 변환, XML에서도 마찬로 데이터를 보내줄 수 있습니다.

 

main.go 파일 내부에 모든 Route Handler가 사용할 render 함수를 만들겠습니다. 이 함수는 request의 Accept header를 참조하여 rendering을 처리할 것입니다.

 

Gin에서는 라우트 핸들러에 전달 된 Context 객체에 Request라는 필드가 포함됩니다. This field contains the header field which contains all the request headers. Get 메소드를 를 이용하여 Header로부터 Accept header를 다음과 같이 추출할 수 있습니다.

// c is the Gin Context 
c.Request.Header.Get("Accept")
  • application/json 으로 설정하면 함수가 JSON을 렌더링합니다.
  • application/xml 으로 설정하면 함수가 XML을 렌더링하고
  • 이것이 다른 것으로 설정되거나 비어 있으면 함수는 HTML을 렌더링합니다.

main.go에 render 함수를 아래와 같이 추가합니다.

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

var router *gin.Engine

func main() {
	router := gin.Default()

	router.LoadHTMLGlob("templates/*")

	router.GET("/", showIndexPage)
	router.GET("/article/view/:article_id", getArticle)

	router.Run()

}

func render(c *gin.Context, data gin.H, templateName string) {

	switch c.Request.Header.Get("Accept") {
	case "application/json":
		// Respond with JSON
		c.JSON(http.StatusOK, data["payload"])
	case "application/xml":
		// Respond with XML
		c.XML(http.StatusOK, data["payload"])
	default:
		// Respond with HTML
		c.HTML(http.StatusOK, templateName, data)
	}

}

2. 유닛 테스트를 통한 Route Handler 요구사항 정의 =>생략...

3. Route Handler 업데이트

기존의 c.HTML방법을 render 함수로 바꿔주기만 하면 됩니다.

 

<기존>

func showIndexPage(c *gin.Context) {
  articles := getAllArticles()

  // Call the HTML method of the Context to render a template
  c.HTML(
    // Set the HTTP status to 200 (OK)
    http.StatusOK,
    // Use the index.html template
    "index.html",
    // Pass the data that the page uses
    gin.H{
      "title":   "Home Page",
      "payload": articles,
    },
  )

}

<변경>

func showIndexPage(c *gin.Context) {
  articles := getAllArticles()

  // Call the render function with the name of the template to render
  render(c, gin.H{
    "title":   "Home Page",
    "payload": articles}, "index.html")

}

 

JSON 형식으로 Article List 추출

JSON테스트를 위해새로 어플리케이션을 빌드한 후 아래를 실행합니다.

curl -X GET -H "Accept: application/json" http://localhost:8080/

다음과 같은 응답을 반환해야합니다.

[{"id":1,"title":"Article 1","content":"Article 1 body"},{"id":2,"title":"Article 2","content":"Article 2 body"}]

 

XML 형식으로 Article 추출

XML 테스트를 위해 아래의 명령어를 실행합니다.

curl -X GET -H "Accept: application/xml" http://localhost:8080/article/view/1

다음과 같은 응답을 반환해야합니다.

<article><ID>1</ID><Title>Article 1</Title><Content>Article 1 body</Content></article>

 

4. Application 테스트

 이제 우리가 작성한 테스트를 실행하고 결과를 확인해 보겠습니다. 프로젝트 폴더에서 다음 명령을 실행합니다.

go test -v

이 명령을 실행하면 아래와 유사한 결과가 나타납니다.

=== RUN   TestShowIndexPageUnauthenticated
[GIN] 2016/06/14 - 19:07:26 | 200 |     183.315µs |  |   GET     /
--- PASS: TestShowIndexPageUnauthenticated (0.00s)
=== RUN   TestArticleUnauthenticated
[GIN] 2016/06/14 - 19:07:26 | 200 |     143.789µs |  |   GET     /article/view/1
--- PASS: TestArticleUnauthenticated (0.00s)
=== RUN   TestArticleListJSON
[GIN] 2016/06/14 - 19:07:26 | 200 |      51.087µs |  |   GET     /
--- PASS: TestArticleListJSON (0.00s)
=== RUN   TestArticleXML
[GIN] 2016/06/14 - 19:07:26 | 200 |      38.656µs |  |   GET     /article/view/1
--- PASS: TestArticleXML (0.00s)
=== RUN   TestGetAllArticles
--- PASS: TestGetAllArticles (0.00s)
=== RUN   TestGetArticleByID
--- PASS: TestGetArticleByID (0.00s)
PASS
ok    github.com/demo-apps/go-gin-app 0.084s

이 출력에서 ​​볼 수 있듯이이 명령은 우리가 작성한 모든 테스트를 한번에 실행하며,이 경우 애플리케이션이 의도 한대로 작동하고 있음을 나타냅니다. 출력을 자세히 살펴보면 Go가 경로 핸들러를 테스트하는 과정에서 HTTP 요청을 수행했음을 알 수 있습니다.

 


이렇게 Gin Framework에 대한 강좌 따라하기를 수행해보았는데요, 마지막 JSON/XML 부분과 최종 테스트 부분은 아직 정확히 테스트는 못해보고 그냥 자료 번역 수준으로 올려놓습니다. 나중에라도 익숙해지면 해보려구요. 혹시라도 참고가 되시면 좋겠습니다.

 

그럼 이만~~~

반응형
반응형
개별 Article 화면 구성

현재까지 구성한 앱에서는 Article을 클릭했을 때 링크가 작동하지 않았습니다. 이번에는 각 Article에 대한 핸들러와 템플릿을 추가하도록 하겠습니다.

1. Route 설정

router.GET("/article/view/:article_id", getArticle)

main함수의 Route 설정 부분에 위구문을 추가합니다. 위 라우터는 패턴과 맞는 요청에 대해 경로를 일치시키고, 경로 마지막부분을 route 파라미터인 article_id에 저장합니다. 이 라우터에서는 handler함수로 getArticle을 정의합니다.

 

main.go 전체 코드 모습

package main

import (
	//"net/http"

	"github.com/gin-gonic/gin"
)

var router *gin.Engine

func main() {
	router := gin.Default()

	router.LoadHTMLGlob("templates/*")

	router.GET("/", showIndexPage)
	router.GET("/article/view/:article_id", getArticle)

	router.Run()

}

 

2. View Templates 만들기

개별 Article Contents를 표현할 새 템플릿 templates/article.html 을 생성하겠습니다.

<!--article.html-->

<!--Embed the header.html template at this location-->
{{ template "header.html" .}}

<!--Display the title of the article-->
<h1>{{.payload.Title}}</h1>

<!--Display the content of the article-->
<p>{{.payload.Content}}</p>

<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}

유닛 테스트....가 필요한데 Pass...

3. Route Handler 생성

Article 추출

models.article.go파일에  getArticleByID() 함수 정의하여 article을 가져오는 기능을 추가합니다.

package main

import "errors"

type article struct {
	ID      int    `json:"id"`
	Title   string `json:"title"`
	Content string `json:"content"`
}

// For this demo, we're storing the article list in memory
// In a real application, this list will most likely be fetched
// from a database or from static files
var articleList = []article{
	article{ID: 1, Title: "Article 1", Content: "Article 1 body"},
	article{ID: 2, Title: "Article 2", Content: "Article 2 body"},
}

// Return a list of all the articles
func getAllArticles() []article {
	return articleList
}

func getArticleByID(id int) (*article, error) {
	for _, a := range articleList {
		if a.ID == id {
			return &a, nil
		}
	}
	return nil, errors.New("Article not found")
}

getArticleByID 함수는 Article List를 반복하다가 ID가 일치할 경우 해당 Article을 반환합니다. 일치하는 기사가 없으면 오류를 반환합니다.

 

handlers.article.go파일 수정

Article을 article.html 템플릿에 전달하여 렌더링하도록 getArticle 함수를 추가합니다.

// handlers.article.go

package main

import (
  "net/http"
  "strconv"

  "github.com/gin-gonic/gin"
)

func showIndexPage(c *gin.Context) {
  articles := getAllArticles()

  // Call the HTML method of the Context to render a template
  c.HTML(
    // Set the HTTP status to 200 (OK)
    http.StatusOK,
    // Use the index.html template
    "index.html",
    // Pass the data that the page uses
    gin.H{
      "title":   "Home Page",
      "payload": articles,
    },
  )

}

func getArticle(c *gin.Context) {
  // Check if the article ID is valid
  if articleID, err := strconv.Atoi(c.Param("article_id")); err == nil {
    // Check if the article exists
    if article, err := getArticleByID(articleID); err == nil {
      // Call the HTML method of the Context to render a template
      c.HTML(
        // Set the HTTP status to 200 (OK)
        http.StatusOK,
        // Use the index.html template
        "article.html",
        // Pass the data that the page uses
        gin.H{
          "title":   article.Title,
          "payload": article,
        },
      )

    } else {
      // If the article is not found, abort with an error
      c.AbortWithError(http.StatusNotFound, err)
    }

  } else {
    // If an invalid article ID is specified in the URL, abort with an error
    c.AbortWithStatus(http.StatusNotFound)
  }
}

 

<결과>

 

 

 

<파일구성>

 

 

 

 
반응형
반응형

Article List 표시

이 섹션에서는 index 페이지에 모든 article list를 표시하는 기능을 추가합니다.

1.Router 설정

원문에 따르면 응용 프로그램이 커질 것을 대비하여 별도의 Router파일에서 경로를 정의하는 방식으로 구성하였는데, 무슨 문제인지 제 실습 중에는 routes.go파일에 따로 코드를 분리하니 에러가 발생했습니다. 그래서 route 를 main() 함수 내부에 구성하도록 하겠습니다. 단, route handler 함수만 별도로 분리해 내도록 하겠습니다.(handlers.article.go)

 

main.go파일은 아래와 같이 코딩합니다.

package main

import (
	//"net/http"

	"github.com/gin-gonic/gin"
)

var router *gin.Engine

func main() {
	router := gin.Default()

	router.LoadHTMLGlob("templates/*")
	
	router.GET("/", showIndexPage)

	router.Run()

}

2. Article Model 디자인

router를 마치기 전에 우선 Model을 구성하도록 합니다. 우리가 구성할 Article 모델은 Id, Title, Content의 세 개의 필드 만 사용하여 구성합니다. 일반적인 어플리케이션이라면 당연히 데이터베이스를 사용하지만, 예제에서는 이를 단순화하기 위해 아래와 같이 하드코딩된 List변수를 사용하도록 하겠습니다. 그리고 모든 Article List을 반환하는 함수가 필요합니다. 이 함수의 이름을 getAllArticles()로 하고 models.article.go 파일에 함께 구성합니다.

 

models.article.go

// models.article.go

package main

type article struct {
  ID      int    json:"id"
  Title   string json:"title"
  Content string json:"content"
}

// For this demo, we're storing the article list in memory
// In a real application, this list will most likely be fetched
// from a database or from static files
var articleList = []article{
  article{ID: 1, Title: "Article 1", Content: "Article 1 body"},
  article{ID: 2, Title: "Article 2", Content: "Article 2 body"},
}

// Return a list of all the articles
func getAllArticles() []article {
  return articleList
}

또한 단위 테스트를 위한 models.article_test.go 파일을 생성하고 내부에 TestGetAllArticles 함수를 작성하겠습니다.

 

models.article_test.go

// models.article_test.go

package main

import "testing"

// Test the function that fetches all articles
func TestGetAllArticles(t *testing.T) {
  alist := getAllArticles()

  // Check that the length of the list of articles returned is the
  // same as the length of the global variable holding the list
  if len(alist) != len(articleList) {
    t.Fail()
  }

  // Check that each member is identical
  for i, v := range alist {
    if v.Content != articleList[i].Content ||
      v.ID != articleList[i].ID ||
      v.Title != articleList[i].Title {

      t.Fail()
      break
    }
  }
}

위 단위 테스트에서는 getAllArticles() 함수를 이용해 모든 Article List를 가져오는 테스트 수행합니다. 이 테스트는 먼저getAllArticles() 함수로 가져온 Article List와 전역 변수 articleList의 요소 개수가 동일한지 확인합니다. 그런 다음 Article List들을 반복하여 각각의 Article이 동일한 지 확인합니다. 이 두 검사 중 하나가 실패하면 테스트는 Fail이 됩니다.

3. View Template 만들기

index.html에서 모든 Article들의 List를 표시해야합니다. Article List는 payload라는 이름의 변수로 전달하도록 하겠습니다. 아래는 모든 article list를 보여주게 됩니다. 모든 Article List에 대해 Title, Content를 표시해주게 됩니다만, 아직 라우터를 완성하지 않았으므로 표시되는 건 없습니다.

 

 

업데이트 된 index.html파일은 아래와 같습니다.

<!--index.html-->

<!--Embed the header.html template at this location-->
{{ template "header.html" .}}

  <!--Loop over the payload variable, which is the list of articles-->
  {{range .payload }}
    <!--Create the link for the article based on its ID-->
    <a href="/article/view/{{.ID}}">
      <!--Display the title of the article -->
      <h2>{{.Title}}</h2>
    </a>
    <!--Display the content of the article-->
    <p>{{.Content}}</p>
  {{end}}

<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}

(주의) header에는 웹페이지의 타이틀을 표시하는 {{.title}}변수가 있고, index에서 호출하는 {{.Title}}변수는 Article의 타이틀을 의미합니다.

4. 유닛 테스트를 통한 Route Handler 요구사항 정의

Index 라우트 생성 전에 이 route handler의 동작을 미리 예상한 테스트를 정의하겠습니다. 이 테스트에서 확인할 조건은 다음과 같습니다.

  • 핸들러는 HTTP 상태 코드 200으로 응답한다.
  • 반환 된 HTML에는 "Home Page"라는 텍스트가 포함 된 title tag가 포함된다.

 

handlers.article_test.go파일을 생성하고, 내부에 TestShowIndexPageUnauthenticated 라는 테스트 함수를 생성합니다. 그리고 이 함수에서 사용할 helper 함수를 common_test.go파일에 작성합니다.

 

handlers.article_test.go다음과 같습니다.

// handlers.article_test.go

package main

import (
  "io/ioutil"
  "net/http"
  "net/http/httptest"
  "strings"
  "testing"
)

// Test that a GET request to the home page returns the home page with
// the HTTP code 200 for an unauthenticated user
func TestShowIndexPageUnauthenticated(t *testing.T) {
  r := getRouter(true)

  r.GET("/", showIndexPage)

  // Create a request to send to the above route
  req, _ := http.NewRequest("GET", "/", nil)

  testHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {
    // Test that the http status code is 200
    statusOK := w.Code == http.StatusOK

    // Test that the page title is "Home Page"
    // You can carry out a lot more detailed tests using libraries that can
    // parse and process HTML pages
    p, err := ioutil.ReadAll(w.Body)
    pageOK := err == nil && strings.Index(string(p), "<title>Home Page</title>") > 0

    return statusOK && pageOK
  })
}

 

common_test.go다음과 같습니다.

package main

import (
  "net/http"
  "net/http/httptest"
  "os"
  "testing"

  "github.com/gin-gonic/gin"
)

var tmpArticleList []article

// This function is used for setup before executing the test functions
func TestMain(m *testing.M) {
  //Set Gin to Test Mode
  gin.SetMode(gin.TestMode)

  // Run the other tests
  os.Exit(m.Run())
}

// Helper function to create a router during testing
func getRouter(withTemplates bool) *gin.Engine {
  r := gin.Default()
  if withTemplates {
    r.LoadHTMLGlob("templates/*")
  }
  return r
}

// Helper function to process a request and test its response
func testHTTPResponse(t *testing.T, r *gin.Engine, req *http.Request, f func(w *httptest.ResponseRecorder) bool) {

  // Create a response recorder
  w := httptest.NewRecorder()

  // Create the service and process the above request.
  r.ServeHTTP(w, req)

  if !f(w) {
    t.Fail()
  }
}

// This function is used to store the main lists into the temporary one
// for testing
func saveLists() {
  tmpArticleList = articleList
}

// This function is used to restore the main lists from the temporary one
func restoreLists() {
  articleList = tmpArticleList
}

 

테스트를 도와주는 helper 함수 몇개를 작성했습니다. 이 함수들은 유사한 기능 테스트를 위한 추가 테스트 코드를 작성할 때 상용구 코드를 줄이는 데에도 도움이됩니다.

 

TestMain함수는 Gin이 테스트 모드를 사용하도록 설정하고 나머지 테스트 함수를 호출합니다. getRouter함수는 기본 애플리케이션과 유사한 방식으로 라우터를 생성/반환합니다. saveLists() 함수는 (original) Article List를 임시 변수에 저장합니다. 임시 변수는 restoreLists() 함수에서 사용되어,  단위 테스트가 실행 된 후 Article List를 테스트 수행 전 초기 상태로 복원하는 역할을 합니다.

 

마지막으로 testHTTPResponse함수는 인자로 전달 된 함수를 실행하여 true/false를 반환하는지 확인합니다.(테스트 성공/실패). 이 함수는 HTTP 요청에 대한 응답을 테스트하는 데 필요한 중복 코드를 방지해줍니다.

 

HTTP 코드와 반환 된 HTML을 확인하기 위해 다음을 수행합니다.

  • 새 router 생성.
  • 메인 앱에서 사용하는 것과 동일한 handler를 사용하는 route 정의( showIndexPage),
  • 이 route에 접근하기 위한 새 request 생성
  • HTTP 코드와 HTML을 테스트하기 위한 응답처리 함수 생성
  • testHTTPResponse() 호출. 단, 새로 생성한 응답처리 함수와 연결.

 

5. Route Handler 생성

handlers.article.go파일에 Article 관련 기능들에 대한 모든 route handler 함수인 showIndexPage를 정의합니다. payload라는 변수를 통해 Article List를 템플릿에 전달하도록 수정하였습니다.

 

handlers.article.go파일

// handlers.article.go

package main

import (
  "net/http"

  "github.com/gin-gonic/gin"
)

func showIndexPage(c *gin.Context) {
  articles := getAllArticles() // 기존에 정의한 getAllArticles 함수를 이용하여 article list 가져오기

  // Call the HTML method of the Context to render a template
  c.HTML(
    // Set the HTTP status to 200 (OK)
    http.StatusOK,
    // Use the index.html template
    "index.html",
    // Pass the data that the page uses
    gin.H{
      "title":   "Home Page",
      "payload": articles,
    },
  )

}

<실행>

 

 

<앱 구성>

 

 

 

 
 
 
 
 

 

 
 
 
 
 
반응형
반응형
package main

import (
	"fmt"
	"image/color"
	_ "unicode/utf8"

	"fyne.io/fyne"
	"fyne.io/fyne/app"
	"fyne.io/fyne/canvas"
	"fyne.io/fyne/layout"
	"fyne.io/fyne/theme"
	"fyne.io/fyne/widget"
)

func main() {
	f := app.New()
	//f.Settings().SetTheme(theme.LightTheme())
	f.Settings().SetTheme(theme.DarkTheme())
	w := f.NewWindow("")

	//상단에 넣을 위젯 및 레이아웃 - NewFormLayout
	qry := widget.NewEntry()
	btn_go := widget.NewButton("New Memo", New_btn)

	text := canvas.NewText("Text Object", color.White)
	text.Alignment = fyne.TextAlignTrailing
	text.TextStyle = fyne.TextStyle{Italic: true}

	ret := fyne.NewContainerWithLayout(layout.NewFormLayout())
	ret.AddObject(btn_go)
	ret.AddObject(qry)

	//하단에 넣을 위젯 및 전체 레이아웃 구성 - NewBorderLayout
	label2 := widget.NewLabel("Simple Memo")
	labox2 := fyne.NewContainerWithLayout(layout.NewCenterLayout(), label2)

	b1 := widget.NewButton("Go1", func() { fmt.Println("Go1 Button") })
	b1.ExtendBaseWidget(b1)

	b2 := widget.NewButton("Go2", func() { fmt.Println("Go2 Button") })
	b2.ExtendBaseWidget(b2)

	out_entry := widget.NewMultiLineEntry()
	out_entry.SetPlaceHolder("결과...")
	out_entry.ExtendBaseWidget(out_entry)

	frm := fyne.NewContainerWithLayout(layout.NewBorderLayout(ret, labox2, nil, nil)) //상, 하, 좌(없음), 우(없음)
	frm.AddObject(ret)                                                                //상단
	frm.AddObject(labox2)                                                             //하단
	frm.AddObject(out_entry)                                                          //좌-우가 없으므로 5번째에(center) 추가됨

	w.SetContent(frm)
	w.Resize(fyne.Size{Height: 640, Width: 480})
	w.ShowAndRun()

}

 

반응형
반응형

 

 

회사에서는 예전에 만들어둔 Visual Basic 6.0을 어쩌지 못해 계속 사용하고 있습니다. 저는 그 유지보수 담당입니다. 다른 언어로 갈아 엎고는 싶지만,,,  온지 얼마 안돼서..아니, 실력이 아직 한참 모자라서 그냥 유지보수 중입니다.

그러나 마음만은 항상 다른 언어로 포팅하려고 준비하고 있습니다. 배포가 편리한 Java를 유력 후보로 생각하고 있는데요..(C# 안사줌..ㅠㅠ)

그 전에 간단한 프로그램 프로토타입 설계를 위해 tkinter를 손대보기로 했습니다.

 

결론은, 필요한 기능 그때그때 불러다 쓸 기본 위젯 종합 선물세트를 만들었습니다.  필요할 때 골라 쓰려구요. 실행하면 이런 gui프로그램이 나오게 될 것입니다.

 

그리고, 소스는 https://076923.github.io/ 사이트를 참조했음을 알려드리며, 개발자분께 감사드립니다. 자세한 모듈 속성에 대한 설명도 해당 사이트에서 확인할 수 있습니다.


import tkinter

window=tkinter.Tk()

#기본 설정
window.title("GUI Sample")
window.geometry("640x640+100+100")  #너비X높이+X좌표+Y좌표
window.resizable(True, True)        #사이즈 변경 가능

#레이블
label_1=tkinter.Label(window, text="위젯 테스트용입니다.", width=20, height=5, fg="red", relief="solid")
label_2=tkinter.Label(window, text="", width=20, height=3, fg="red", relief="solid")

label_1.pack()
label_2.pack()

#버튼
button = tkinter.Button(window, text="hi", overrelief="solid", width=20)
button.pack()


# 엔트리 함수
def calc(event):
    label.config(text="결과=" + str(eval(entry.get())))

#엔트리 입력창
entry=tkinter.Entry(window)
entry.bind("<Return>", calc)
entry.pack()

#리스트박스
listbox=tkinter.Listbox(window, selectmode='extended', height=0)
listbox.insert(0, "no1")
listbox.insert(1, "no2")
listbox.insert(2, "no3")
listbox.insert(3, "no4")
listbox.insert(4, "no5")
listbox.pack()

#체크박스 함수
def flash():
    button.flash()

#체크박스
CheckVariety_1=tkinter.IntVar()
CheckVariety_2=tkinter.IntVar()

checkbutton1=tkinter.Checkbutton(window,text="O", variable=CheckVariety_1, activebackground="blue")
checkbutton2=tkinter.Checkbutton(window, text="Y", variable=CheckVariety_2)
checkbutton3=tkinter.Checkbutton(window, text="X", variable=CheckVariety_2, command=flash)

checkbutton1.pack()
checkbutton2.pack()
checkbutton3.pack()

#라디오버튼
RadioVariety_1=tkinter.IntVar()

#value값이 같을 경우 함께 선택됨
radio1=tkinter.Radiobutton(window, text="1번", value=3, variable=RadioVariety_1)
radio1.pack()
radio2=tkinter.Radiobutton(window, text="2번", value=3, variable=RadioVariety_1)
radio2.pack()
radio3=tkinter.Radiobutton(window, text="3번", value=9, variable=RadioVariety_1)
radio3.pack()

#메뉴
def close():
    window.quit()
    window.destroy()

menubar=tkinter.Menu(window)

menu_1=tkinter.Menu(menubar, tearoff=0)
menu_1.add_command(label="Sub Menu1-1")
menu_1.add_command(label="Sub Menu1-2")
menu_1.add_separator()
menu_1.add_command(label="종료", command=close)
menubar.add_cascade(label="Menu1", menu=menu_1)

menu_2=tkinter.Menu(menubar, tearoff=0, selectcolor="red")
menu_2.add_radiobutton(label="Sub Menu2-1", state="disable")
menu_2.add_radiobutton(label="Sub Menu2-2")
menu_2.add_radiobutton(label="Sub Menu2-3")
menubar.add_cascade(label="Menu2", menu=menu_2)

menu_3=tkinter.Menu(menubar, tearoff=0)
menu_3.add_checkbutton(label="Sub Menu3-1")
menu_3.add_checkbutton(label="Sub Menu3-2")
menu_3.add_checkbutton(label="Sub Menu3-3")
menubar.add_cascade(label="Menu3", menu=menu_3)


#메뉴 버튼
menubutton=tkinter.Menubutton(window,text="Menu Button", relief="raised", direction="right")
menubutton.pack()

menu=tkinter.Menu(menubutton, tearoff=0)
menu.add_command(label="Sub-1")
menu.add_separator()
menu.add_command(label="Sub-2")
menu.add_command(label="Sub-3")

menubutton["menu"]=menu
window.config(menu=menubar)

#배치(place(), pack(), grid())
b1=tkinter.Button(window, text="top")
b1.pack(side="top")
b2=tkinter.Button(window, text="bottom")
b2.pack(side="bottom")
b3=tkinter.Button(window, text="left")
b3.pack(side="left")
b4=tkinter.Button(window, text="right")
b4.pack(side="right")

bb1=tkinter.Button(window, text="(50, 50)")
bb2=tkinter.Button(window, text="(50, 100)")
bb3=tkinter.Button(window, text="(100, 150)")
bb4=tkinter.Button(window, text="(0, 200)")
bb5=tkinter.Button(window, text="(0, 300)")
bb6=tkinter.Button(window, text="(0, 300)")

bb1.place(x=50, y=50)
bb2.place(x=50, y=100, width=50, height=50)
bb3.place(x=100, y=150, bordermode="inside")
bb4.place(x=0, y=200, relwidth=0.5)
bb5.place(x=0, y=300, relx=0.5)
bb6.place(x=0, y=300, relx=0.5, anchor="s")

"""     grid() 는 pack()과 함께 쓰일 수 없음

bbb1=tkinter.Button(window, text="(0,0)")
bbb1.grid(row=0, column=0)
bbb2=tkinter.Button(window, text="(1,1)", width=20)
bbb2.grid(row=1, column=1, columnspan=3)
bbb3=tkinter.Button(window, text="(1,2)")
bbb3.grid(row=1, column=2)
bbb4=tkinter.Button(window, text="(2,3)")
bbb4.grid(row=2, column=3)
"""

window.mainloop()

 

필요하신 분, 가져다가 적극 활용하시기 바랍니다.

감사합니다.^^

 

 

 

 

 

 

 

 

 

 

반응형

+ Recent posts